Lucky Number counting - python

I'm trying to make a lucky number counter where if there is a number containing either a 6 or an 8 between the two inputs the number is lucky, but if there's both a 6 and an 8 the number is unlucky. I'm having an issue where it's double-counting numbers, like 66, 88, etc., and not calling unlucky numbers like 68, 86, etc. Please help fast :\
l, h = [int(x) for x in input().split()]
count = 0
for i in range(l,h+1):
i = str(i)
for j in range(len(i)):
if i[j] == '6' or i[j] == '8':
count += 1
print(count)

Try this:
import sys
temp1 = ""
while len(temp1) != 2:
temp1 = input("Enter 2 digits: ")
try:
temp2 = int(temp1)
except ValueError:
print("You did not enter valid input")
sys.exit(1)
lucky = False
if "6" in temp1:
lucky = True
if "8" in temp1:
lucky = True
if ("6" in temp1) and ("8" in temp1):
lucky = False
print("Lucky number: "+str(lucky))

Something like this, probably:
number = ''
while len(number) != 2 or any(ch not in '0123456789' for ch in number):
number = input('Enter a 2-digit positive integer:')
print(f'{number} is {"lucky" if ("6" in number) != ("8" in number) else "not lucky"}')
# or, if you meant to say "exactly one 6 or 8":
print(f'{number} is {"lucky" if len([ch for ch in number if ch in "68"]) == 1 else "not lucky"}')

You could try using the count() method for Strings:
numbers = input().split(' ')
count = 0
for num in numbers:
if num.count('6') > 0:
if num.count('8') > 0:
continue
else:
count += 1
elif num.count('8') > 0:
count += 1
print(count)

this, while not as elegant or efficient, seems to be the correct code for the implied question
l, h = [int(x) for x in input().split()]
count = 0
for i in range(l,h+1):
i = str(i)
if ('6' in i and '8' in i):
continue
if i.count('6') > 0 or i.count('8') > 0:
count += 1
print(count)

Related

How do I keep a loop going with a variable that changes in every loop

So I'm new to coding and I'm struggling with the following exercise
So we start with a random number and we have to count the even numbers and the odd numbers. With this, we make a second number that starts with the amount of the even numbers, amount of the odd numbers, and the amount of numbers in total. We should continue this until the number 123 is reached.
For example:
number = 567421 --> odd numbers = 3 , even numbers = 3 , total numbers = 6 --> new number = 336 -->...
I had an idea to write it like this:
number = input()
evennumbers = ''
oddnumbers = ''
a = len(number)
while number != '123':
for i in str(number):
if int(i) % 2 == 0:
evennumbers += i
else:
oddnumbers += i
b = len(evennumbers)
c = len(oddnumbers)
number = input(print(f"{b}{c}{a}"))
But I have no idea how to keep this loop going with the variable 'number' until 123 is reached
You need your variable initialization to be inside the while loop, and remove the input(print(... on the final line.
number = '567421'
while number != '123':
print(number)
evennumbers = ''
oddnumbers = ''
a = len(number)
for i in str(number):
if int(i) % 2 == 0:
evennumbers += i
else:
oddnumbers += i
b = len(evennumbers)
c = len(oddnumbers)
number = f"{b}{c}{a}"
You could simplify like this:
while number != '123':
print(number)
total = len(number)
odds = sum(int(digit) % 2 for digit in number)
evens = total - odds
number = f"{evens}{odds}{total}"

I'm trying to write a condition on the python list

I tried writing a Python program to accept a list of integers starting with 0 and ending with 20 from the user. Each integer of the said list either differs from the previous one by two or is four times the previous one. Return true or false
Can someone correct the condition which I have written
lst = []
n = int(input("Enter the no of elements in the list :"))
for i in range (0,n):
elem = int(input("Enter the elements between 0 and 20 : "))
lst.append(elem)
if elem >= 0 and elem <=20:
print(lst)
for i in elem:
if (i+1) >= 2(i) or 4(i+1) == i:
print(True)
else:
print(False)
You can use zip to pair up items with their successors. This will let you compare them and check your condition using any() or all() depending on your requirement:
if any(abs(a-b)==2 or a*4==b for a,b in zip(lst,lst[1:]):
print(True) # at least one number pair meets the criteria
else:
print(False)
or
if all(abs(a-b)==2 or a*4==b for a,b in zip(lst,lst[1:]):
print(True) # all numbers meets the criteria
else:
print(False)
arr_len = int(input("Input a length for list: "))
nums = [0] * arr_len
res = [False] * arr_len
for i in range(len(nums)):
num = -1
while not(num >= 0 and num <= 20):
num = input("Enter the elements between 0 and 20 : ")
num = nums[i] = int(num)
if num >= 0 and num <= 20:
print('appended')
else:
print('that number is not between 0 and 20')
for i in range(1, len(res)):
num = nums[i]
prev_num = nums[i-1]
if abs(num-prev_num) == 2 or prev_num == 4*num:
res[i] = True
for i in range(len(nums)):
print('i is: ', i, 'nums[i], ', nums[i],
', is allowed in array: ', res[i])
res = dict(zip(nums, res))
print(res)

Counter in for loop always prints 0

I need to check if a number is Lychrel number and if not to print the number of times the loop did until it got to the palindrome, for some reason it always print 0
num = input('please enter your number ')
num = int(num)
count = 0
for i in range(1, 500):
if str(num) == str(num)[::-1]:
print(count)
exit()
else:
num = num + int(str(num)[::-1])
count += 1
print('True')
update: thanks to Vova the code is now working.
fixed code:
num = int(input('please enter your number '))
count = 0
for i in range(1, 500):
if str(num) == str(num)[::-1]:
print(count)
exit()
else:
num = num + int(str(num)[::-1])
count += 1
print('True')
It will print 0 each time when you type 1 numeric number(0..9)
When you type more than 1 numeric not mirror number for example 2,3,4 etc(10,234 etc), it will print 1
Moreover it will never print True, coz you exit() it in if statement
Try to input 23, it will print 1:
num = int(input('please enter your number '))
count = 0
for i in range(1, 500):
if str(num) == str(num)[::-1]:
print(count)
exit()
else:
num = num + int(str(num)[::-1])
count += 1
print('True')

The Next Palindrome number

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

sum of the product of even positioned digits

I have attempted this problem like this :
a = input("Enter number : ")
s = 3
w = 1
while a>0:
digit=a%10
if n%2 == 0:
p = p*digit
else:
s = s+digit
a=a/10
n=n+1
print "The sum is",s
it works perfectly for even no of digits but for odd no of digits like for 234 it shows the sum as 6 and product 3
No explicit loop:
import operator
from functools import reduce # in Python 3 reduce is part of functools
a = input("Enter number : ")
lst = [int(digit) for digit in a]
add = sum(lst[1::2])
mul = reduce(operator.mul, lst[::2],1)
print("add =",add,"mul =",mul,"result =",add+mul)
Producing:
Enter number : 234
add = 3 mul = 8 result = 11
You have to start with n = 0 for this to work
a = int(input("Enter number"))
s = 0
p = 1
n = 0
while a>0:
digit=a%10
if n%2 == 0:
p *= digit
else:
s += digit
a /= 10
n += 1
print "The sum is",s
print "Product is",p
Easy mistake to make about the numbering. The first item of any string, list or array is always index 0. For example, be careful in future to take away 1 from the value returned from len(list) if you are iterating through a list's items with a for loop e.g.
for x in range(len(list)-1):
#your code using list[x]
Here's the mathematical version:
n = input('Enter a number: ')
digits = []
while n > 0:
digits.append(n%10)
n //= 10
s = 0
p = 1
i = 0
for digit in reversed(digits):
if i%2 == 0:
s += digit
else:
p *= digit
i += 1
print 'Sum of even digits:', s
print 'Product of odd digits:', p
print 'Answer:', s+p
I have tried to make this as simple as possible for you.
Here's a function that does the same thing:
def foo(n):
s = 0
p = 1
for i, digit in enumerate(str(n)):
if i%2 == 0:
s += digit
else:
p *= digit
return s+p
def foo(num):
lst = [int(digit) for digit in str(num)]
mul, add = 1, 0
for idx, val in enumerate(lst):
if not idx % 2:
mul *= val
else:
add += val
return add, mul
And using it:
>>> foo(1234)
(6, 3)
>>> foo(234)
(3, 8)
This function will take an integer or a string representation of an integer and split it into a list of ints. It will then use enumerate to iterate over the list and preform the required operations. It returns a 2 element tuple.

Categories