def getList(num):
result = []
while num>0:
remain=num%10
if remain >0:
result.append(remain)
elif remain ==0:
result.append(float('inf'))
num /= 10
return result
not_ans = []
for i in range(left, right+1):
for num in getList(i):
if i%num != 0:
not_ans.append(i)
ans = []
for i in range(left, right+1):
if i not in not_ans:
ans.append(i)
return ans
I have always been struggling with how I should write the code and append the result, when all the conditions should be met in for loop. I can only do it with a negative list. Can you guys help me with this? Thank you!
why don't you just append the anses in an else block:
def main():
not_ans = []
ans = []
for i in range(left, right+1):
for num in getList(i):
if i%num != 0:
not_ans.append(i)
else:
ans.append(i)
return ans
Related
I am currently doing an assignment in my intro level CS class and just need a smidge of help.
They are asking me to write a program that reads a list of integers and determines if it has;
multiples of 10
no multiples of 10
mixed values.
It currently correctly outputs everything but mixed values. This is what I have:
n = int(input())
my_list =[]
for i in range(n):
num = int(input())
my_list.append(num)
def is_list_mult10(my_list):
mult10 = True
for i in range(len(my_list)):
if my_list[i] % 10 != 0:
mult10 = False
return mult10
def is_list_no_mult10(my_list):
no_mult10 = True
for i in range(len(my_list)):
if my_list[i] % 10 != 1:
no_mult10 = False
return no_mult10
if is_list_no_mult10(my_list) == True:
print("no multiples of 10")
elif is_list_mult10(my_list) == True:
print("all multiples of 10")
else:
print("mixed values")
def check_multiplier(my_list):
is_10_multiplier = []
for i in my_list:
if i % 10 == 0:
is_10_multiplier.append(True)
else:
is_10_multiplier.append(False)
if sum(is_10_multiplier) == len(my_list):
print("all multiples of 10")
elif sum(is_10_multiplier) == 0:
print("no multiples of 10")
else: print("mixed values")
# tests
mixed = [1, 20, 34, -10]
check_multiplier(mixed)
no_10 = [13, 22, 101, -5]
check_multiplier(no_10)
only_10 = [20, 140, 30, -50]
check_multiplier(only_10)
Function check_multiplier indexing all elements from my_list and saves booleans into is_10_multiplier. Then checks the sum of is_10_multiplier, if all items are True then sum is equal length of passed list, if all are False then sum is 0.
As mentioned in the comments, you have a couple of errors in your code (the return statements are inside the for loop).
Also, the logic seems a little too complicated :) No need to have 2 separate functions, you can try:
n = int(input('How many numbers?: '))
my_list =[]
for i in range(n):
num = int(input(f'Insert element {i}: '))
my_list.append(num)
def how_may_mult10(my_list):
# counting how many multiples of 10 you have in your list
number_of_m10 = 0
for num in my_list:
if num % 10 == 0:
number_of_m10 += 1
return number_of_m10
number_of_m10 = how_may_mult10(my_list)
if number_of_m10 == len(my_list):
print('All multiples of 10')
elif number_of_m10 == 0:
print('No multiples of 10')
else:
print('Mixed values')
I see you have done some logical as well as syntactic error, as mentioned in the comments also.
Below is your modified code :
n = int(input())
my_list =[]
for i in range(n):
num = int(input())
my_list.append(num)
def is_list_mult10(my_list):
mult10 = True
for i in range(len(my_list)):
if my_list[i] % 10 != 0:
mult10 = False
return mult10 #changed here
def is_list_no_mult10(my_list):
no_mult10 = True
for i in range(len(my_list)):
if my_list[i] % 10 == 0: #changed here
no_mult10 = False
return no_mult10 #changed here
if is_list_no_mult10(my_list) == True:
print("no multiples of 10")
elif is_list_mult10(my_list) == True:
print("all multiples of 10")
else:
print("mixed values")
It successfully prints the correct statement. However I'll suggest you to try to optimise e your program.
I was working on a Sudoku solver, and when I ran it, it just didn't work- the function f returned a none type. After debugging, I found out the code didn't solve some of the squares. I don't know why this happened, but I suspect the loop checking all the numbers possible in a square stops after finding one possible number and doesn't check the rest too. Can you please pinpoint me the problem in my code? Thanks.
Note: for empty spaces in the Sudoku, enter 0.
# enter the Sudoku as a two-dimensional array (a[i][j])
def square_check(array, loc_x, loc_y, val):
added_x = loc_x - (loc_x % 3)
added_y = loc_y - (loc_y % 3)
for i in range(3):
for j in range(3):
if i+added_y != loc_y or j+added_x != loc_x:
if array[i+added_y][j+added_x] == val:
return False
return True
def line_check(array, loc_x, loc_y, val):
for i in range(9):
if i != loc_x:
if array[loc_y][i] == val:
return False
return True
def col_check(array, loc_x, loc_y, val):
for i in range(9):
if i != loc_y:
if array[i][loc_x] == val:
return False
return True
def f(array):
flag = True
mark = True
for i in range(0, 9):
for j in range(0, 9):
if array[i][j] == 0:
flag = False
if flag:
return array
for i in range(0, 9):
for j in range(0, 9):
if array[i][j] == 0:
for num in range(1, 10):
if square_check(array, j, i, num):
if col_check(array, j, i, num):
if line_check(array, j, i, num):
new_array = array.copy()
new_array[i][j] = num
mark = False
f(new_array)
if mark:
break
def to_str(array):
for i in range(len(array)):
print(array[i])
print("")
to_str(f(sudoku))
I'm a Python beginner. I'm trying to solve the 3n+1 problem on UVa Online Judge. The program worked fine with the input files. However, I submitted several times but still got Runtime error.
import sys
def compute(i, j):
maxCycleLength = 1
if i <= j/2:
k = j/2+1
else:
k = i
for n in range(k, j+1):
num = n
cycleLength = 1
while (num != 1):
if num%2 != 0:
num = 3*num+1
else:
num = num/2
cycleLength += 1
if cycleLength > maxCycleLength:
maxCycleLength = cycleLength
return maxCycleLength
while True:
nums = sorted(int(x) for x in next(sys.stdin).split())
m = compute(nums[0], nums[1])
print("{} {} {}\n".format(nums[0], nums[1], m))
I have to get userinputs of ints and store them in a array, and print the max number in the list. But I had to create my own max function. Im not sure what steps to take to implement it into my code.
def getInt(prompt):
n = int
done = False
while not done:
try:
n = int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
if n == 0:
done = True
return n
def maxNum(l):
maxi = [0]
for num in l:
if maxi > num:
maxi = num
return maxi
def result():
print("The maxium value is: " + maxNum(i))
def main():
num = []
i = 0
done = False
while not done:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
done = True
results = maxNum(i)
The below code does exactly what you want.
def getInt(prompt):
try:
n = int(input(prompt))
return n
except ValueError:
print("I was expecting a number, please try again...")
getInt()
def maxNum(lst):
if not lst: # if list is empty
return None
max_elem = lst[0]
for x in lst:
if x > max_elem:
max_elem = x
return max_elem
def main():
nums = []
while True:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
break
nums.append(num)
result = maxNum(nums)
print("The maxium value is: " + str(result))
main()
python support built-in max function
max([1,2,3]) # return 3
and Your code is totally wrong.
if you want to input array of integers, getInt may be like this.
def getInt():
array = []
while True:
x = int(input('message'))
if x == 0: break
array.append(x)
return array
and main code will be
array = getInt()
max_value = max(array)
print (max_value)
if you want your own max function, it can be
def max_func(array):
max_val = array[0]
for val in array:
if val > max_val: max_val = val
return max_val
Here is a fixed version of your maxNum function:
def maxNum(l):
if not l:
return None # or return whatever you want if user did not input anything
maxi = l[0] # it expects 'l' to be an array!
for num in l[1:]:
if maxi > num:
maxi = num
return maxi
Let's also fix your getInt function:
def getInt(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
Finally, your "main" function needs the following fix:
def main():
num = []
n = 1
while n != 0:
n = getInt("Please enter an integer < 0 to finish >: ") # store user input into n - do not overwrite num!
num.append(n) # append each user value to the list num
results = maxNum(num) # pass the entire *list* to maxNum
I have a programm, which uses binary search.
And in the end, i need to print a count of loops.
How it would be better to do?
import re
def binarySearch(sumList, whattofind):
a=0
if len(sumList) == 0:
return False
else:
midpoint = len(sumList)/2
if sumList[midpoint]==whattofind:
a=a+1
print(a)
return True
else:
if whattofind<sumList[midpoint]:
a+=1
return binarySearch(sumList[:midpoint],whattofind)
else:
a+=1
return binarySearch(sumList[midpoint+1:],whattofind)
print(a)
result = re.findall(r'\w\w', open("text.txt","r").read())
sumList=[]
for line in result:
sumList.append(ord(line[0])+ord(line[1]))
sumList.sort()
whattofind=int(input('Enter number: '))
print (sumList)
print(binarySearch(sumList, whattofind))
do the following
count = 0
def binarySearch(sumList, whattofind):
global count
count += 1
and at the last line of code just print value of count