Python - Input a str. and convert it to a number. (print calculation) - python-3.x

How do I input a letter (a , b or c) and then print out a result as a int.(5 * 1) and not a str? (5 * a).
number = int(input("Input a number: "))
letter = input("Input a latter: ")
a = 1
b = 5
c = 3
print(number * letter)

You can simply use a dictionary here as follows:
For your code:
number = int(input('Enter a number: '))
letter = input('Enter a letter: ')
dict = {'a':1,'b':5,'c':3}
print( number * dict[letter.lower()])

You can try this:
number = int(input('Input a number: '))
letter = input('Input a letter: ')
a = 1
b = 5
c = 3
letter = letter.lower()
if letter in 'abc':
idx = 'abc'.index(letter)
letter = [a, b, c][idx]
print(number * letter)
For a more flexible way, you can do this:
number = int(input('Input a number: '))
letter = input('Input a letter: ')
a = 1
b = 5
c = 3
d = 4
letter = letter.lower()
# locals() returns a dict of all variables in the current scope.
v = locals().get(letter)
if v is None:
print('"%s" is not an expected choice!' % letter)
else:
print(number * v)

Related

Finding a substring that occurs k times in a long string

I'm trying to solve some algorithm task, but the solution does not pass the time limit.
The condition of the task is the following:
You are given a long string consisting of small Latin letters. We need to find all its substrings of length n that occur at least k times.
Input format:
The first line contains two natural numbers n and k separated by a space.
The second line contains a string consisting of small Latin letters. The string length is 1 ≤ L ≤ 10^6.
n ≤ L, k ≤ L.
Output Format:
For each found substring, print the index of the beginning of its first occurrence (numbering in the string starts from zero).
Output indexes in any order, in one line, separated by a space.
My final solution looks something like this:
def polinomial_hash(s: str, q: int, R: int) -> int:
h = 0
for c in s:
h = (h * q + ord(c)) % R
return h
def get_index_table(inp_str, n):
q = 1000000007
power = q ** (n-1)
R = 2 ** 64
M = len(inp_str)
res_dict = {}
cur_hash = polinomial_hash(inp_str[:n], q, R)
res_dict[cur_hash] = [0]
for i in range(n, M):
first_char = inp_str[i-n]
next_char = inp_str[i]
cur_hash = (
(cur_hash - ord(first_char)*(power))*q
+ ord(next_char)) % R
try:
d_val = res_dict[cur_hash]
d_val += [i-n+1]
except KeyError:
res_dict[cur_hash] = [i-n+1]
return res_dict
if __name__ == '__main__':
n, k = [int(i) for i in input().split()]
inp_str = input()
for item in get_index_table(inp_str, n).values():
if len(item) >= k:
print(item[0], end=' ')
Is it possible to somehow optimize this solution, or advise some alternative options?!

Is it possible to not have to replicate code for each iteration of the function

def math():
x = str('y')
while x == 'y':
a = float(input("Please enter a number: "))
a = (((4*a)+1)/(a-3))
b = float(input("Please enter a number: "))
b = (((4*b)+1)/(b-3))
c = float(input("Please enter a number: "))
c = (((4*c)+1)/(c-3))
d = float(input("Please enter a number: "))
d = (((4*d)+1)/(d-3))
print(a)
print(b)
print(c)
print(d)
x == str(input("Would you like to continue"))
math()
Hello I'm new to programming and I was just casually doing this to make an easy calculator for my homework assignment and I wanted to know instead of replicating the code for each variable if there was a way to do the math one time and just keep reassigning values to the variable for the math. This might be dumb a question and it's not serious or anything I just was curious if there are better way's to do this.
Comments and suggestions:
def math():
x = str('y')
'y' is a string, so there is no need to convert it to a string using str(). x = 'y' is sufficient.
while x == 'y':
a = float(input("Please enter a number: "))
a = (((4*a)+1)/(a-3))
b = float(input("Please enter a number: "))
b = (((4*b)+1)/(b-3))
c = float(input("Please enter a number: "))
c = (((4*c)+1)/(c-3))
d = float(input("Please enter a number: "))
d = (((4*d)+1)/(d-3))
DRY - don't repeat yourself.
Define a function which takes an input and returns the computed results:
def compute(n_times):
results = [] # initialize results, empty list
for repetition in range(n_times): # repeat n times
inp = float(input("Please enter a number: "))
results.append(((4 * inp) + 1) / (inp - 3)) # append result to list
return results # return filled list
and call this function n times:
result_list = compute(4) # compute() returns a list with results
for result in result_list: # iterate through list
print(result)
ask user if they wish to continue:
x == input("Would you like to continue? ")
run your function:
math()
Conclusion:
def compute(n_times):
results = [] # initialize results, empty list
for repetition in range(n_times): # repeat n times
inp = float(input("Please enter a number: "))
results.append(((4 * inp) + 1) / (inp - 3)) # append result to list
return results # return filled list
def math():
how_often = 4
answer = 'y'
while answer == 'y':
result_list = compute(how_often) # compute() returns a list with results
for result in result_list: # iterate through list
print(result)
answer == input("Would you like to continue? (y/n): ")
math()

How to check if this input is a negative number

I'm new to python and want to make a program that generates Pi with the given decimal numbers. Problem is that I don't know how to check if the user has inputted a positive number.
This is the function that generates Pi (I don't know for sure how it works)
def PiBerekening(limiet):
q = 1
r = 0
t = 1
k = 1
n = 3
l = 3
decimaal = limiet
teller = 0
while teller != decimaal + 1:
if 4 * q + r - t < n * t:
# yield digit
yield n
# insert period after first digit
if teller == 0:
yield '.'
# end
if decimaal == teller:
print('')
break
teller += 1
nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) // t) - 10 * n
q *= 10
r = nr
else:
nr = (2 * q + r) * l
nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
And this is how I ask the user how many decimals he wants to see
while not verlaatloop:
try:
pi_cijfers = PiBerekening(int(input("With how many decimals would you like to calculate Pi?")))
assert pi_cijfer > 0 # This is one of the things I've tried but I get the "NameError: name 'pi_cijfer' is not defined" error and I don't know what to do to check if the inputted number is negative
except ValueError:
print("This isn't a valid number, try again")
except AssertionError:
print("This number is negative, try again")
else:
verlaatloop = True
This is how I show the calculated Pi
for pi_cijfer in pi_cijfers:
print(pi_cijfer, end='')
You can first validate the input and then pass it to the PiBerekening function. Something like this:
while not verlaatloop:
try:
no_decimals = int(input("With how many decimals would you like to calculate Pi?"))
if no_decimals > 0:
pi_cijfers = PiBerekening(no_decimals)
#assert pi_cijfer > 0 # This is one of the things I've tried but I get the "NameError: name 'pi_cijfer' is not defined" error and I don't know what to do to check if the inputted number is negative
except ValueError:
print("This isn't a valid number, try again")
except AssertionError:
print("This number is negative, try again")
else:
verlaatloop = True

How to arrange a list of numbers into column and row

I want to input 12 numbers and have it by column and rows but Im having a problem how to do that
lst = []
num = int(input("Enter 12 numbers:"))
for n in range(num):
numbers = int(input(' '))
lst.append(numbers)
I want the output to look ike this:
Thr numbers will only depend on the entered numbers
1 2 3 4
5 6 7 8
9 1 2 3
Just use a loop to print the list on the amount of rows you want. Say you want to print lst on n rows:
row_len = len(lst) // n
for i in range(0, len(lst), row_len):
print(lst[i: i + row_len])
lst = []
num = int(input("Enter 12 numbers:"))
while num > 0:
lst.append(num % 10)
num = int(num / 10)
lst.reverse()
for i in range(3):
temp = ""
for j in range(4):
index = i * 3 + j
temp += str(lst[index]) + " "
print(temp)

could someone instruct me to understand this code

def count_char(text, char):
count = 0
for c in text:
if c == char:
count += 1
return count
filename = input("Enter a filename: ")
with open(filename) as f:
text = f.read()
for char in "abcdefghijklmnopqrstuvwxyz":
perc = 100 * count_char(text, char) / len(text)
print("{0} - {1}%".format(char, round(perc, 2)))
It's a script that counts the relative occurrence of letters abcdefghijklmnopqrstuvwxyz in the given text file.
The first block defines a function that counts how many times the character char is present in the text:
def count_char(text, char):
count = 0
for c in text:
if c == char:
count += 1
return count
The second block asks you to input the name of the file:
filename = input("Enter a filename: ")
and saves the contents of that file as a string in the variable text:
with open(filename) as f:
text = f.read()
The third block displays the relative occurrence of characters a b c d e f g h i j k l m n o p q r s t u v w x y z in text.
For each of these characters, it first computes the proportion of the amount of the given characters in the text count_char(text, char) to the total length of the text len(text) and multiplies the result by 100 to convert it to percentage:
perc = 100 * count_char(text, char) / len(text)
and displays the results as a formatted string. The numbers in curly brackets are replaced by the character char and the percentage of its occurrence, rounded to two decimals round(perc, 2):
print("{0} - {1}%".format(char, round(perc, 2)))
You can read more about string formatting in Python here.

Resources