Write a Python program that reads an integer that gives the number of integers to be read and then reads these integers, one per line, into a list. Print the total of these integers except that if an integer appears more than once it will not be counted.
You may not use the count method of lists. For example, the input:
• 5 1 2 3 4 5 would give 15;
• 5 1 2 3 4 2 would give 8;
• 5 1 2 1 4 2 would give 4; and
• 5 2 2 2 2 2 would give 0.
My code works but is a little hard to read, anyways to so simply this without imports?
xs = [int(input()) for i in range(int(input()))]
print(sum([xs[i] for i in range(len(xs)) \ if xs[i] not in xs[:i] + xs[i + 1:]]))
Split the counting and summing steps. Do one pass over the list to determine the unique elements, then another to sum them.
from collections import Counter
def sum_unique(inputs):
counts = Counter(inputs)
return sum(num for num, count in counts.items() if count == 1)
xs = [int(input()) for i in range(int(input()))]
print(sum_unique(xs))
Edit: Sorry, I didn't see "without imports". You can make a regular dict act like a Counter, it's just not as pretty.
def sum_unique(inputs):
counts = {}
for x in inputs:
counts[x] = counts.get(x, 0) + 1
return sum(num for num, count in counts.items() if count == 1)
Related
I have this task I need to complete:
"There are N athletes competing in a hammer throw. Each of them made M
throws. The athlete with the highest best throw wins. If there are
several of them, then the one with the best sum of results for all
attempts wins. If there are several of them, the athlete with the
minimum number is considered the winner. Determine the number of the winner of the competition."
I can find highest best throw wins, but I can't find the athlete with the minimum number.
Sample Input:
4 3
4 2 7
1 2 7
1 3 5
4 1 6
Sample Output:
1
My code so far:
row,columns = map(int,input().split())
matrix = [[int(i) for i in input().split()] for j in range(row)]
numbers = []
suma = []
for i in range(row):
numbers.append(matrix[i][0])
sumaa = sum(matrix[i]) - matrix[i][0]
suma.append(sumaa)
new_matrix = [numbers,suma]
print(new_matrix.index(max(new_matrix)))
input = """4 3
4 2 7
1 2 7
1 3 5
4 1 6
"""
def winner(input):
athletes = input.split("\n")
best_throw = max(" ".join(athletes).split(" "))
best_total = max(map(lambda s: sum(list(map(lambda n: int(n) if n != '' else 0, s.split(" ")))), athletes))
best_athletes_indexes = []
for i, athlete in enumerate(athletes):
if best_throw in athlete.split(" ") and sum(map(int, athlete.split(" "))) == best_total:
best_athletes_indexes.append(i)
best_athletes_attempts = list(map(lambda i: len(athletes[i].split(" ")), best_athletes_indexes))
return best_athletes_indexes[best_athletes_attempts.index(min(best_athletes_attempts))]
print(winner(input))
please please please do not ask me to explain this this is the first python i hav written in 2 years. i come from a world of type safety wth
my search history is literally "remove item from list python" the python standard library is strange
It's answer
a = []
b = []
row, columns = map(int, input().split())
for i in range(row):
a.append(list(map(int, input().split())))
for i in range(row):
b.append([max(a[i]), sum(a[i])])
print(b.index(max(b)))
Try this code:
row, columns = map(int, input().split())
matrix = [list(map(int, input().split())) for _ in range(row)]
matrix_max_sum_elms = [[max(row), sum(row)] for row in matrix]
best_athlete_ind = matrix_max_sum_elms.index(max(matrix_max_sum_elms)) + 1
print(best_athlete_ind)
Explanation:
First, we create a list of lists with an input value,
then we create a new list of lists, in which each list contains the maximum value and the sum of the elements of the input values. As a result, we take the index of the list that contains the maximum value and add 1, since indexing starts from 0
I know there are multiple questions asked reguarding finding the most frequent numbers and how many times they have been repeated. However, I have a problem that requires to sole the question only using for loop, if, etc.
I'm not allowed to use .count, dic, arrary or any other fancy functions.
My_list=[1,1,1,1,1,1,1,1,2,2,2,3,4,5,6,6,7,7,8,7,8,8,8,8,8,8,8]
The answer that is required to print would be
1, 8times 8, 8times
I know it may be a pain to use only for loop, but it's killing me and i'm craving for hlep :(
There are a lot of questions that exist will practice iterative and list. I do not think so this is a good practice. For your pain, I thought to provide you a little bit of a messy answer (messy means a lot of use of variables).
You have not mentioned length of your list. Therefore, I have created this code to work with any range.
Code with comments
My_list=[1,1,1,1,1,1,1,1,2,2,2,3,4,5,6,6,7,7,8,7,8,8,8,8,8,8,8]
list1 = []
list2 = []
list3 = []
c = 0
k = 1
y = 1
while y == 1: # Use while loop until all objects read and store in another lists
for i in My_list: # read oblectsa in My_list one by one
if i == k:
list1.append(k) # append all same digits into list1
list2.append(len(list1)) # Get the length of list1 that have same digits and store it in list2
list3.append(list1[0]) # Get the first value of list1 that have same digits and store it in list2
list1 = [] # Reset the list one for store next same digits
k = k + 1
if k == My_list[-1] + 1: # get the value of last digit of the list
y = 0
m = 0
for j in list2: # use this for loop to get final outcome
print(m, ",", j, "times", list3[m], ",", j, "times")
m = m + 1
Code without comments
My_list=[1,1,1,1,1,1,1,1,2,2,2,3,4,5,6,6,7,7,8,7,8,8,8,8,8,8,8]
list1 = []
list2 = []
list3 = []
c = 0
k = 1
y = 1
while y == 1:
for i in My_list:
if i == k:
list1.append(k)
list2.append(len(list1))
list3.append(list1[0])
list1 = []
k = k + 1
if k == My_list[-1] + 1:
y = 0
m = 0
for j in list2:
print(m, ",", j, "times", list3[m], ",", j, "times")
m = m + 1
Output -:
0 , 8 times 1 , 8 times
1 , 3 times 2 , 3 times
2 , 1 times 3 , 1 times
3 , 1 times 4 , 1 times
4 , 1 times 5 , 1 times
5 , 2 times 6 , 2 times
6 , 3 times 7 , 3 times
7 , 8 times 8 , 8 times
Note -:
You can use print(list2) and print(list3) end of the code to see what happens. And also try to understand the code by deleting part by part.
Disclaimer: I'm a relatively new python user and programmer in general.
I am building a class for a deck of cards, and for the __str__ method I want to return the ascii symbols for cards currently in the deck as thirteen rows of four columns. Later, I will need similar logic when displaying players' hands when I actually use this class for a game. I'm hoping to find a way to do this where the number of columns is variable, and the number of rows is dependent upon the number of columns and the length of the list (or put plainly, just stops when out of cards). This way it will work for my __str__ return with 4 columns, and with a player's hand at a variable number of columns.
Since I'm only wanting to understand the logic to do this, I've simplified the issue down to the code below. I've done quite a bit of research, but I haven't found an example of this that I can understand or that doesn't use imported libraries. I've learned to use a comma after a print statement to prevent forcing a new line, but even with that tool I cannot find a way to make this work using for and while loops. I will also paste some code from my final use case. It is only an example of many that haven't worked, and it's probably hideous, but it's where I'm at.
Simplified use case:
# Each string in each list below would actually be one line of ascii art for
# the whole card, an example would be '|{v} {s} |'
deck = [['1','2','3','4'],
['5','6','7','8'],
['9','10','11','12'],
['a','b','c','d'],
['e','f','g','h'],
['i','j','k','l']]
# expected output in 3 columns:
#
# 1 5 9
# 2 6 10
# 3 7 11
# 4 8 12
#
# a e i
# b f j
# c g k
# d h l
#
# expected output in 4 columns:
#
# 1 5 9 a
# 2 6 10 b
# 3 7 11 c
# 4 8 12 d
#
# e i
# f j
# g k
# h l
End use case:
def __str__(self):
# WORKS empty list to hold ascii strings
built_deck = []
# WORKS fill the list with ascii strings [card1,card2,card3,card4...]
for card in self.deck:
built_deck.append(self.build_card(str(card[0]),str(card[1:])))
# WORKS transform the list to [allCardsRow1,allCardsRow2,allCardsRow3,allCardsRow4...]
built_deck = list(zip(*built_deck))
# mark first column as position
position = 1
# initialize position to beginning of deck
card = 0
# Try to print the table of cards ***FAILURE***
for item in built_deck:
while position <= 4:
print(f'{item[card]}\t',)
card += 1
continue
position = 1
print(f'{item[card]}')
card += 1
#return built_deck
The trick is here to realize that what you are doing it taking successive transposes of the matrix of your cards and printing them where the size of the matrix you preform the operation on is the number of items you want to be displayed. We can get a transpose using zip in python.
def display(deck, number_of_columns):
col = 0
while col < len(deck):
temp = deck[col:col+number_of_columns]
temp = zip(*temp)
for x in temp:
for y in x:
print(y, end=" ")
print()
col += number_of_columns
display(deck, 3)
print()
display(deck, 4)
Output
1 5 9
2 6 10
3 7 11
4 8 12
a e i
b f j
c g k
d h l
1 5 9 a
2 6 10 b
3 7 11 c
4 8 12 d
e i
f j
g k
h l
I have a 2-D 6x6 array, A.
I want its values to be input by the user in the following format or example:
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
where the 0's indicate the places where the user would write their values.
This is my code. It returns an error in split().
def arr_input(x):
for i in range(6):
for j in range(6):
n = int(input().split(' '))
if n>=-9 and n<=9:
x[i][j] = n
print "\n"
I don't want input in a single line. Please help!
EDIT 1
The code I needed was already provided :D. Nevertheless, I learned something new and helpful. Here is the existing code to do the task I wanted:
arr = []
for arr_i in xrange(6):
arr_temp = map(int,raw_input().strip().split(' '))
arr.append(arr_temp)
First of all, you are using input() which returns int when you enter numbers in terminal. You should use raw_input() and get it line by line.
Second, you are trying to convert a list to integer, you should loop through the list values, convert and insert on the resulting list.
Fixed code:
def arr_input(x):
for i in range(6):
num_list = raw_input().split(' ')
for j, str_num in enumerate(num_list):
n = int(str_num)
if n >= -9 and n <= 9:
x[i][j] = n
print "\n"
Here, I used enumerate() to loop though the number list by getting its index each iteration.
There's an inconsistency in how you're treating the input. In python 2.7, the input() function is designed to read one, and only one, argument from stdin.
I'm not exactly sure which way you're trying to read the input in. The nested for loop suggests that you're trying to read the values in one by one, but the split suggests that you're doing it line by line. To cover all bases, I'll explain both cases. At least one of them will be relevant.
Case 1:
Let's say you've been inputting the values one by one, i.e.
1
4
9
4
...
In this case, what's happening is that the input() function is automatically parsing the inputs as integers, and when you try running split() on an integer there's a type error. Python is expecting a string and you're providing an int. That's going to break. There's an easy solution--this can be fixed by simply replacing that line with
n = input()
Case 2: Let's say you're inputing the numbers line by line, as strings. By this, I mean something like:
"1 3 4 5 7 9"
"4 1 8 2 5 1"
...
What's occurring here is that int(...) is trying to cast a list of strings into an integer. That will clearly break the code. A possible solution would be to restructure the code by gett rid of the inner for loop. Something like this should work:
def arr_input(arr):
for i in range(6):
s = input()
nums_s = s.split(' ')
nums = [int(x) for x in nums_s]
arr.append(nums)
print "\n"
return arr
# Usage
a = []
print(a)
a = arr_input(a)
print(a)
Give this one-liner a try:
def arr_input(N=6):
print 'Enter %d by %d array, one row per line (elements separated by blanks)' % (N, N)
return [[n if abs(n)<=9 else 0 for n in map(int, raw_input().split())] for i in range(N)]
The following interactive session demonstrates its usage:
>>> A = arr_input(3)
Enter 3 by 3 array, one row per line (elements separated by blanks)
1 2 -3
4 5 -6
8 9 10
>>> A
[[1, 2, -3], [4, 5, -6], [8, 9, 0]]
I'm a few weeks into learning python and I am trying to write a script that takes an input of any length of numbers and splits them in one-character lengths. like this:
input:
123456
output:
1 2 3 4 5 6
I need to do this without using strings, and preferably using divmod...
something like this:
s = int(input("enter numbers you want to split:"))
while s > 0:
s, remainder = divmod(s, 10)
I'm not sure how to get the spacing right.
Thank you for the help.
As your priority is to use divmod, you can do it like this:
lst=[]
while s>0:
s, remainder = divmod(s, 10)
lst.append(remainder)
for i in reversed(lst):
print i,
Output:
enter numbers you want to split:123456
1 2 3 4 5 6
You can use join() to achieve that. Cast to string if your are using python 2.*
s = input("enter numbers you want to split:")
s= str(s)
digitlist=list(s)
print " ".join(digitlist)
In case, you are in need of integers, just do it.
intDigitlist=map(int,digitlist)
What about the following using the remainder:
s = 123456
output = []
while s > 0:
s, r = divmod(s, 10)
output.append(r)
fmt='{:<12d}'*len(output)
print fmt.format(*output[::-1])
Output:
1 2 3 4 5 6
This also uses some other useful Python stuff: the list of digits can be reversed (output[::-1]) and formatted into 12-character fields, with the digit aligned on the left ({:<12d}).
Try it with mod:
while x > 0:
x = input
y = x % 10
//add y to list of numbers
x = (int) x / 10
e.g. if x is 123:
123 % 10 is 3 -> you save 3.
the Integer value of 123 / 10 is 12.
Then 12 % 10 is 2 -> you save 2
Int of 12 / 10 is 1.
1 % 10 = 1 -> you save 1
Now you have all numbers. You can invert the list after that to have it like you want.
You can iterate over Python string amd use String.join() to get result:
>>>' '.join(str(input("Enter numbers you want to split: ")))
Enter numbers you want to split: 12345
1 2 3 4 5