My aim: Two inputs will be given.
purchase date and number on plate.
My code should add all numbers of purchase date till single digit is reached and compare it with the similar addition of plate number.
If the both the numbers turn out to be same , it should return lucky otherwise it should display dare.
This is what I tried:
def lucky_dare():
input1=input("enter ; ")
input2=input("enter:")
s=str(input1)
p1=int(s[0])
p2=int(s[1])
p3=int(s[2])
sty=[]
ma=max([p1,p2,p3])
while ma>0:
if p1>0 and p2>0 and p3>0:
sty.append(input1)
elif p1<1 and p2<0 and p3>0:
sty.append(int(s[2]))
elif p1<1 and p2>0 and p3<1:
sty.append(int(s[1]+"0"))
elif p1<1 and p2>0 and p3>0:
sty.append(int(s[1]+s[2]))
elif p1>0 and p2<1 and p3<1:
sty.append(int(s[0]+"0"+"0"))
elif p1>0 and p2<1 and p3>0:
sty.append(int(s[0]+"0"+s[2]))
elif p1>0 and p2>0 and p3<1:
sty.append(int(s[0]+s[1]+"0"))
else:
pass
p1-=1
p2-=1
p3-=1
ma-=1
print(sum(sty))
lucky_dare()
But I am getting several errors. So I couldn't display what errors I got here. Where am I going wrong? Can someone please help. Thanks in advance for your time and help:)
Here is a nicer, simpler and cleaner way to solve your problem:
import re
def recursive_sum(text):
while (len(text) > 1):
numbers = re.findall(r'\d', text)
_sum = sum(map(int, numbers))
text = str(_sum)
return text
def luck_dare():
input1= input("enter ; ")
input2=input("enter:")
return recursive_sum(input1) == recursive_sum(input2)
I don't really understand your code, but it can be done much simpler. Here is my attempt, but it can still be optimized:
def lucky_dare():
dop = sum([int(i) for i in input("enter date of purchase: ").split('/')])
# 23/05/1998
while dop > 9:
dop = sum([int(i) for i in str(dop)])
pn = int(input("enter plate number: ")) # 2345
while pn > 9:
pn = sum([int(i) for i in str(pn)])
print('lucky' if dop == pn else 'dare')
# print(dop, pn)
lucky_dare()
def lucky_dare():
input1=input("enter date: ")
input2=input("enter car number:")
# Evaluating date
s = input1.split('/')
a = [int(num) for num in s]
b = sum(a)
c = [int(i) for i in str(b)]
d=(sum(c))
single_digit_dt = str(d)[0]
# Evaluating car number
y = [int(num) for num in input2]
x= sum(y)
single_digit_platenumber =str(x)[0]
# Comparing both the numbers
print(single_digit_dt, single_digit_platenumber)
if single_digit_dt ==single_digit_platenumber:
print('Lucky')
else:
print('Dare')
lucky_dare()
Related
I am looking to see if any 2 indices add up to the inputed target number, and print the combination and index location of the respective pair. I honestly am not too sure how to approach this, my first reaction was using a for loop but due to inexperience i couldn't quite figure it out.
def length():
global lst_length
break_loop = False
while break_loop == False:
lst_length = int(input("Enter the length: "))
if lst_length >= 10 or lst_length <= 2:
print("Invalid list")
elif lst_length >= 2 and lst_length <= 10:
print('This list contains', lst_length, 'entries')
break_loop == True
break
def entries():
i = 0
x = 0
global lst
lst = []
while i < lst_length:
number = float(input("Enter the entry at index {0}:".format(x)))
if i < 0:
print('Invalid entry')
else:
lst = []
lst.append(number)
i += 1
x += 1
def target():
target_num = int(input("Enter the target number: "))
length()
entries()
target()
If I understand your question correctly, you want the user to insert numbers, and when finally two numbers match the wanted result, print them?
well, my code is pretty basic, and it gets the job done, please let me know if you meant something else.
for indices, I suppose you can fill in the gaps.
def check(wanted):
numbers_saved = []
checking = True
while checking:
x = float(input("enter a number: "))
if x < 0:
print("only numbers bigger than 0")
else:
for num in numbers_saved:
if num + x == wanted:
print(num, x)
checking = False
return
numbers_saved.append(x)
I'm making a piece of code that moves the first digit of a user-inputted number to the back of the number (ex. 125 to 251), and I want it to display all the possible combinations of this. (ex. if I enter 125, then it will display 251, 512, and 125). I tried using the while - if function (python's version of a repeat until function), but this just make the program stop after displaying only one number (ex. i entered 125 and it gave 251 before stopping). Here's my code:
n = 1
num = input("number: ")
while n == 1:
length = len(num)
intnum = int(num)
intnum2 = intnum
x = int(intnum2 // 10**(length-1))
s = (intnum2 - x*(10**(length-1)))
l = s*10
final = (l+x)
print(final)
final = intnum2
if final == intnum:
break
else:
print("Done")
If anyone could help that would be greatly appreciated!
If you're ok with using your number as a string, here's a shorter way. Just append the first character to the end of the rest of the characters repeatedly
num = input("number: ")
for _ in range(len(num)):
num = num[1:]+num[0]
print(num)
print('Done')
Are you looking for something like this?
import itertools
num = input("number: ")
perms = [''.join(combs) for combs in itertools.permutations(num)]
print(perms)
input
number: 153
output
['153', '135', '513', '531', '315', '351']
Recently I created a 24 game solver with python
Read this website if you do not know what the 24 game is:
https://www.pagat.com/adders/24.html
Here is the code:
from itertools import permutations, product, chain, zip_longest
from fractions import Fraction as F
solutions = []
def ask4():
num1 = input("Enter First Number: ")
num2 = input("Enter Second Number: ")
num3 = input("Enter Third Number: ")
num4 = input("Enter Fourth Number: ")
digits = [num1, num2, num3, num4]
return list(digits)
def solve(digits, solutions):
digit_length = len(digits)
expr_length = 2 * digit_length - 1
digit_perm = sorted(set(permutations(digits)))
op_comb = list(product('+-*/', repeat=digit_length-1))
brackets = ([()] + [(x,y)
for x in range(0, expr_length, 2)
for y in range(x+4, expr_length+2, 2)
if (x,y) != (0,expr_length+1)]
+ [(0, 3+1, 4+2, 7+3)])
for d in digit_perm:
for ops in op_comb:
if '/' in ops:
d2 = [('F(%s)' % i) for i in d]
else:
d2 = d
ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))
for b in brackets:
exp = ex[::]
for insert_point, bracket in zip(b, '()'*(len(b)//2)):
exp.insert(insert_point, bracket)
txt = ''.join(exp)
try:
num = eval(txt)
except ZeroDivisionError:
continue
if num == 24:
if '/' in ops:
exp = [(term if not term.startswith('F(') else term[2])
for term in exp]
ans = ' '.join(exp).rstrip()
print("Solution found:", ans)
solutions.extend(ans)
return ans
print("No solution found for:", ' '.join(digits))
def main():
digits = ask4()
solve(digits, solutions)
print(len(solutions))
print("Bye")
main()
Right now, my code only shows one solution for the numbers given, even when there are clearly more solutions.
So if someone knows how to do this please help me
Thanks
You're not allowing the code to finish it's task before all of the solutions have been calculated and listed. Better to save the solutions in a list/array instead of returning it straight away.
Your function is returning as soon as it finds a solution. Delete the return statement. After the loop, you can return the list of all solutions if desired. To check if there were none, see if the length of the list is zero (so you know when to say there are no solutions).
I would also suggest making solutions local to solve, instead of global.
Fellow python developers. I have a task which I can't seem to crack and my tutor is MIA. I need to write a program which only makes use of while loops, if, elif and else statements to:
Constantly ask the user to enter any random positive integer using int(raw_input())
Once the user enters -1 the program needs to end
the program must then calculate the average of the numbers the user has entered (excluding the -1) and print it out.
this what I have so far:
num = -1
counter = 1
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
counter += anyNumber
answer = counter + anyNumber
print answer
print "Good bye!"
Try the following and ask any question you might have
counter = 0
total = 0
number = int(raw_input("Enter any number: "))
while number != -1:
counter += 1
total += number
number = int(raw_input("Enter another number: "))
if counter == 0:
counter = 1 # Prevent division by zero
print total / counter
You need to add calculating average at the end of your code.
To do that, have a count for how many times the while loop runs, and divide the answer at the end by that value.
Also, your code is adding one to the answer each time because of the line - answer = counter + anyNumber, which will not result in the correct average. And you are missing storing the first input number, because the code continuously takes two inputs. Here is a fixed version:
num = -1
counter = 0
answer = 0
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
counter += 1
answer += anyNumber
anyNumber = int(raw_input("Enter another number: "))
if (counter==0): print answer #in case the first number entered was -1
else:
print answer/counter #print average
print "Good bye!"
There's another issue I think:
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
The value of the variable anyNumber is updated before the loop and at the beginning of the loop, which means that the first value you're going to enter is never going to be taken in consideration in the average.
A different solution, using a bit more functions, but more secure.
import numpy as np
numbers = []
while True:
# try and except to avoid errors when the input is not an integer.
# Replace int by float if you want to take into account float numbers
try:
user_input = int(input("Enter any number: "))
# Condition to get out of the while loop
if user_input == -1:
break
numbers.append(user_input)
print (np.mean(numbers))
except:
print ("Enter a number.")
You don't need to save total because if the number really big you can have an overflow. Working only with avg should be enough:
STOP_NUMBER = -1
new_number = int(raw_input("Enter any number: "))
count = 1
avg = 0
while new_number != STOP_NUMBER:
avg *= (count-1)/count
avg += new_number/count
new_number = int(raw_input("Enter any number: "))
count += 1
I would suggest following.
counter = input_sum = input_value = 0
while input_value != -1:
counter += 1
input_sum += input_value
input_value = int(raw_input("Enter any number: "))
try:
print(input_sum/counter)
except ZeroDivisionError:
print(0)
You can avoid using two raw_input and use everything inside the while loop.
There is another way of doing..
nums = []
while True:
num = int(raw_input("Enter a positive number or to quit enter -1: "))
if num == -1:
if len(nums) > 0:
print "Avg of {} is {}".format(nums,sum(nums)/len(nums))
break
elif num < -1:
continue
else:
nums.append(num)
Here's my own take on what you're trying to do, although the solution provided by #nj2237 is also perfectly fine.
# Initialization
sum = 0
counter = 0
stop = False
# Process loop
while (not stop):
inputValue = int(raw_input("Enter a number: "))
if (inputValue == -1):
stop = True
else:
sum += inputValue
counter += 1 # counter++ doesn't work in python
# Output calculation and display
if (counter != 0):
mean = sum / counter
print("Mean value is " + str(mean))
print("kthxbye")
I want the user to input a number
Give a number : he types "10" -but...
Give a number : he types "I want to type 10"
i want the program to just "count" the integer. Because if he types a string the program will stop
import random
goal = random.randrange(1,10)
n = 1
tries = 0
name = input("Dose to onoma sou ")
print("A game in Python")
while n != 0 :
value = int(input("madepse poio einai to noumero:"))
n = abs(value - goal)
print(value,n)
tries = tries + 1
if n >= 4 :
print("den eisai koda")
elif n > 0 and n <= 3 :
print("eisai koda")
else :
print("to vrikes")
print ("to score sou einai: ",tries)
skoros = str(tries)
score = open('score.txt', 'a')
score.write(name)
score.write(' ')
score.write(skoros)
score.write("\n")
score.close
This will take any input and pull the first number out of it. \d matches any digit 0-9, and + means "one or more".
import re
while True:
user = input('Enter a number: ')
match = re.search(r'\d+',user)
if match:
value = int(match.group(0))
break
else:
print("I didn't see a number in that response.")
print(value)
Well, you could just manually loop through the string and store the position of the number using isdigit().
The following approach expects the number to be the only one in the string (multi digit allowed):
start = None
stop = None
for i in range(len(input)):
c = input[i]
if c.isdigit():
if start == None:
start = i
stop = i
try:
number = int(input[start:stop])
catch:
print("invalid input")
EDIT:
I guess there would be some nice and easy Regex solution, but I'll leave my hands off of it, as I am not too experienced with it...