I am taking a basic course in Python and have difficulty on solving the following task (NOTE: I can only use FOR loops and IF statements as that is what we have learned so far):
The user has to enter 2*n numbers, where "n" is input from the user.
Then the 1st and 2nd number form a pair as do the 3rd and 4th and so on.
I have to write simple code which compare if all pairs have the same value and if not to calculate the max difference between 2 consequent pairs.
If all pairs have equal value I must print "Yes, value={Value}". If not, I must print "No, maxdiff={Difference}".
Currently I have written the following (which doesn't work):
count_numbers = int(input()) * 2
sum_pair1 = 0
sum_pair2 = 0
result = 0
for i in range(0, count_numbers * 2, 2):
sum_pair1 = int(input()) + int(input())
sum_pair2 = int(input()) + int(input())
if sum_pair1 == sum_pair2:
result = f"Yes, value ={sum_pair1}"
else:
result = f"No, maxdiff={abs(sum_pair1 - sum_pair2)}"
print(result)
Tried writing code but cannot get it right.
I used max_diff to keep track of maximal difference and are_all_equal to tell whether all numbers are equal.
max_diff = 0
last_number = None
are_all_equal = True
# How many numbers would you like to enter?
numbers_count = int(input())
for _ in range(numbers_count):
number1 = int(input())
number2 = int(input())
if are_all_equal:
if number1 == number2:
if last_number and last_number != number1:
are_all_equal = False
last_number = number1
else:
are_all_equal = False
diff = abs(number1 - number2)
if diff > max_diff:
max_diff = diff
if are_all_equal:
print(f"Yes, value = {last_number}")
else:
print(f"No, maxdiff = {max_diff}")
Related
I wrote this code for summing up digits of a number which is bigger than 10 until the result only have one digit and when I try to compile it, it won't even give me an error until I stop it. I want to know what's the problem.
number = input()
#sumed_up_digits = result
result = 0
while len(number) != 1:
for i in number:
int_i = int(i)
result = result + int_i
number = str(result)
print(result)
Try the following code:
s=input()
n=len(s)
result=0
for i in range(n-1):
result=result+int(s[i])
print(result)
This for loop runs from 0th to (n-2)th index of the given string, hence the last digit will not be added to the result. Like for 1245, it will add 1,2 and 4 to result, but not 5.
result is cumulative and include previous sums.
try:
number = input()
#sumed_up_digits = sum
sum = 0
while len(number) != 1:
result = 0
for i in number:
int_i = int(i)
result = result + int_i
sum = sum + result
number = str(result)
print(sum)
You can do it like this:
number = input()
if len(number) <= 1:
print(0)
while len(number) > 1:
number = str(sum(int(i) for i in number))
print(int(number))
Of course, you would need to check that the initial input number is made of digits...
the problem is number isn't being shortened so the condition for the loop to stop is never reached.
number = input()
result = 0
while len(number) != 1:
# set digit to last number
digit = int(number) % 10
result += digit
number = number[:-1]
print(result)
My task is to:
"Write a program that will keep asking the user for some numbers.
If the user hits enter/return without typing anything, the program stops and prints the average of all the numbers that were given. The average should be given to 2 decimal places.
If at any point a 0 is entered, that should not be included in the calculation of the average"
I've been trying for a while, but I can't figure out how to make the programs act on anything I instruct when the user hits 'enter' or for it to ignore the 0.
This is my current code:
count = 0
sum = 0
number = 1
while number >= 0:
number = int(input())
if number == '\n':
print ('hey')
break
if number > 0:
sum = sum + number
count= count + 1
elif number == 0:
count= count + 1
number += 1
avg = str((sum/count))
print('Average is {:.2f}'.format(avg))
You're very close! Almost all of it is perfect!
Here is some more pythonic code, that works.
I've put comments explaining changes:
count = 0
sum = 0
# no longer need to say number = 1
while True: # no need to check for input number >= 0 here
number = input()
if number = '': # user just hit enter key, input left blank
print('hey')
break
if number != 0:
sum += int(number) # same as sum = sum + number
count += 1 # same as count = count + 1
# if number is 0, we don't do anything!
print(f'Average is {count/sum:.2f}') # same as '... {:.2f} ...'.format(count/sum)
Why your code didn't work:
When a user just presses enter instead of typing a number, the input() function doesn't return '\n', rather it returns ''.
I really hope this helps you learn!
Try this:
amount = 0 # Number of non-zero numbers input
nums = 0 # Sum of numbers input
while True:
number = input()
if not number: # Breaks out if nothing is entered
break
if int(number) != 0: # Only add to the variables if the number input is not 0
nums+=int(number)
amount += 1
print(round(nums/amount,2)) # Print out the average rounded to 2 digits
Input:
1
2
3
4
Output:
2.5
Or you can use numpy:
import numpy as np
n = []
while True:
number = input()
if not number: # Breaks out if nothing is entered
break
if int(number) != 0: # Only add to the variables if the number input is not 0
n.append(int(number))
print(round(np.average(n),2)) # Print out the average rounded to 2 digits
A list can store information of the values, number of values and the order of the values.
Try this:
numbers = []
while True:
num = input('Enter number:')
if num == '':
print('Average is', round(sum(numbers)/len(numbers), 2)) # print
numbers = [] # reset
if num != '0' and num != '': numbers.append(int(num)) # add to list
Benefit of this code, it does not break out and runs continuously.
I am trying to use the modulo operator in this function that prints the highest even number in a list, but I always get this error:
TypeError: not all arguments converted during string formatting
Code:
def largest_even():
"""
-------------------------------------------------------
Returns the largest even number.
Use: result = largest_even()
-------------------------------------------------------
Preconditions:
Postconditions:
returns
result - largest even number
-------------------------------------------------------
"""
num = int(input('Enter a number:'))
n_list = []
while num != "":
n_list.append(num)
num = input('Next number:')
print(n_list)
n = 0
e_list = []
while n < len(n_list):
a = (n_list[n]) % 2
if a == 0:
e_list.append(n_list[n])
n = n + 1
print(n)
print(e_list)
if len(e_list) == 0:
result = 'False'
result = e_list[0]
n = 0
while n < len(e_list):
if e_list[n] > result:
result = e_list[n]
print("{} is the largest even number in that list.".format(result))
You only add one number to the list; inside the loop, you are adding strings.
num = input('Enter a number:')
n_list = []
while num != "":
n_list.append(int(num))
num = input('Next number:')
This is a program that has the first input for the number of elements in the input array , the second input is the input array and the third input is the numbers to be counted in the list
num = int(input())
array = input()
lissst = array.split()
lissst = [int(a) for a in lissst]
num_query = int(input())
i = num_query
while i > 0:
queries = int(input())
x = lissst.count(queries)
if x > 0:
print (x)
elif x == 0:
print("NOT PRESENT")
i = i - 1
Input format is as shown below:
6
1 1 1 2 2 0
6
1
2
1
0
3
4
Output layout is as follows:
3
2
3
1
NOT PRESENT
NOT PRESENT
I need to reduce execution time for large inputs, any tips on how to do so for this particular problem?
Slowness probably comes from here:
x = lissst.count(queries)
since list.count has to read the whole list each time.
You can speed it up by putting each number from the input array in a dictionary (number -> how often it appeared in the array). Below I use collections.Counter, which is just a convenient wrapper around dicts:
from collections import Counter
num = int(input())
array = input()
array = [int(a) for a in array.split()]
counter = Counter(array)
i = int(input())
while i > 0:
query = int(input())
x = counter[query]
if x > 0:
print (x)
else:
print("NOT PRESENT")
i -= 1
to answer on the query number faster, you can build a dictionary mapping of number -> count.
when receiving query number, use the dictionary mapping to return the result in O(1) amortized (instead of O(n) of the original naive solution)
build the mapping O(n):
num2count = {}
for i in my_array:
if not i in num2count:
num2count[i] = 1
else:
num2count[i] += 1
answer a query "how many times x in array" O(1) on average
counts = num2count.get(x, 0)
Your code updated
num = int(input())
array = input()
lissst = array.split()
lissst = [int(a) for a in lissst]
num2count = {}
for i in lissst:
if not i in num2count:
num2count[i] = 1
else:
num2count[i] += 1
num_query = int(input())
i = num_query
while i > 0:
queries = int(input())
x = num2count.get(queries, 0)
if x > 0:
print (x)
elif x == 0:
print("NOT PRESENT")
i = i - 1
In addition to the existing answers, you could try Pypy: https://pypy.org
“If you want your code to run faster, you should probably just use PyPy.” — Guido van Rossum (creator of Python)
I am beginner in programming, So can you please tell me what's wrong with my code?
I want to print next palindrome number if the number entered by the user (n) is not palindrome
n = int(input("Enter any number :- "))
reverse = 0
temp = n
while (n!=0):
reverse = reverse * 10
reverse = reverse + n%10
n=n//10
if(temp==reverse):
print ("Already palindrome:: ")
if(temp != reverse):
new_temp = temp
new_reverse = 0
for i in range(new_temp,new_temp+10):
while(temp != 0):
new_reverse = new_reverse * 10
new_reverse = new_reverse + temp%10
temp = temp//10
if(new_temp==new_reverse):
print ("Next pallindrome is :- ",new_temp)
break
if(new_temp != new_reverse):
temp = new_temp+1
There are two problems with your code.
1) Your "for i in range" loop calculates the reverse of the temp variable, but you don't change the temp variable's value.
You do
new_temp = temp
for i in range(new_temp,new_temp+10):
[SNIP]
if(new_temp != new_reverse):
temp = new_temp+1 #this value never changes.
So you're making 10 iterations with one and the same value.
2) Ten iterations might not be enough to find a palindrome. Keep going until you find a palindrome.
Working code:
def reverse(num):
reverse= 0
while num:
reverse= reverse*10 + num%10
num= num//10
return reverse
num= int(input("Enter any number :- "))
if num==reverse(num):
print ("Already palindrome.")
else:
while True:
num+= 1
if num==reverse(num):
print ("Next palindrome is : %s"%num)
break
To check if a number is a palindrome, you don't need to convert it to a number. In fact, its a lot simpler if you just check the string equivalent of your number.
>>> i = '212'
>>> i == i[::-1]
True
>>> i = '210'
>>> i == i[::-1]
False
Use this to your advantage, and create a function:
def is_palindrome(foo):
return str(foo) == str(foo)[::-1]
Next, to find the next palindrome, simply increment the number till your palindrome check is true.
Combine all that, and you have:
def is_palindrome(n):
return str(n) == str(n)[::-1]
n = raw_input('Enter a number: ')
if is_palindrome(n):
print('Congratulations! {0} is a palindrome.'.format(n))
else:
n1 = n
while not is_palindrome(n1):
n1 = int(n1)+1
print('You entered {0}, but the next palindrome is {1}'.format(n, n1))
Here is how it works:
$ python t.py
Enter a number: 123
You entered 123, but the next palindrome is 131
$ python t.py
Enter a number: 121
Congratulations! 121 is a palindrome.
If it helps, I believe it's possible to solve this problem with n/2 iterations where n is the length of the input number. Here's my solution in Python:
def next_palin_number(number):
number+=1
# Convert the number to a list of its digits.
number = list(str(number))
# Initialize two indices for comparing symmetric digits.
i = 0
j = len(number) - 1
while i < j:
# If the digits are different:
if number[i] != number[j]:
# If the lower-power digit is greater than the higher-power digit:
if int(number[j]) > int(number[i]):
if number[j-1]!='9':
number[j - 1] = str(int(number[j - 1]) + 1)
number[j] = number[i]
else:
number = list(str(int(''.join(number[:j]))+1))+number[j:]
else:
number[j] = number[i]
i += 1
j -= 1
# Concatenate and return the result.
return "".join(number)
This problem has a wonderful number of ways to solve them.
One of them is
def nearest_palindrome(number):
#start writitng your code here
while True:
number+=1
if str(number) == str(number)[::-1]:
return number
number=12300
print(nearest_palindrome(number))
Thanks for your time to read my answer : )
I have written this for finding next pallindrome number given a pallindrome number.
def palindrome(num):
bol=False
#x=len(str(num))
num=num+1
while(bol==False):
if(check_palindrome(num)):
bol=True
else:
num=num+1
return num
def check_palindrome(n):
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
return True
b=palindrome(8)
print(b)
def next_palin_drome(n):
while True:
n+=1
if str(n) == str(n)[::-1]:
return n
n=12231
print(next_palin_drome(n))
output:12321
def nearest_palindrome(number):
for i in range(1,number):
number=number+1
tem=str(number)
tem1=tem[-1::-1]
if(tem==tem1):
return number
else:
continue
number=12997979797979797
print(nearest_palindrome(number))
def nearest_palindrome(number):
n = len(str(number))//2
if(len(str(number)) % 2 == 0):
#number like 1221
number_1 = int((str(number))[:n]) #12
number_2 = int((str(number))[n:]) #21
if(number_1 < number_2):
number_1 += 1
number_2 = int(str(number_1)[::-1])
else:
number_2 = int(str(number_1)[::-1])
# if last half part is zero then just reverse the first number
if number_2 == 0:
number_2 = str(number_1)[::-1]
#combining the both parts
ans = int(str(number_1) + str(number_2))
return ans
else:
#numer like 12510 n=2
nu = int((str(number))[:n+1]) #add in this number
number_1 = int((str(number))[:n]) # 12
number_2 = int((str(number))[n+1:]) # 21
if (number_1 < number_2):
nu += 1
number_2 = int((str(nu))[::-1][1:])
else:
number_2 = int((str(nu))[::-1][1:])
#if last half part is zero then just reverse the first number
if number_2 == 0:
number_2 = str(nu)[::-1]
number_2 = number_2[1:]
#combinning both parts
ans = int(str(nu) + str(number_2))
return ans
number=12331
print(nearest_palindrome(number))
If a definite range is given:
# function to check if the number is a palindrome
def palin(x):
s=str(x)
if s==s[::-1]:
return True
else:
return False
n=int(input("Enter the number"))
# Putting up range from the next number till 15 digits
for i in range(n+1,int(10e14)):
if palin(i) is True:
print(i)
break
A brute force method:
def math(n):
while not var:
n += 1
if str(n) == str(n)[::-1] : f = 'but next is : '+str(n); return f
n = int(input()); t = math(n); print('Yes',t) if str(n) == str(n)[::-1] else print('No',t); global var; var = False
This is a good fast solution. I saw that the other solutions were iterating and checking through every +1 they did, but this is really slow for big numbers.
This solution has O(n) time if you look at the length of the number
beginNumber = 123456789101112131415161718 #insert number here for next palidrome
string = str(beginNumber + 1)
length = len(string)
number= [int(x) for x in list(string)]
for i in range(length//2):
if (number[i] != number[length-1-i]):
if (number[i]<number[length-1-i]):
number[length-2-i] += 1
number[length-1-i] = number[i]
print("".join([str(x) for x in number]))
I have written this for finding next pallindrome number given a pallindrome number..
#given a pallindrome number ..find next pallindrome number
input=999
inputstr=str(input)
inputstr=inputstr
#append 0 in beginning and end of string ..in case like 99 or 9999
inputstr='0'+inputstr+'0'
length=len(inputstr)
halflength=length/2;
#if even length
if(length%2==0):
#take left part and reverse it(which is equal as the right part )
temp=inputstr[:length/2]
temp=temp[::-1]
#take right part of the string ,move towards lsb from msb..If msb is 9 turn it to zero and move ahead
for j,i in enumerate(temp):
#if number is not 9 then increment it and end loop
if(i!="9"):
substi=int(i)+1
temp=temp[:j]+str(substi)+temp[j+1:]
break;
else:
temp=temp[:j]+"0"+temp[j+1:]
#now you have right hand side...mirror it and append left and right part
output=temp[::-1]+temp
#if the length is odd
if(length%2!=0 ):
#take the left part with the mid number(if length is 5 take 3 digits
temp=inputstr[:halflength+1]
#reverse it
temp=temp[::-1]
#apply same algoritm as in above
#if 9 then make it 0 and move on
#else increment number and break the loop
for j,i in enumerate(temp):
if(i!="9"):
substi=int(i)+1
temp=temp[:j]+str(substi)+temp[j+1:]
break;
else:
temp=temp[:j]+"0"+temp[j+1:]
#now the msb is the middle element so skip it and copy the rest
temp2=temp[1:]
#this is the right part mirror it to get left part then left+middle+right isoutput
temp2=temp2[::-1]
output=temp2+temp
print(output)
similarly for this problem take the left part of given number ...reverse it..store it in temp
inputstr=str(number)
if(inputstr==inputstr[::-1])
print("Pallindrome")
else:
temp=inputstr[:length/2]
temp=temp[::-1]
for j,i in enumerate(temp):
if(i!="9"):
substi=int(i)+1
temp=temp[:j]+str(substi)+temp[j+1:]
break;
else:
temp=temp[:j]+"0"+temp[j+1:]
now depending on length of your number odd or even generate the output..as in the code
if even then output=temp[::-1]+temp
if odd then temp2=temp1[1:]
output=temp2[::-1]+temp
I am not sure about this solution..but hope it helps