Entering floats into a list without overwriting list - python

I have some code here meant to allow me to keep creating floats until I input 0 to have it stop (the 0 is then deleted). These floats are supposed to be entered into a list. The issue I'm having is that each time the while loop is run, the float_list is overwritten.
again = True
float_count = 1
while (again):
float_list = [float(input("Float%d: " % i))for i in range(float_count, float_count + 1)]
last_float = float_list[-1]
if (last_float == 0):
again = False
del float_list[-1]
else:
float_count = float_count + 1
Is there any way to alter this code so all of the floats are entered into a list? Thanks!

This maybe a good option to use the alternative form of iter(fn, sentinel), e.g.:
float_list = [float(x) for x in iter(input, '0')]
If you need the prompt then you can create a helper function:
import itertools as it
fc = it.count(1)
float_list = [float(x) for x in iter(lambda: input('Float{}: '.format(next(fc))), '0')]
Or alternatively (most closely matches OP's attempt - would exit on 0, 0.0, 0.00, etc.):
fc = it.count(1)
float_list = list(iter(lambda: float(input('Float{}: '.format(next(fc)))), 0.0))
With error handling:
def get_float():
fc = it.count(1)
def _inner():
n = next(fc)
while True:
try:
return float(input("Float{}: ".format(n)))
except ValueError as e:
print(e)
return _inner
float_list = list(iter(get_float(), 0.0))

A list comprehension really isn't appropriate here. Much simpler:
float_count = 1
float_list = []
while True:
val = input("Float%d: " % float_count)
if val == '0':
break
float_list.append(float(val)) # call float(val) to convert from string to float
float_count += 1
it might be more user friendly to not crash if the user didn't type a float, e.g.:
def read_float(msg):
while 1:
val = input(msg)
if val == '0':
return val
try:
return float(val)
except ValueError:
print("%s is not a float, please try again.." % val)
def read_float_list():
float_count = 1
float_list = []
while True:
val = read_float("Float%d: " % float_count)
if val == '0':
break
float_list.append(val) # now val has been converted to float by read_float.
float_count += 1

Related

Why is this function I made cliaming that log(4) is complex

I was making a class for logarithims of different bases and I noticed certain numbers like log(2) and log(4) were coming up as complex
class LogBaseN:
def __init__(self,base):
self.base = base
def __call__(self,x):
y,I = sp.symbols("y I")
self.x = x
if self.x == 1:
return 0
pass
if type(self.x) == int or type(self.x) == float:
ans = sp.solve(sp.Eq(self.base,self.x**(1/y)))[0]
try:
if int(ans) == float(ans):
return int(eval(str(ans)))
else:
return float(eval(str(ans)))
return ans
except:
return(eval(str(ans)))
if type(self.x) == list:
answers = []
for num in self.x:
i = num
if i == 1:
answers.append(0)
continue
ans = sp.solve(sp.Eq(self.base,i**(1/y)))[0]
try:
if int(ans) == float(ans):
answers.append(int(eval(str(ans))))
else:
answers.append(float(eval(str(ans))))
except:
answers.append(ans)
return answers
ln = LogBaseN(e)
log2 = LogBaseN(2)
Log = LogBaseN(10)
print(Log(4))
#Output log(2)/(3.14159265359*I + log(sqrt(10)))
I tried evaluating in by using str() then evaling using eval but that didnt fix it just to make it output I had to use sympy.symbols so the "I" would not cause an error

replacing all integers in one list, with strings in another

testdeck = ['rock']
finaldeck = ['apple','banana','napalm','ice',5,6,7,8]
def deckhelp(testdeck,finaldeck):
testnumber = 0
testlength = len(testdeck)
for index, (card, item) in enumerate(zip(testdeck, finaldeck)):
if isinstance(item, int): #checks if item is an integer
finaldeck[index] = card
print(finaldeck)
testnumber += 1
if testnumber == testlength:
print('done')
pass
deckhelp(testdeck,finaldeck)
I want rock to replace the 5 located in finaldeck, can't seem to make it happen
This is not an appropriate use of zip() because you only want to iterate through testdeck when you reach the integers in finaldeck.
You also need to use return, not pass, to end the function when you reach the end of testdeck.
def deckhelp(testdeck, finaldeck):
testindex = 0
testlength = len(testdeck)
for index, item in enumerate(finaldeck):
if isinstance(item, int):
finaldeck[index] = testdeck[testindex]
testindex += 1
if testindex == testlength:
print('done')
return
Zip only works in testdeck and finaldeck have the same length. Instead, you can use something like this:
def deckhelp(testdeck, finaldeck):
replace_index = 0
for i, val in enumerate(finaldeck):
if isinstance(val, int):
finaldeck[i] = testdeck[replace_index]
replace_index += 1
if replace_index == len(testdeck):
print("done")
return

RLE ALgorithm in python

like the title suggest I want to do an RLE algorithm and I have few problems with that
for example in RLE algorithm if we take aaaabbbccd it should return a4b3c2d1 as a result
the rle function should return the compressed string of aaabbbccccddddd
rle(data : str) : str
so it would be a3b3c4d5
Here's the code I know it's wrong but I don't know If it was a good way to begin
def rle(data):
data = 'aaabbbccccddddd'
for i in range(0,len(data)):
if data.count(f'{i}') > 1:
data.replace(i, data.count(f'{i}'))
print(data)
print(rle(data))
data = 'aaabbbccccddddd'
seq = []
r = None
for d in data:
if d != r:
seq.append(d)
seq.append(str(1))
r = d
else:
seq[-1] = str(int(seq[-1]) + 1)
print("".join(seq))
I thought that this code snippet is simple, and so didn't explain it...
we have a str and want to convert it to Char-TheNumberOfRepetitions pairs, like ['a',3,'b',3,'c',4,...], so we loop a char over str and when it is new, we add [char, 1] to list, otherwise, we add 1 to last element of list while we get a new char...
r variable is for new char recognition and is a temp variable that we store every new char (if a char was not equal to it, replace)
finally, we convert ['a',3,'b',3,'c',4,...] to str, using join
why we use str() and int()? because python join method is a bit silly :) and throw an exception, if an element of list be int... and everytime we convert it to int to add 1 and then convert to str, again...
why not map? because I assume that OP is beginner and map is complicate for him...
and, a more pythonic way:
def rle(data: str) -> str:
seq = [data[0], 1]
for elem in data[1:]:
if elem != seq[-2]:
seq += [elem, 1]
else:
seq[-1] += 1
return ''.join(map(str, seq))
and reverse:
def reverse_rle(data: str, end_char = '$') -> str:
def convert(): return seq[:-2] + [seq[-2] * (seq[-1] or 1)]
seq = [data[0], 0]
for elem in data[1:] + end_char:
if elem.isdigit():
seq[-1] = seq[-1] * 10 + int(elem)
else:
seq = convert()
if elem != end_char:
seq += [elem, 0]
return "".join(seq)
and if you dont want to use end_char:
def reverse_rle(data: str) -> str:
def convert(): return seq[:-2] + [seq[-2] * (seq[-1] or 1)]
seq = [data[0], 0]
for elem in data[1:]:
if elem.isdigit():
seq[-1] = seq[-1] * 10 + int(elem)
else:
seq = convert() + [elem, 0]
return "".join(convert())
This should work better
def rle(data):
# Initialize a few variables
prev = None
cnt = 0
res = ""
for i in data:
if i == prev:
# if same char as previous one, just add one to counter
cnt += 1
else:
# Check that we are not at first round and add to result
if prev != None:
res += "%s%s" % (cnt,prev)
# Set new character as previous one
prev = i
# Add last char to result
res += "%s%s" % (cnt,prev)
return res
print(rle("aaabbbccccddddd"))

Why does Python 3 for loop output and behave differently?

This is a password generator, I couldn't really determine where the problem is, but from the output, I could say it's around turnFromAlphabet()
The function turnFromAlphabet() converts an alphabetical character to its integer value.
The random module, I think doesn't do anything here as it just decides whether to convert a character in a string to uppercase or lowercase. And if a string is in either, when sent or passed to turnFromAlphabet() it is converted to lowercase first to avoid errors but there are still errors.
CODE:
import random
import re
#variables
username = "oogisjab" #i defined it already for question purposes
index = 0
upperOrLower = []
finalRes = []
index2a = 0
#make decisions
for x in range(len(username)):
decision = random.randint(0,1)
if(decision is 0):
upperOrLower.append(True)
else:
upperOrLower.append(False)
#Apply decisions
for i in range(len(username)):
if(upperOrLower[index]):
finalRes.append(username[index].lower())
else:
finalRes.append(username[index].upper())
index+=1
s = ""
#lowkey final
s = s.join(finalRes)
#reset index to 0
index = 0
def enc(that):
if(that is "a"):
return "#"
elif(that is "A"):
return "4"
elif(that is "O"):
return "0" #zero
elif(that is " "):
# reduce oof hackedt
decision2 = random.randint(0,1)
if(decision2 is 0):
return "!"
else:
return "_"
elif(that is "E"):
return "3"
else:
return that
secondVal = []
for y in range(len(s)):
secondVal.append(enc(s[index]))
index += 1
def turnFromAlphabet(that, index2a):
alp = "abcdefghijklmnopqrstuvwxyz"
alp2 = list(alp)
for x in alp2:
if(str(that.lower()) == str(x)):
return index2a+1
break
else:
index2a += 1
else:
return "Error: Input is not in the alphabet"
#real final
finalOutput = "".join(secondVal)
#calculate some numbers and chars from a substring
amount = len(finalOutput) - round(len(finalOutput)/3)
getSubstr = finalOutput[-(amount):]
index = 0
allFactors = {
};
#loop from substring
for x in range(len(getSubstr)):
hrhe = re.sub(r'\d', 'a', ''.join(e for e in getSubstr[index] if e.isalnum())).replace(" ", "a").lower()
print(hrhe)
#print(str(turnFromAlphabet("a", 0)) + "demo")
alpInt = turnFromAlphabet(hrhe, 0)
print(alpInt)
#get factors
oneDimensionFactors = []
for p in range(2,alpInt):
# if mod 0
if(alpInt % p) is 0:
oneDimensionFactors.append(p)
else:
oneDimensionFactors.append(1)
indexP = 0
for z in oneDimensionFactors:
allFactors.setdefault("index{0}".format(index), {})["keyNumber"+str(p)] = z
index+=1
print(allFactors)
I think that you are getting the message "Error: input is not in the alphabet" because your enc() change some of your characters. But the characters they becomes (for example '#', '4' or '!') are not in your alp variable defined in turnFromAlphabet(). I don't know how you want to fix that. It's up to you.
But I have to say to your code is difficult to understand which may explain why it can be difficult for you to debug or why others may be reluctant to help you. I tried to make sense of your code by removing code that don't have any impact. But even in the end I'm not sure I understood what you tried to do. Here's what I understood of your code:
import random
import re
#username = "oogi esjabjbb"
username = "oogisjab" #i defined it already for question purposes
def transform_case(character):
character_cases = ('upper', 'lower')
character_to_return = character.upper() if random.choice(character_cases) == 'upper' else character.lower()
return character_to_return
username_character_cases_modified = "".join(transform_case(current_character) for current_character in username)
def encode(character_to_encode):
translation_table = {
'a' : '#',
'A' : '4',
'O' : '0',
'E' : '3',
}
character_translated = translation_table.get(character_to_encode, None)
if character_translated is None:
character_translated = character_to_encode
if character_translated == ' ':
character_translated = '!' if random.choice((True, False)) else '_'
return character_translated
final_output = "".join(encode(current_character) for current_character in username_character_cases_modified)
amount = round(len(final_output) / 3)
part_of_final_output = final_output[amount:]
all_factors = {}
for (index, current_character) in enumerate(part_of_final_output):
hrhe = current_character
if not hrhe.isalnum():
continue
hrhe = re.sub(r'\d', 'a', hrhe)
hrhe = hrhe.lower()
print(hrhe)
def find_in_alphabet(character, offset):
alphabet = "abcdefghijklmnopqrstuvwxyz"
place_found = alphabet.find(character)
if place_found == -1 or not character:
raise ValueError("Input is not in the alphabet")
else:
place_to_return = place_found + offset + 1
return place_to_return
place_in_alphabet = find_in_alphabet(hrhe, 0)
print(place_in_alphabet)
def provide_factors(factors_of):
for x in range(1, int(place_in_alphabet ** 0.5) + 1):
(quotient, remainder) = divmod(factors_of, x)
if remainder == 0:
for current_quotient in (quotient, x):
yield current_quotient
unique_factors = set(provide_factors(place_in_alphabet))
factors = sorted(unique_factors)
all_factors.setdefault(f'index{index}', dict())[f'keyNumber{place_in_alphabet}'] = factors
print(all_factors)
Is near what your wanted to do?

How do I display the max function i created in python

I have to get userinputs of ints and store them in a array, and print the max number in the list. But I had to create my own max function. Im not sure what steps to take to implement it into my code.
def getInt(prompt):
n = int
done = False
while not done:
try:
n = int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
if n == 0:
done = True
return n
def maxNum(l):
maxi = [0]
for num in l:
if maxi > num:
maxi = num
return maxi
def result():
print("The maxium value is: " + maxNum(i))
def main():
num = []
i = 0
done = False
while not done:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
done = True
results = maxNum(i)
The below code does exactly what you want.
def getInt(prompt):
try:
n = int(input(prompt))
return n
except ValueError:
print("I was expecting a number, please try again...")
getInt()
def maxNum(lst):
if not lst: # if list is empty
return None
max_elem = lst[0]
for x in lst:
if x > max_elem:
max_elem = x
return max_elem
def main():
nums = []
while True:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
break
nums.append(num)
result = maxNum(nums)
print("The maxium value is: " + str(result))
main()
python support built-in max function
max([1,2,3]) # return 3
and Your code is totally wrong.
if you want to input array of integers, getInt may be like this.
def getInt():
array = []
while True:
x = int(input('message'))
if x == 0: break
array.append(x)
return array
and main code will be
array = getInt()
max_value = max(array)
print (max_value)
if you want your own max function, it can be
def max_func(array):
max_val = array[0]
for val in array:
if val > max_val: max_val = val
return max_val
Here is a fixed version of your maxNum function:
def maxNum(l):
if not l:
return None # or return whatever you want if user did not input anything
maxi = l[0] # it expects 'l' to be an array!
for num in l[1:]:
if maxi > num:
maxi = num
return maxi
Let's also fix your getInt function:
def getInt(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
Finally, your "main" function needs the following fix:
def main():
num = []
n = 1
while n != 0:
n = getInt("Please enter an integer < 0 to finish >: ") # store user input into n - do not overwrite num!
num.append(n) # append each user value to the list num
results = maxNum(num) # pass the entire *list* to maxNum

Categories

Resources