FInding the most frequent number only using for loop - python

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.

Related

How find the minimum number?

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

String of numbers converted to int and added to a list(Optimization issue)

I've managed to make the code work but i believe it could be optimized... a lot.
The input is a string of numbers separated with spaces. Something like - 4 2 8 6 or 1 2 3 4 5 6 7
It has to find which 3 numbers match this condition a + b == c. While 'b' is always on the right side of 'a' and for every time the condition is met print the numbers on the console in the following format - 'a + b == c'. If there isn't a single match print 'No'.
The only restriction is for 'b' to be at least 1 index away from 'a'.
This is what I have come up with.
lineOfNums = input('Line of numbers: ') # User input: example - 4 2 6 8
arrNums = lineOfNums.split()
conMet = False # Is the condition met at least once
for a in range(0, len(arrNums)):
for b in range(a + 1, len(arrNums)):
for c in range(0, len(arrNums)):
if int(arrNums[a]) + int(arrNums[b]) == int(arrNums[c]):
print(f'{arrNums[a]} + {arrNums[b]} == {arrNums[c]}')
conMet = True
if conMet == False: print('No')
You can do it with itertools, first of course convert to int
from itertools import combinations
# Convert to int
arr= [int(i) for i in arrNums]
# Get all the combinations
psums = {sum(i): i for i in combinations(arr, 2)}
# Then loop once
for i, v in enumerate(arr):
if v in psums:
print(f'{psums[v][0]} + {psums[v][1]} == {v}')
The big O for this algorithm is O(n^2) on average, which comes from O(n choose r), where n is the number of inputs (4 in this example) and r is the count of numbers your summing, in this case 2.
First, do the integer conversion once when you create arrNum, not every time through the loops.
arrNum = [int(x) for x in lineOfNums.split()]
The outer loop only needs to go to len(arrNums)-1, since it needs to leave room for B to the right of it.
for a in range(0, len(arrNums)-1):
for b in range(a + 1, len(arrNums)):
for c in range(0, len(arrNums)):
if arrNums[a] + arrNums[b] == arrNums[c]:
print(f'{arrNums[a]} + {arrNums[b]} == {arrNums[c]}')
conMet = True

Adding unique integers

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)

How to access lists elements particular digits in python?

str1= ",".join(str(e) for e in paths)
str2= ",".join(str(e) for e in newlist)
print(str1)
print(str2)
for j in str2:
for i in str1:
if (j[0]==i[0]):
print('number is {}'.format(i))
Hey, I was making program where I needed to to access lists elements particular digits like if one list is [12,23,34] and another is [13,34],I want to access the first elements i.e 12's digits i.e 1 & 2 and compare it with another list and if any equal digit occurs i want to print the first element of the first list.
Like in our example 12 & 13 have 1 as equal digit I want to print 12.I am trying it from several days but getting stuck.And also I tried converting it in string then also some problem arised.
In the above example I am getting the particular digits printed like this:
number is 1
number is 3
number is 3
number is ,
number is ,
number is 1
number is 4
I dont want the 'comma' ,and if a match occurs the number should be printed as mentioned in the example.Any help would be highly appreciated.
Thanks.
Wouldn't keeping them as lists be easier to work with?
If you only want to compare the same indexes, then:
In []:
l1 = [12,23,34]
l2 = [13,34]
for a, b in zip(l1, l2):
if a//10 == b//10:
print(a)
Out[]:
12
Or you want to check any index:
In []:
import itertools as it
l1 = [12,23,34]
l2 = [13,34]
for a, b in it.product(l1, l2):
if a//10 == b//10:
print(a)
Out[]:
12
34
try this
str1= ",".join(str(e) for e in paths)
str2= ",".join(str(e) for e in newlist)
print(str1)
print(str2)
for j in str2:
for i in str1:
if (j[0]==i[0] and (i and j != ',')):
print('number is {}'.format(i))
output
12,23,34
13,34
number is 1
number is 3
number is 3
number is 3
number is 3
number is 4
This should work for your use-case
list1 = [123, 12, 32232, 1231]
list2 = [1232, 23243, 54545]
def find_intersection(list1, list2):
list2_digits = set.union(*[get_digits(x) for x in list2])
for num1 in list1:
digits1 = get_digits(num1)
for num2 in list2:
digits2 = get_digits(num2)
if digits1.intersection(digits2):
print 'Found Match', num1, num2 # We found a match
# Break here unless you want to find all possible matches
def get_digits(num):
d = set()
while num > 0:
d.add(num % 10)
num = num / 10
return d
find_intersection(list1, list2)
I'm not sure I totally understand the question, however:
list1 = [13,23,34]
list2 = [24,18,91]
list1 = list(map(str,list1)) #Map the arrays of ints to arrays of strings
list2 = list(map(str,list2))
for j in list1:
for i in list2:
for character in j:
if character in i:
print(j+' matches with '+i)
break
Prints out:
13 matches with 18
13 matches with 91
23 matches with 24
34 matches with 24

Python - replay values in list

Please help for task with the list in Python my logic is bad works:( .
This is full text of task: Write a program that takes a list of
numbers on one line and displays the values in a single row, are
repeated in it more than once.
To solve the problem can be useful sort method list.
The procedure for withdrawal of repetitive elements may be arbitrary.
My beginning code is :
st = (int(i) for i in input().split())
ls = []
for k in st:
if k == k + 1 and k > 1:
Task is : if we have replay value in list we must print it. We only can use sort() method and without any modules importing.
Results Examples:
Sample Input 1:
4 8 0 3 4 2 0 3
Sample Output 1:
0 3 4
Sample Input 2:
10
Sample Output 2:
Sample Input 3:
1 1 2 2 3 3
Sample Output 3:
1 2 3
This code isn't run( sort() function doesn't want sort my_list. But I must input values like my_list = (int(k) for k in input().split())
st = list(int(k) for k in input())
st.sort()
for i in range(0,len(st)-1):
if st[i] == st[i+1]:
print(str(st[i]), end=" ")
my_list = (int(k) for k in input().split())
After running this line, my_list is a generator, something that will create a sequence - but hasn't yet done so. You can't sort a generator. You either need to use []:
my_list = [int(k) for k in input().split()]
my_list.sort()
which makes my_list into a list from the start, instead of a generator, or:
my_list = list(int(k) for k in input().split()))
my_list.sort()
gather up the results from the generator using list() and then store it in my_list.
Edit: for single digits all together, e.g. 48304, try [int(k) for k in input()]. You can't usefully do this with split().
Edit: for printing the results too many times: make the top of the loop look backwards a number, like this, so if it gets to the second or third number of a repeating number, it skips over and continues on around the loop and doesn't print anything.
for i in range(0,len(st)-1):
if st[i] == st[i-1]:
continue
if st[i] == st[i+1]:
print...
st = (int(i) for i in input().split())
used = []
ls = []
for k in st:
if k in used: # If the number has shown up before:
if k not in used: ls.append(k) # Add the number to the repeats list if it isn't already there
else:
used.append(k) # Add the number to our used list
print ' '.join(ls)
In summary, this method uses two lists at once. One keeps track of numbers that have already shown up, and one keeps track of second-timers. At the end the program prints out the second-timers.
I'd probably make a set to keep track of what you've seen, and start appending to a list to keep track of the repeats.
lst = [num for num in input("prompt ").split()]
s = set()
repeats = []
for num in lst:
if num in s and num not in repeats:
repeats.append(num)
s.add(num)
print ' '.join(map(str,repeats))
Note that if you don't need to maintain order in your output, this is faster:
lst = [num for num in input("prompt ").split()]
s = set()
repeats = set()
for num in lst:
if num in s:
repeats.add(num)
s.add(num)
print ' '.join(map(str, repeats))
Although if you can use imports, there's a couple cool ways to do it.
# Canonically...
from collections import Counter
' '.join([num for num,count in Counter(input().split()).items() if count>1])
# or...
from itertools import groupby
' '.join([num for num,group in groupby(sorted(input().split())) if len(list(group))>1])
# or even...
from itertools import tee
lst = sorted(input('prompt ').split())
cur, nxt = tee(lst)
next(nxt) # consumes the first element, putting it one ahead.
' '.join({cur for (cur,nxt) in zip(cur,nxt) if cur==nxt})
this gives the answers you're looking for, not sure if it's exactly the intended algorithm:
st = (int(i) for i in input().split())
st = [i for i in st]
st.sort()
previous = None
for current in st:
if ((previous is None and current <= 1)
or (previous is not None and current == previous + 1)):
print(current, end=' ')
previous = current
>>> "4 8 0 3 4 2 0 3"
0 3 4
>>> "10"
>>> "1 1 2 2 3 3"
1 2 3
updated to:
start with st = (int(i) for i in input().split())
use only sort method, no other functions or methods... except print (Python3 syntax)
does that fit the rules?

Categories

Resources