python printing dictionaries in different order - python-3.x

Below is my code
qas = [
["Apple","Red"],
["Banana", "Yellow"],
["Berries","Blue"]
]
answer_choices = {
"a" : "Red",
"b" : "Yellow",
"c" : "Blue"
}
Answers_count = 0
for qa in qas :
print("Choose from")
for k,v in answer_choices.items() :
print("("+k+") "+" "+v)
ans=input("\nWhat color is "+ qa[0]+" : ")
if answer_choices.get(ans) == qa[1] :
print("Correct \n")
Answers_count += 1
else :
print("Wrong \n")
print("You got "+str(Answers_count)+" correct")
Answers are expected to be printed as (a), (b), (c)
Some how order in which answer choice key value pairs printing is changing with the order of keys in qas.
Please suggest

Python dictionary are not keeping the insertion order of the elements, it's not having a lexicographic ordering as well.
You can try using an OrderedDict in order to keep the insertion order (not lexicographic one).
Another suggestion will be to replace the answer_choices with a list of tuples where the first argument will be the answer key while the seconds one will be the choose.
answer_choices = [("a", "Red"), ("b", "Yellow"), ("c", "Blue")]
for k,v in answer_choices:
print("(" + k + ") " + " " + v)

Related

How do I fix my true/false scoring code so that it can display score properly?

So the trouble I am having is the score not being properly calculated because it should have a minimum score of 0 and maximum score of 5, instead the minimum score is changed to 12, and maximum to 13. The score should be calculated if the inputted number corresponds to the answer bracket stored.
#This is an example of a list
questlist = ["Q1","t", "Q2", "f", "Q3", "t", "Q4","f", "Q5", "t"]
#I want to display each question individually, to be answered then moving on to the next question.
#breaks down the questlist into questions and answers.
newqlist = (questlist[::2])
anslist = (questlist[1::2])
#print (newqlist)
#print (anslist)
score = 0
for i in newqlist:
print (i)
answer = input("Enter 'true' for true, 'false' for false.")
if answer == ("t"):
count += 1
elif answer ==("f"):
count += 1
else:
print("invalid answer")
count += 1
for j in anslist:
if answer == j:
score +=1
print (score)
#gives back the user their score once completed
# if the user gets a question correct, score will be added to a maximum of 5
percentage = ((score/5)* 100)
print ("Your score is " + str(score) + " out of 5 and " + str(percentage) + "%." )
3 things:
Change the loop statement to this: for q, realAns in zip(newqlist, anslist): This basically iterates through a list that has the question and answer paired up into tuples. So for example, the first element looks like: ("Q1", "t")
Change if answer == ("t"): to if answer == realAns. This just checks whether the user's answer matches the real answer.
Under if answer == realAns:, change the count += 1 to score += 1. A score variable doesn't exist in your code, so it would just error out.
Remove the elif answer ==("f"): statement and its corresponding count += 1.
Remove the count += 1 under your else statement.
Remove this section:
for j in anslist:
if answer == j:
score +=1
Since this loop runs every time your answer a question, it'll add the number of times the answer shows up in the answer list 5 times, which probably isn't what you want if you're just counting how many answers the user got right.
Your code after these changes should look something like this:
#This is an example of a list
questlist = ["Q1","t", "Q2", "f", "Q3", "t", "Q4","f", "Q5", "t"]
#I want to display each question individually, to be answered then moving on to the next question.
#breaks down the questlist into questions and answers.
newqlist = (questlist[::2])
anslist = (questlist[1::2])
score = 0
for q, realAns in zip(newqlist, anslist):
print (q)
answer = input("Enter 'true' for true, 'false' for false.")
if answer == realAns:
score += 1
else:
print("incorrect answer")
#gives back the user their score once completed
print (score)
percentage = ((score/5)* 100)
print ("Your score is " + str(score) + " out of 5 and " + str(percentage) + "%." )

Why does my solution to problem 3 of the CodeJam 2020 Qualification Round not work?

I would like to receive help in understanding why my solution to Problem 3 of the Google CodeJam 2020 Qualifier does not work.
Link to problem: https://codingcompetitions.withgoogle.com/codejam/round/000000000019fd27/000000000020bdf9
My solution:
High-level overview:
take input
figure out if the given input is impossible by sorting according to start times and then checking if more than 2 subsequent activities are 'active' at once (which is impossible)
if it is, output accordingly; if it isn't, proceed with the procedure below
arbitrarily assign the first person: in my solution I choose Cameron (C).
next, since we know that a solution exists, and the array I iterate through is sorted according to start times, if the very next activity interval (chronologically) overlaps in its duration with the current, assign it to the person who is not currently busy. This is purely because a solution exists, and it clearly cannot be the current person, so it must be the other.
moreover, if the very next activity interval (chronologically) does not overlap with the current activity, then assign it to the person who is currently busy (because he will not be busy for the next activity)
in addition, quoted directly from the problem's official analysis: "If an assignment is possible, there cannot be any set of three activities that pairwise overlap, so by the contrapositive of the the previous argument, we will be able to assign the activity to at least one of Jamie or Cameron at every step."
At this moment, I believe that these arguments suffice to show that my logic is valid, although my code evidently does not always produce the correct answer. I would greatly appreciate any help on this, since I have spent hours trying to debug, un-reason, or find a counter-example to my code to no avail. I have included my code, for reference, below.
Code:
for p in range(int(input())):
s = int(input())
l = []
for i in range(s):
l.append(list(map(int, list(input().split()))))
unsort = l.copy()
l = sorted(l, key=lambda tup: (tup[0],tup[1]))
enumerated = list(enumerate(unsort))
enumerated.sort(key=lambda x: x[1][0])
impossible = False
endings = sorted([(x[1], False) for x in unsort])
startings = sorted([(x[0], True) for x in unsort])
total = sorted(endings + startings, key=lambda tup: (tup[0], tup[1]))
size = 0
for i in total:
if i[1] == True:
size += 1
else:
size -= 1
if size > 2:
impossible = True
def overlap(a,b):
if not max(a[0], b[0]) >= min(a[1], b[1]):
return True
else:
return False
ans = "C"
def opp(a):
if a == "C":
return "J"
else:
return "C"
if impossible == True:
print("Case #" + str(p+1) + ": " + "IMPOSSIBLE")
else:
for i in range(0, s-1):
if overlap(l[i], l[i+1]) == True:
ans = ans + opp(ans[len(ans)-1])
else:
ans = ans + opp(opp(ans[len(ans)-1]))
#the stuff below is to order the activity assignments according to input order
key_value = [(ans[i], l[i]) for i in range(s)]
fans = ""
for i in range(s):
for j in range(s):
if enumerated[j][0] == i:
fans = fans + key_value[j][0]
print("Case #" + str(p + 1) + ": " + fans)

How to fix python basic math operations returning as address codes?

I created a simple python calculator using functions for basic mathematical operations (eg: divide, add). It runs without errors but it shows some kind of an 'address code' as the final output without showing the actual calculation.
example output:
0x00401978
I was trying to output the calculation as "calculaion = xxx" using print("calculation =" + str(add)).
but as I got these weird outputs, I removed all the strings and tried to output only the calculation. But the problem remained. This is that minimal code-
def add (a,b) :
calc = a + b
return calc
def subs (a,b) :
calc = a - b
return calc
def mul (a,b) :
calc = a * b
return calc
def divi (a,b) :
calc = a/b
return calc
print (" Select operation. \n 1.Add \n 2.Substract \n 3.Multiply \n 4.divide ")
choice = int (input (" Enter choice (1/2/3/4) "))
a = int (input (" Enter first number: "))
b = int (input (" Enter second number : "))
if choice == 1 :
print (add)
elif choice == 2 :
print (subs)
elif choice == 3 :
print (mul)
elif choice == 4 :
print (divi)
else:
print ("Ooops my love. Wrong number")
Full Output with the weird result-
Select operation.
1.Add
2.Substract
3.Multiply
4.divide
Enter choice (1/2/3/4) 2
Enter first number: 20
Enter second number : 10
<function subs at 0x030AE198>
I just need the output to be "Calculation = XXXX" and the operations must be done in functions. (XXXX is the result)
You are not calling the method. You are printing the memory location/repr of the method.
Each of your ifs should be
if choice == 1 :
print (add(a,b))
elif choice == 2 :
print (subs(a,b))
elif choice == 3 :
print (mul(a,b))
elif choice == 4 :
print (divi(a,b))
Or remove the print
if choice == 1 :
add(a,b)
elif choice == 2 :
subs(a,b)
elif choice == 3 :
mul(a,b)
elif choice == 4 :
divi(a,b)
A very simplistic example of what you're doing:
def test_method():
print("I've been called!")
test_method
test_method()

Dictionary: Check if each element of key & value is equal or not

So I've extracted the source of a html and converted everything into a big dictionary.
This is only an example:
d = {fist:mist}
My goal is to compare the characters by their indexes:
(key[0] & value[0], key[1] & value[1], etc.)
and check if the characters are equal:
f != m, i == i, s==s, t==t
The best I could do:
d = {fist:mist}
difference = 0
no_difference = 0
for key, value in d.items():
for char1 in key:
pass
for char2 in value:
pass
if char1 != char2:
difference += 1
if char1 == char2:
no_difference +=1
print(difference)
print(no_difference)
I appreciate any help.
Edit: Big thanks to Glenn Codes, Joe Iddon and Mike Müller!
You need to loop through the key : value pairs in the dictionary. For each pair, you need to work out how many differences there are between the key and the value. This can be done by working out the length of a list that only contains characters which are different.
We then just add this length to a variable outside the loop to keep track of the total.
d = {"fist":"mist"}
differences = 0
for k, v in d.items():
differences += len([i for i,c in enumerate(k) if c != v[i]])
print(differences)
which, for the small example here, gives 1 as the 'f' and 'm' are different.
If you also want a count of the number of characters which matches (i.e. not different), then you can just do the same process but add the length of the key minus the differences to get the number of characters which were the same:
d = {"fist":"mist"}
differences = 0
same = 0
for k, v in d.items():
differences += len([i for i,c in enumerate(k) if c != v[i]])
same += len(k) - differences
print(differences)
print(same)
which again gives differences as 1, but also gives same as 3 (for 'i', 's' and 't').
If you just wanted a boolean (True / False) value for whether there are any differences between any of the pairs, you can do the whole operation in one line:
all(k == v for k,v in d.items())
which gives False in this case.
Assuming key and value will be the same length you can do:
for key, value in d.items():
for i in range(len(key)):
if key[i] == value[i]:
no_difference +=1
else:
difference += 1
Assuming a dictionary with multiple items and possible different lengths of keys and values, this should work:
from itertools import zip_longest
d = {'fist': 'mist', 'fist1': 'mist22', 'x': 'many differences here'}
difference = 0
no_difference = 0
for k, v in d.items():
for item1, item2 in zip_longest(k, v, fillvalue=''):
if item1 == item2:
no_difference += 1
else:
difference += 1
print('difference:', difference)
print('no_difference:', no_difference)
Output:
difference: 25
no_difference: 6

Find and print vowels from a string using a while loop

Study assignment (using python 3):
For a study assignment I need to write a program that prints the indices of all vowels in a string, preferably using a 'while-loop'.
So far I have managed to design a 'for-loop' to get the job done, but I could surely need some help on the 'while-loop'
for-loop solution:
string = input( "Typ in a string: " )
vowels = "a", "e", "i", "o", "u"
indices = ""
for i in string:
if i in vowels:
indices += i
print( indices )
while-loop solution:
string = input( "Typ in a string: " )
vowels = "a", "e", "i", "o", "u"
indices = ""
while i < len( string ):
<code>
i += 1
print( indices )
Would the use 'index()' or 'find()' work here?
Try This :
string = input( "Typ in a string: " )
vowels = ["a", "e", "i", "o", "u"]
higher_bound=1
lower_bound=0
while lower_bound<higher_bound:
convert_str=list(string)
find_vowel=list(set(vowels).intersection(convert_str))
print("Vowels in {} are {}".format(string,"".join(find_vowel)))
lower_bound+=1
You can also set higher_bound to len(string) then it will print result as many times as len of string.
Since this is your Study assignment you should look and practice yourself instead of copy paste. Here is additional info for solution :
In mathematics, the intersection A ∩ B of two sets A and B is the set
that contains all elements of A that also belong to B (or
equivalently, all elements of B that also belong to A), but no other
elements. For explanation of the symbols used in this article, refer
to the table of mathematical symbols.
In python :
The syntax of intersection() in Python is:
A.intersection(*other_sets)
A = {2, 3, 5, 4}
B = {2, 5, 100}
C = {2, 3, 8, 9, 10}
print(B.intersection(A))
print(B.intersection(C))
print(A.intersection(C))
print(C.intersection(A, B))
You can get the character at index x of a string by doing string[x]!
i = 0 # initialise i to 0 here first!
while i < len( string ):
if string[i] in vowels:
indices += str(i)
i += 1
print( indices )
However, is making indices a str really suitable? I don't think so, since you don't have separators between the indices. Is the string "12" mean that there are 2 vowels at index 1 and 2, or one vowel index 12? You can try using a list to store the indices:
indices = []
And you can add i to it by doing:
indices.append(i)
BTW, your for loop solution will print the vowel characters, not the indices.
If you don't want to use lists, you can also add an extra space after each index.
indices += str(I) + " "

Resources