Decided to help out with doing a lab for my buddy, first time ever doing this so please don't make fun of my code lol. I have to get a number "num" of how many numbers to add to array, then a total number. Then from that I want to add user defined numbers from the size of the array. Then if any of those numbers adds up to the total then print them out, else print sorry. Can't understand why it doesn't work :(
EXTRA EDIT: Problem is, my script does not show the numbers that add up to the total value, only the print('sorry')
edit: I learned prior to this java and C, couldn't figure out the foor loops or how variable types are instantiated.
num = int(input('Please enter the amount of numbers you wish to use: '))
total = int(input('Please the total wild card number: '))
hasValue = int(0)
ar = []
i = int(0)
j = int(0)
k = int(0)
l = int(0)
m = int(0)
while (i < num):
j = i + 1
inNum = input('Please enter number %d:' %j)
ar.append(inNum)
i = i + 1
while (k < num):
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
if (hasValue == 0):
print('sorry, there no such pair of values')
As I got it, your current script is looking for two consequent numbers where sum equal to total, but should search for any pair in array, right? So if we have
ar = [1, 2, 3]
and
total = 5
program should display 2, 3 pair. But it will not find 1+3 for total=4.
Here are some general advices:
There is error in print invocation, where pair is printed (string should go first in str+int concatenation). Use format
print('%d, %d'.format(ar[k], ar[k])
or print result as tuple
print(ar[k], ar[l])
Use for k in range(num) instead of while
hasValue is better to be boolean value
Well, here is my solution (python2.7)
num = int(input("Array size: "))
sum = int(input("Search for: "))
a = []
found = False
# Fill array
for i in range(num):
a.append(int(input("Enter number #{}: ".format(i+1))))
# More effective algorithm - does not check same numbers twice
for i in range(num):
for j in range(i+1, num):
if a[i] + a[j] == sum:
print "{}, {}".format(a[i], a[j])
found = True
if not found:
print "Sorry..."
This is how to do for-loops in python:
for x in range(10):
# code for the for loop goes here
This is equivalent to:
for (int x = 0; x < 10; x++) {
// code for the for loop goes here
}
... in C++
(Notice how there is no initializing the variable 'x'. When you do a for loop, python automatically initializes it.
Here is what I think you wish to do:
def main():
num = int(input("Enter the amount of numbers: "))
total = int(input("Enter the total: "))
array = []
counter, elem = 0, 0
for user_numbers in range(num):
array.append(int(input("Please enter number: ")))
for each_element in array:
counter += each_element
elem += 1
if counter == total:
print(array[:elem])
break
if counter != total:
print("sorry...")
main()
while (k < num):
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
Apart from the fact that the loops are not "pythonic", you need to initialize l = 0 within the k loop.
while (k < num):
l = 0
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
or slightly more python way:
for num1 in ar:
for num2 in ar:
if num1+num2==total:
print(num1 +' , '+ num2) # not sure about this syntax. I am a python beginner myself!
hasValue = hasValue + 1
Related
I'm trying to add up all the number from 1 to N and print the result and then keep asking the user to enter number till the number zero is entered. I can make it sum the numbers and end the while but can't make it keep asking for more numbers like this: https://pastebin.com/9pWDT6su
num = int(input('N: '))
sum = 0
while num != 0:
while num < 0:
num = int(input('ERROR - N: '))
sum = sum + num
num = num - 1
print('Sum: ', sum)
# If I put this outside the WHILE it'll work but it won't allow me to
# keep adding numbers
num = int(input('N: '))
print('END')
Try this :
num = int(input('N: '))
while num != 0:
sum=0
while num > 0:
sum = sum + num
num = num - 1
print('Sum: ', sum)
num = int(input('N: '))
print('END')
If you want the sum of 1-n for all numbers remove sum=0 inside while
Try this:
num = int(input('N: '))
sum_ = 0
while True:
if num < 0:
num = int(input('ERROR - N: '))
elif num == 0:
break
else:
sum_ = sum_ + num
print('Sum: ', sum_)
num = int(input('N: '))
I am trying to solve this problem in Python : https://pastebin.com/xjz062uU (Google Kickstart Round A)
Here is the code : https://pastebin.com/fxAg5JUK
Code :
t = int(input())
for i in range(1, t + 1):
number , budget = [int(s) for s in input().split(" ")]
l = input()
l1 = l.split()
l1.sort()
sum = 0
count = 0
for k in range(len(l1)):
sum = sum + int(l1[k])
if (sum> budget):
sum = sum - int(l1[k])
break
else:
count = count + 1
continue
print("Case #{}: {}".format(i,count))
I am getting correct answers on the sample input given but the judge says that my answer is incorrect. I can't seem to find the problem Any help is appreciated, thanks.
If you sort the houses' prices as strings, you'll have problems due to differing lengths of numbers because for example it'll sort an array [9, 12, 1000] as [1000, 12, 9] and will make your program fail on such a case. Instead, you need to do something along the lines of l1 = sorted(list(map(int,input().split()))) to input the list as a list of integers and subsequently sort it.
i = int(input())
num = []
for j in range(i):
l = input()
x , y = l.split()
y = int(y)
m = input()
p =[]
p = m.split(" ")
sum = 0
count = 0
s = []
for w in p:
w = int(w)
s.append(w)
s = sorted(s)
for q in s:
q = int(q)
if sum+q <= y:
sum += q
count+=1
r = count
num.append(r)
i = 0
for op in num:
i +=1
j = "Case #"+str(i)+": "
print(j,end="")
print(op)
TRY USING THIS CODE
Find a Number X whose sum with its digits is equal to N
n = int(input())
for i in range(n//2, n):
z = [int(x) for x in str(i)]
zz = sum(z)
if zz<=100:
ans = int(i) + int(zz)
if(int(i) + int(zz) == n) :
print(i)
tile limit is exceeding
If it can be any number, this would be a fast way to do it.
i = int(input("Your number: "))
result = ""
while i > 9:
result += "9"
i -= 9
result += str(i)
print(result)
How about
for k in range(1000):
if sum([int(i) for i in str(k)]) == k:
print(k)
But there seem to be only very few numbers with that property...
I am trying to list all the factors of a number called count. Whenever I run it, it returns 1. For example: if 6 = count, then what should be returned when calling findFactor(6) is 1 2 3 6. What is returned is 1
divisors = ""
def findFactor(count):
divisors = ""
valueD = 0
for i in range(1, count+1):
valueD = count/i
if isinstance(valueD,int) == True:
divisors = str(valueD)+" "
print divisors
This can be done on one line using list comprehension.
def factorize(num):
return [n for n in range(1, num + 1) if num % n == 0]
You can refer this code:
def find_factor(n):
factor_values = []
for i in range(1, n + 1):
if n % i == 0:
factor_values.append(i)
values = ""
for v in factor_values:
values += str(v) + " "
return values
The function will return 1 2 3 6
First of all, you have an indentation error. print divisors need to be tabbed to inside the for-loop.
divisors = ""
def findFactor(count):
divisors = ""
valueD = 0
for i in range(1, count+1):
valueD = count/i
if isinstance(valueD,int) == True:
divisors = str(valueD)+" "
print divisors
Furthermore like #juanpa.arrivillaga mentioned, your results will vary between Python 2 and Python 3.
However, if you want your divisors to print in the order you want, i.e. start with 1 you need to change your range to for i in range(count,0, -1). You will get multiple 1's , but that's something I'll leave for you to figure out. A little challenge, if you will. ;)
This is the total code I have come up with. Thank you for all the help.
def findFactor(n):
factorValues = []
for i in range(1, n + 1):
if n % i == 0:
factorValues.append(i)
values = ""
for v in factorValues:
values += str(v) + " "
print values.count(" ")
# prints the number of factors
print values
findFactor(21)
It will print the number of factors, and then the factors on the next line.
The answers given so far are all brute force methods.
For n=10000, they will have to iterate ten thousand times.
The following will iterate only 100 times:
def find_factors(n):
factors = []
i = 1
j = n
while True:
if i*j == n:
factors.append(i)
if i == j:
break
factors.append(j)
i += 1
j = n // i
if i > j:
break
return factors
If there were a list of prime numbers available, it could be made even faster.
I am writing this program to find the 13 adjacent digits in this number that, when added together, have the largest sum. When I run it, however, the b value does not start at 12; it starts at some obscenely high number and I cannot figure out why. Any idea why my a and b values are not incrementing correctly?
num = "731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511125069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
a = 0
b = 12
greatest = 0
while b != len(str(num)):
num = str(num)
newNum = num[a:b]
total = 0
for num in newNum:
num = int(num)
total += num
if total > greatest:
greatest = total
a+=1
b+=1
print(b)
print(greatest)
The main issue is that you are reusing num in the inner loop, which renders the "original" num wrong after the first run.
Additionally, if you want a 13 digits run-in, you'd better start with b = 13
And furthermore, there is no need for str(num) since it is already a string, and no need to change b along the program. You can also replace the inner loop with a sum upon map.
Here is what it should look like after these changes:
num = "731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511125069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
index = 0
run_in = 13
greatest = 0
while index + run_in < len(num):
num_slice = num[index: index + run_in]
slice_sum = sum(map(int, num_slice))
if slice_sum > greatest:
greatest = slice_sum
index += 1
print(greatest)
If you are into super functions, you can create the same effect with a list comprehension and a max closure, iterating all possible indexes (until the length of the number minus the run in):
greatest = max(sum(map(int, num[index: index + run_in])) for index in range(len(num) - run_in))
def largest(num, k):
num = str(num)
if len(num) < k: raise ValueError("Need a number with at least {} digits".format(k))
currsum = sum(int(i) for i in num[:k])
answer = currsum, 0
i = k+1
while i < len(num):
currsum -= int(num[i-k])
currsum += int(num[i])
if currsum > answer[0]: answer = currsum, i
i += 1
return answer
total, ind = largest(myNum, 13)
print("The maximum sum of digits is {}, starting at index {}".format(total, ind))