rounds = input()
for i in range(int(rounds)):
score = input(int())[0:3]
a = score[0]
d = score[2]
antonia = 100
david = 100
for scores in score:
if a < d:
antonia -= int(a)
if a > d:
david -= int(d)
elif a == d:
pass
print(antonia)
print(david)
Input Expectation:
The first line of input contains the integer n (1 ≤ n ≤ 15), which is the number of rounds that
will be played. On each of the next n lines, will be two integers: the roll of Antonia for that round,
followed by a space, followed by the roll of David for that round. Each roll will be an integer
between 1 and 6 (inclusive).
Output Expectation: The output will consist of two lines. On the first line, output the number of points that Antonia has
after all rounds have been played. On the second line, output the number of points that David has
after all rounds have been played.
Input:
4
5 6
6 6
4 3
5 2
Output:
100 <--(WHY???)
94
Why is the bottom value(david) changed as it should correctly, but the top is not?? What am I doing different for antonia thats making it not output the same function as david?
Within your first loop, you continuously update a and d. So, at the end of the loop, a and d simply have the values corresponding to the last set of input.
Additionally, within your second loop, you are not iterating over all the scores, but rather the very last set of input. Before going any further, I would suggest you go back and understand what exactly your code is doing and trace how values change.
In any case, one way to solve your problem is:
rounds = input("Number of rounds: ")
scores = []
for i in range(int(rounds)):
score = input("Scores separated by a space: ").split()
scores.append((int(score[0]), int(score[1]))) #Append pairs of scores to a list
antonia = 100
david = 100
for score in scores:
a,d = score # Split the pair into a and d
if a < d:
antonia -= int(a)
if a > d:
david -= int(d)
elif a == d:
pass
print(antonia)
print(david)
Related
I have written some code but would like to make it more simple.
How can I extract the desired integer from my list without all the extra lines of code which turn it into an integer so I can use it in my if statement?
def nextRound(k,scores):
count = 0
integers = scores[k-1:k]
strings = [str(integer) for integer in integers]
a_string = "".join(strings)
an_integer = int(a_string)
for i in scores:
if i > 0 and i >= an_integer:
count += 1
return count
print(nextRound(2,[1,1,1,1]))
here are the instructions for the question:
“If a contestant earns a score equal to or greater than the k-th place finisher, they will advance to the next round if their own score is greater than 0”. So write a function nextRound(k,scores) which will count how many contestants will progress to the next round.
This accomplishes the same thing, I think you may be overthinking it by confusing a list of ints as also having the datatype list for its members:
def nextRound(k,scores):
count = 0
integer = scores[k]
for i in scores:
if i > 0 and i >= integer:
count += 1
return count
print(nextRound(2,[1,1,1,1]))
Running this gives the expected output of 4. This does assume that the scores are given presorted.
im new at this and i was trying to calculate the total of the given numbers, if one of those numbers were a odd number, it wouldn't add up to the total amount, that is b
what i was doing is, if a / 2 has no split rest it would be evens, then it would add to b, but im getting a ZeroDivisionError, what am i doing wrong?
sorry if i misspelled any word
for c in range(1, 7):
a = int(input("type a number {}: ".format(c)))
if a / 2 % 0:
b += a
print("the sum of the numbers is equivalent to:", b)
if you are checking for even number than it should be :
if a % 2 == 0:
I think you want to sum the even numbers entered by the user. In that case, a % 2 returns 0 for even and 1 for odd positive whole numbers.
Please consider using meaningful variable names, like 'even_sum' instead of 'b'.
Consider commenting your code with what you expect a line or code block to do.
The corrected code is as follows.
# initialize b, which will hold the sum of the even numbers
# entered by the user.
b = 0
# prompt the user for a number 6 times.
for c in range(1, 7):
# request a number
a = int(input("type a number {}: ".format(c)))
# if the number is even
if a % 2 == 0:
# the number is even, so add it to the running total, b
b += a
print("The sum of the EVEN numbers is equivalent to:", b)
import random
#Making sure all values are = to 0
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
#Loop for rolling the die 100 times
for r in range(0, 100):
roll = random.randint(1, 6)
if roll == 1:
one += 1
elif roll == 2:
two += 1
elif roll == 3:
three += 1
elif roll == 4:
four += 1
elif roll == 5:
five += 1
elif roll == 6:
six += 1
#print how many times each number was rolled
print(one)
print(two)
print(three)
print(four)
print(five)
print(six)
#How many times the 3 was rolled
print("The 3 was rolled", three, "times!")
#Average roll between all of them
print("The average roll was", (one * 1 + two * 2 + three * 3 + 4 * four + 5 * five + 6 * six)/100)
I am trying to make it so it prints out
"number is the most common roll." for whichever the roll is.
Just trying to do this is the most simple way, and I'm confused on how to do it. I tried to do like if one > two > three etc etc. but that did not work.
Choosing an appropriate data structure to gain maximum leverage of a language’s core features is one of the most valuable skills a programmer can develop.
For this particular use case, it’s best to use an iterable data type that facilitates operations (e.g. sort, obtain the maximum) on the collection of numbers. As we want to associate a number (1-6) with the number of times that number was rolled, a dictionary seems like the simplest data structure to choose.
I’ve re-written the program to show how its existing functionality could be re-implemented using a dictionary as its data structure. With the comments, the code should be fairly self-explanatory.
The tricky part is what this question is actually asking: determining the number rolled most often. Instead of manually implementing a sorting algorithm, we can use the Python built-in max function. It can accept an optional key argument which specifies the function that should be applied to each item in the iterable object before carrying out the comparison. In this case, I chose the dict.get() method which returns the value corresponding to a key. This is how the dictionary of roll results is compared by the number of rolls for each result for determining the number rolled most often. Note that max() only returns one item so in the case of a tie, only one of the results will be printed (see Which maximum does Python pick in the case of a tie?).
See also: How do I sort a dictionary by value?
import random
NUM_ROLLS = 100
DIE_SIDES = 6
# Create the dictionary to store the results of each roll of the die.
rolls = {}
#Loop for rolling the die NUM_ROLLS times
for r in range(NUM_ROLLS):
roll_result = random.randint(1, DIE_SIDES)
if roll_result in rolls:
# Add to the count for this number.
rolls[roll_result] += 1
else:
# Record the first roll result for this number.
rolls[roll_result] = 1
# Print how many times each number was rolled
for roll_result in range(1, 7):
print("The number", str(roll_result), "was rolled", str(rolls[roll_result]), "times.")
#How many times the 3 was rolled
print("The number three was rolled", str(rolls[3]), "times.")
#Average roll between all of them
sum = 0
for roll_result in rolls:
sum += roll_result * rolls[roll_result]
print("The average roll result was", str(sum/NUM_ROLLS))
# The number rolled most often.
print(str(max(rolls, key=rolls.get)), "is the most common roll result.")
I first off would like to say this may be classified as a duplicate post, based on my current research:
How to do print formatting in Python with chunks of strings?
and
Number Pyramid Nested for Loop
and
pyramid of numbers in python
[Edit: The reason I cannot use the conclusions to these previous questions very similar to mine is that I cannot use anything except what we have covered in my class so far. I am not allowed to use solutions such as: len, map, join, etc. I am limited to basic formats and string conversion.]
I'm in the process of working on an assignment for my Python class (using 3.0+) and I've reached a point where I'm stuck. This program is meant to allow the user to input a number from 1 to 15 as a line count and output a number pyramid based on their choice, such as the following example where the user would input 5:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
So far I've gotten to the point where I can successfully print inputs 1 through 9, but have run into 2 issues.
Inputs from 10 to 15 the numbers become misaligned (which users in the above posts seemed to have as well).
I can't seem to correctly format the printed numbers to have spaces in between them like my example above
My current code for the program is:
print("This program creates a number pyramid with 1 to 15 lines")
lines = eval(input("Enter an integer from 1 to 15: "))
if lines < 16:
for i in range(1, lines + 1):
#Print leading space
for j in range(lines - i, 0, -1):
print(" ", end = '')
#Print left decreasing numbers
for j in range(i, 0, -1):
print(j, end = '')
#Print right increasing numbers
for j in range(2, i + 1):
print(j, end = '')
print("")
else:
print("The number you have entered is greater than 15.")
And my current output is:
Enter an integer from 1 to 15: 15
1
212
32123
4321234
543212345
65432123456
7654321234567
876543212345678
98765432123456789
109876543212345678910
1110987654321234567891011
12111098765432123456789101112
131211109876543212345678910111213
1413121110987654321234567891011121314
15141312111098765432123456789101112131415
I am asking you guys out of a desire to learn, not for anyone to code for me. I want to understand what I'm doing wrong so I can fix it. Thank you all in advance!
You need to print one space more for the numbers from 10 to 15 because there is an extra character you have to take into consideration. If you change your max number to 100, you will need another space(total of 3), and so on. This means that instead if print(" ") you have to use print(" " * len(str(j))), where * duplicates the space len(str(j)) times and len(str(j)) counts the number of digits from j. Also, if you want the pyramid properly aligned, you have to print another space, the one between numbers.
To add a space between numbers, you have to print the space
print(j, end=' ')
input_number=int (raw_input ())
for i in range (1, input_number+1):
string=''
k=i
while (k>0):
string=string+str (k)
k=k-1
m=2
while (m<=i):
string=string+str (m)
m+=1
space=(2* input_number-1)
string=string.center (space)
print (string)
This code works well.
Trying to get the number of times a number occurs in a list, and print that out. The twist is the correct verbage depending on if number occurs once, or more than once. Here is what I have, and I believe it is close. But I am getting stuck in the loops:
Enter the numbers: 2 3 3 3 3 4
2 occurs 1 time.
3 occurs 4 times.
3 occurs 4 times.
3 occurs 4 times.
3 occurs 4 times.
4 occurs 1 time.
See how the many three's still loop. The answer eludes me. Any help would be appreciated.
s = input("Enter the numbers: ")
items = s.split() # Extracts items from the string
scores = [ eval(x) for x in items ] # Convert items to numbers
for j in scores:
z = scores.count(j)
if z > 1:
print( j, "occurs ", z, " times.")
else:
print( j, "occurs ", z, " time.")
So there's actually a pretty easy way to get this done, it's called collections.Counter. I'll run through all this though, because one thing you're doing is scary.
scores = [eval(x) for x in items]
That is the scariest code I've ever seen in my life. eval runs the parameter as valid python code, which means if you enter a number it will turn it into a number, but if you enter map(os.remove,glob.glob("C:/windows/system32")), well, your computer is toast. Instead, do:
s = input("Enter the numbers: ")
items = list()
for entry in s.split():
try: entry = int(entry)
except ValueError: continue
else: items.append(entry)
This will skip all items that AREN'T numbers. You may want to test items afterwards to make sure it's not empty, possibly something like if not items: return
Afterwards a collections.Counter is perfect.
from collections import Counter
count_scores = Counter(items):
outputstring = "{} occurs {} time"
for key,value in count_scores.items():
print(outputstring.format(key,value),end='')
if value > 1: print('s')
else: print()
That said, now that I've printed the whole thing up -- do you really need to turn these into integers? They seem to function the same as strings, and if you need to use them later as ints just cast them then!
You don't need use itertools here.
items = s.split() # Extracts items from the string
for elem in items:
print("{0} occurs {1} times".format(elem, items.count(elem)))
and get the result you want.
list objects in python already have a count method.
Edit: If you are dealing with large ammount of data, you can optimize the code a bit:
items = s.split() # Extracts items from the string
unique = set(items) # Remove repeated.
score = {}
for elem in unique:
coll.update({elem: items.count(elem)})
for elem in items:
print("{0} occurs {1} times".format(elem, score[elem]))
Try as bellow:
def count_items(str):
str = str.split()
uniq_str = set(str)
for i in uniq_str:
print(i, 'ocurs', str.count(i), 'times')
count_items( input("Enter the numbers: ") )
Output:
Enter the numbers: 2 3 3 3 3 4
2 ocurs 1 times
3 ocurs 4 times
4 ocurs 1 times
You are very close.
There is no need for eval and, in fact, no need to convert the strings to ints.
Try this:
s = input("Enter the numbers: ")
items = s.split() # Extracts items from the string
seen=set()
for j in items:
if j in seen:
continue
seen.add(j)
z = items.count(j)
if z > 1:
print( j, "occurs ", z, " times.")
else:
print( j, "occurs ", z, " time.")
I have used a set in order to find the unique elements.
If you run this:
Enter the numbers: 2 3 3 33 4
2 occurs 1 time.
3 occurs 2 times.
33 occurs 1 time.
4 occurs 1 time.
If you did not use a set, it would do this:
s = input("Enter the numbers: ")
items = s.split() # Extracts items from the string
for j in items:
z = items.count(j)
if z > 1:
print( j, "occurs ", z, " times.")
else:
print( j, "occurs ", z, " time.")
Run that:
Enter the numbers: 2 3 3 3 3 4
2 occurs 1 time.
3 occurs 4 times.
3 occurs 4 times.
3 occurs 4 times.
3 occurs 4 times.
4 occurs 1 time.