how would I delete item's in a dictionary within specific parameters? - dictionary

for my code I want all numbers from a dictionary under 70 to be deleted, I'm unsure of how to specify this and I need it to also delete the associated name with that number as well, either that or only diplay numbers that are 70 or above.
Below is the code that I have in it's entirety:
name = []
number =[]
name_grade = {}
counter = 0
counter_bool= True
num_loop = True
while counter_bool:
stu = int(input("please enter the number of students: "))
if stu < 2:
print("value is too low, try again")
continue
else:
break
while counter != stu:
name_inp = str(input("Enter your name: "))
while num_loop:
number_inp = int(input("Enter your number: "))
if number_inp < 0 or number_inp > 100:
print("The value is too high or too low, please enter a number between 0 and 100.")
continue
else:
break
name_grade[name_inp] = number_inp
name.append(name_inp)
number.append(number_inp)
counter += 1
print(name_grade)
sorted_numbers = sorted(name_grade.items(), key= lambda x:x[1])
print(sorted_numbers)
if number > 70:
resorted_numbers = number < 70
print(resorted numbers)
how would I go about this?
Also if it's also not too much trouble could someone explain in detail about dictionary keys and how the lambda function I've used works? I got help but I would prefer to know the small details on how it's applied and formatted but don't worry if it's a pain to explain.

You can just iterate over the dictionary and filter for values less than 70:
resorted_numbers = {k:v for k,v in name_grade.items() if v<70}
dict.items method returns a list of key-value tuple pairs of a dictionary, so the lambda function is telling the sorted function to sort by the second element in each tuple.

Related

How to take user input and insert it into an array?

New to Julia, trying to simply ask the user to choose 5 numbers and put it into an array and print the array. My output only says pick 5 numbers with "nothing" followed underneath. I cant seem to figure out why it wont read my inputs.
function ask()
lst = []
i = 0
println("pick 5 numbers to add to a list")
while i < 5
choice = readline
choice = push!(lst, choice);
i += 1
end
end
println(ask())
You were assigning function reference to list elements rather than calling the function.
This should be:
function ask()
lst = String[]
i = 0
println("pick 5 numbers to add to a list")
while i < 5
choice = readline()
choice = push!(lst, choice);
i += 1
end
lst
end
If you want numbers rather than Strings the last line could be parse.(Int, lst) or you could add this conversion near readline
Note that if you do not plan to introduce some error checking etc. this all code could be simply written as:
println("pick 5 numbers to add to a list")
lst = [parse(Int, readline()) for _ in 1:5]

Python 3.6 user-defined board size win check with 2 variables

I have somewhat a general question for more experienced programmers. I'm somewhat new to programming, but still enjoy it quite a bit. I've been working with Python, and decided to try to program a tic tac toe game, but with variable board size that can be decided by the user (all the way up to a 26x26 board). Here's what I've got so far:
print("""Welcome to tic tac toe!
You will begin by determining who goes first;
Player 2 will decide on the board size, from 3 to 26.
Depending on the size of the board, you will have to
get a certain amount of your symbol (X/O) in a row to win.
To place symbols on the board, input their coordinates;
letter first, then number (e.g. a2, g10, or f18).
That's it for the rules. Good luck!\n""")
while True:
ready = input("Are you ready? When you are, input 'yes'.")
if ready.lower() == 'yes': break
def printboard(n, board):
print() #print board in ranks of n length; n given later
boardbyrnk = [board[ind:ind+n] for ind in range(0,n**2,n)]
for rank in range(n):
rn = f"{n-rank:02d}" #pads with a 0 if rank number < 10
print(f"{rn}|{'|'.join(boardbyrnk[rank])}|") #with rank#'s
print(" ",end="") #files at bottom of board
for file in range(97,n+97): print(" "+chr(file), end="")
print()
def sqindex(prompt, n, board, syms): #takes input & returns index
#ss is a list/array of all possible square names
ss = [chr(r+97)+str(f+1) for r in range(n) for f in range(n)]
while True: #all bugs will cause input to be taken for same turn
sq = input(prompt)
if not(sq in ss): print("Square doesn't exist!"); continue
#the index is found by multiplying rank and adding file #'s
index = n*(n-int(sq[1:])) + ord(sq[0])-97
if board[index] in syms: #ensure it contains ' '
print("The square must be empty!"); continue
return index
def checkwin(n, w, board, sm): #TODO
#check rows, columns and diagonals in terms of n and w;
#presumably return True if each case is met
return False
ps = ["Player 1", "Player 2"]; syms = ['X', 'O']
#determines number of symbols in a row needed to win later on
c = {3:[3,3],4:[4,6],5:[7,13],6:[14,18],7:[19,24],8:[25,26]}
goagain = True
while goagain:
#decide on board size
while True:
try: n=int(input(f"\n{ps[1]}, how long is the board side? "))
except ValueError: print("Has to be an integer!"); continue
if not(2<n<27): print("Has to be from 3 to 26."); continue
break
board = (n**2)*" " #can be rewritten around a square's index
for num in c:
if c[num][0] <= n <= c[num][1]: w = num; break
print(f"You'll have to get {w} symbols in a row to win.")
for tn in range(n**2): #tn%2 = 0 or 1, determining turn order
printboard(n, board)
pt = ps[tn%2]
sm = syms[tn%2]
prompt = f"{pt}, where do you place your {sm}? "
idx = sqindex(prompt, n, board, syms)
#the index found in the function is used to split the board string
board = board[:idx] + sm + board[idx+1:]
if checkwin(n, w, board, sm):
printboard(n, board); print('\n' + pt + ' wins!!\n\n')
break
if board.count(" ") == 0:
printboard(n, board); print("\nIt's a draw!")
while True: #replay y/n; board size can be redetermined
rstorq = input("Will you play again? Input 'yes' or 'no': ")
if rstorq in ['yes', 'no']:
if rstorq == 'no': goagain = False
break
else: print("Please only input lowercase 'yes' or 'no'.")
print("Thanks for playing!")
So my question to those who know what they're doing is how they would recommend determining whether the current player has won (obviously I have to check in terms of w for all cases, but how to program it well?). It's the only part of the program that doesn't work yet. Thanks!
You can get the size of the board from the board variable (assuming a square board).
def winning_line(line, symbol):
return all(cell == symbol for cell in line)
def diag(board):
return (board[i][i] for i in range(len(board)))
def checkwin(board, symbol):
if any(winning_line(row, symbol) for row in board):
return True
transpose = list(zip(*board))
if any(winning_line(column, symbol) for column in transpose):
return True
return any(winning_line(diag(layout), symbol) for layout in (board, transpose))
zip(*board) is a nice way to get the transpose of your board. If you imagine your original board list as a list of rows, the transpose will be a list of columns.

GAE - When adding two floats whose sum is over 1000, the sum is changed to the thousands value

This was an administrative issue. It was claimed that it was our fault, and our code was broken, when the issue was elsewhere in different code that can update what ours imports. So, this is a non-problem.
We are adding to values together that are in a dictionary and storing them in a variable to then be added to the NDB datastore.
Essentially, we are importing a csv and parsing the data. If the sum of two of the values is greater than 1,000.00, the float is changed to the thousands value.
Examples:
1263.13 would change to 1
51367.42 would change to 51
218.12 would be unchanged (218.12)
We think it is an issue with storing the data, but we are having trouble reproducing the the issue, and have verified that with a small amount of data, there will be "false positives". IE: there not being an issue.
Reading csv from blob:
blob_reader = blobstore.BlobReader(blob_info.key())
raw_blob = blob_reader.read()
result = [row for row in csv.DictReader(StringIO.StringIO(raw_blob), delimiter=',')]
# loop through all rows in the data/csv
for v, row in enumerate(result):
if set_data_type(row, v) == False:
return False
else:
length = len(result) + 1
# check values for type
if check_values(row, v, length) == False:
return False
else:
# calculate numerical data for storage
calculate_vars(row, v)
if not error_log:
# if no errors, store the row in the datastore
store_data(row, v)
# if there are no errors, add to transaction log.
if not error_log:
added_records = len(result)
old_new = "Upload Success - " + str(added_records) + " records added."
transactions(module, 'Datastore', data[0], 'CSV Bulk Upload', old_new, old_new)
Calculating values:
def calculate_vars(row, v):
# calcuate values for storage based on
# data passed from the csv
try:
float_sum = float(row['float1']) + float(row['float2'])
except Exception, e:
catch_error(["Value calculation error in row ", v+1, " Error: ", e])
return False
else:
# global var
calculated_val = float_sum
Storing Value:
def store_data(row, v):
try:
entry = Datastore(
float_sum = calculated_val
)
except Exception, e:
catch_error(["StoreDataError in row ", v, e])
return False
else:
# add entry to datastore.
entry.put()
The Datastore column 'float_sum' is an ndb.FloatProperty()
What we're trying to figure out is: what could cause the floats to be truncated to the thousands digits and nothing else when the number is larger than 1,000. Obviously, we are aware that adding two floats together will not cause this normally, which is why we think it could be an issue with the datastore itself.

Python 3.4 help - using slicing to replace characters in a string

Say I have a string.
"poop"
I want to change "poop" to "peep".
In fact, I also want all of the o's in poop to change to e's for any word I put in.
Here's my attempt to do the above.
def getword():
x = (input("Please enter a word."))
return x
def main():
y = getword()
for i in range (len(y)):
if y[i] == "o":
y = y[:i] + "e"
print (y)
main()
As you can see, when you run it, it doesn't amount to what I want. Here is my expected output.
Enter a word.
>>> brother
brether
Something like this. I need to do it using slicing. I just don't know how.
Please keep your answer simple, since I'm somewhat new to Python. Thanks!
This uses slicing (but keep in mind that slicing is not the best way to do it):
def f(s):
for x in range(len(s)):
if s[x] == 'o':
s = s[:x]+'e'+s[x+1:]
return s
Strings in python are non-mutable, which means that you can't just swap out letters in a string, you would need to create a whole new string and concatenate letters on one-by-one
def getword():
x = (input("Please enter a word."))
return x
def main():
y = getword()
output = ''
for i in range(len(y)):
if y[i] == "o":
output = output + 'e'
else:
output = output + y[i]
print(output)
main()
I'll help you this once, but you should know that stack overflow is not a homework help site. You should be figuring these things out on your own to get the full educational experience.
EDIT
Using slicing, I suppose you could do:
def getword():
x = (input("Please enter a word."))
return x
def main():
y = getword()
output = '' # String variable to hold the output string. Starts empty
slice_start = 0 # Keeps track of what we have already added to the output. Starts at 0
for i in range(len(y) - 1): # Scan through all but the last character
if y[i] == "o": # If character is 'o'
output = output + y[slice_start:i] + 'e' # then add all the previous characters to the output string, and an e character to replace the o
slice_start = i + 1 # Increment the index to start the slice at to be the letter immediately after the 'o'
output = output + y[slice_start:-1] # Add the rest of the characters to output string from the last occurrence of an 'o' to the end of the string
if y[-1] == 'o': # We still haven't checked the last character, so check if its an 'o'
output = output + 'e' # If it is, add an 'e' instead to output
else:
output = output + y[-1] # Otherwise just add the character as-is
print(output)
main()
Comments should explain what is going on. I'm not sure if this is the most efficient or best way to do it (which really shouldn't matter, since slicing is a terribly inefficient way to do this anyways), just the first thing I hacked together that uses slicing.
EDIT Yeah... Ourous's solution is much more elegant
Can slicing even be used in this situation??
The only probable solution I think would work, as MirekE stated, is y.replace("o","e").

function variable does not live outside a for loop

I have a generic function in julia that the aim is to say if a member of a vector of
a given dimension is negative or not. After a few variations I have:
function any(vec)
dim = size(vec)
for i in 1:dim[2]
fflag = vec[1,i] < 0
println("Inside any, fflag = ", fflag)
if fflag == true
result = 0
println("blabla ", result)
break
else
result =1
println("blabla ", result)
continue
end
end
println("hey, what is result? ")
println(result)
return result
end
If I run a test I found the following result:
Inside any, fflag = false
blabla 1
Inside any, fflag = false
blabla 1
Inside any, fflag = false
blabla 1
hey, what is result?
result not defined
at In[7]:57
I don't know why the compiler says me that 'result' is not defined. I know the variable exist but why does not live outside the for loop?
The documentation on variable scoping clearly states that a for loop defines a new scope. This means result is going out of scope when execution leaves the for loop. Hence it is undefined when you call println(result)
Defining result in advance of the for loop should give the behaviour you are expecting:
function any(vec)
dim = size(vec)
result = -1
for i in 1:dim[2]
...
Or if you do not wish to assign a default value, and are sure the for loop will set its value, you can do:
function any(vec)
dim = size(vec)
local result
for i in 1:dim[2]
...
In the first example, if the for loop does not set a value, result will be -1.
In the the second example, not setting a value in the for loop will leave result undefined.

Resources