Hi so I'm very very new to programming so please forgive me if I'm not able to ask with the correct jargon, but I'm writing a simple program for an assignment in which I'm to convert CGS units to SI units
For example:
if num == "1": #Gauss --> Tesla
A=float(raw_input ("Enter value: "))
print "=", A/(1e4), "T"
with this I'm only able to convert one value at a time. Is there a way I can input multiple values, perhaps separated by commas and perform the calculation on all of them simultaneously and spit out another list with the converted values?
You can read in a comma-separated list of numbers from the user (with added whitespace possibly), then split it, strip the excessive white space, and loop over the resulting list, converting each value, putting it in a new list, and then finally outputting that list:
raw = raw_input("Enter values: ")
inputs = raw.split(",")
results = []
for i in inputs:
num = float(i.strip())
converted = num / 1e4
results.append(converted)
outputs = []
for i in results:
outputs.append(str(i)) # convert to string
print "RESULT: " + ", ".join(outputs)
Later, when you're more fluent in Python, you could make it nicer and more compact:
inputs = [float(x.strip()) for x in raw_input("Enter values: ").split(",")]
results = [x / 1e4 for x in inputs]
print "RESULT: " + ", ".join(str(x) for x in results)
or even go as far as (not recommended):
print "RESULT: " + ", ".join(str(float(x.strip()) / 1e4) for x in raw_input("Enter values: ").split(","))
If you want to keep doing that until the user enters nothing, wrap everything like this:
while True:
raw = raw_input("Enter values: ")
if not raw: # user input was empty
break
... # rest of the code
Sure! You'll have to provide some sort of "marker" for when you're done, though. How about this:
if num == '1':
lst_of_nums = []
while True: # infinite loops are good for "do this until I say not to" things
new_num = raw_input("Enter value: ")
if not new_num.isdigit():
break
# if the input is anything other than a number, break out of the loop
# this allows for things like the empty string as well as "END" etc
else:
lst_of_nums.append(float(new_num))
# otherwise, add it to the list.
results = []
for num in lst_of_nums:
results.append(num/1e4)
# this is more tersely communicated as:
# results = [num/1e4 for num in lst_of_nums]
# but list comprehensions may still be beyond you.
If you're trying to enter a bunch of comma-separated values, try:
numbers_in = raw_input("Enter values, separated by commas\n>> ")
results = [float(num)/1e4 for num in numbers_in.split(',')]
Hell if you wanted to list both, construct a dictionary!
numbers_in = raw_input("Enter values, separated by commas\n>> ")
results = {float(num):float(num)/1e4 for num in numbers_in.split(',')}
for CGS,SI in results.items():
print "%.5f = %.5fT" % (CGS, SI)
# replaced in later versions of python with:
# print("{} = {}T".format(CGS,SI))
Related
I’m using Python IDE 3. My goal is this: If I have a string of text, ‘ABCDEFGHIJKL’, I want to sort it into groups, like three groups (‘ADGJ’,’BEHK’,’CFIL’). I require input for this, but the prompts aren’t showing up and I can’t type in input. Here’s my code:
#data
code_text = input('Text: ').lower()
code_skip = int(input('Shift length: '))
code_list = []
#function
def countSkip(text, shift, listt):
i = 0
group = 1
if group <= shift:
for e in text:
#make sure the set starts at the right place
if e.index()+1 < group:
pass
elif shift != 0:
if i = shift:
listt.append(e)
i = 0
i += 1
else:
listt.append(e)
group += 1
Calling the function
countSkip(code_text, code_shift, code_list)
There's a few things stopping your code from working that people have pointed out in the comments. Instead of trying to dissect your code and get that to work, I wrote a much more concise function that will get you the results you're after
def text_splitter(input_text, set_length):
num_sets = int(len(input_text)/set_length)
split_text = ["".join([input_text[(n * num_sets) + m] for n in range(set_length)]) for m in range(num_sets)]
return split_text
text_to_split = input('Text: ').lower()
len_set = int(input('Set Length: '))
text_list = text_splitter(text_to_split, len_set)
Sorry I was struggling to name the variables in an effective manner but the function above uses a list expression to get you the results you need. Keep in mind that if you use say a 7 letter string and ask for sets of length 2, the last letter won't be appended. However this shouldn't be too hard to check and correct. For example you could add this code to the function or around the initial input for the set length:
while len(input_text) % set_length != 0:
set_length = int(input("The text is length " + str(len(input_text)) + " please enter a different set length: "))
For my comp sci class I was assigned to make an english to pirate dictionary. The user is prompted to enter a sentence which is then translated to pirate but it isn't working and I'm not sure why. Any help would be appreciated.
eng2pir = {}
eng2pir['sir'] = 'matey'
eng2pir['hotel'] = 'fleabag inn'
eng2pir['restauraunt'] = 'galley'
eng2pir['your'] = 'yer'
eng2pir['hello'] = 'avast'
eng2pir['is'] = 'be'
eng2pir['professor'] = 'foul blaggart'
a = input("Please enter a sentence to be translated into pirate: ")
for x in range(len(a)):
b = a.replace(x, eng2pir[x])
print(b)
Your loop is iterating over range(len(a)), so x will take on an integer value for each individual character in your input. This is off for a couple of reasons:
Your goal is to iterate over words, not characters.
Indexing the dictionary should be done with words, not integers (this is the cause of your error).
Finally, note that .replace() replaces the first occurrence of the searched item in the string. To revise your approach to this problem in a way that still uses that method, consider these two main changes:
Iterate over the keys of the dictionary; the words that could potentially be replaced.
Loop until no such words exist in the input, since replace only does individual changes.
You're iterating over each of the characters in the string input, as the other answer before this has said, replace only replaces the first occurence.
You'd want to do something like this (after you've made your dictionary).
a = input("Please enter a sentence to be translated into pirate: ")
for x in eng2pir:
while x in a:
a = a.replace(x,eng2pir[x])
print(a)
for x in range(len(a)):
b = a.replace(x, eng2pir[x])
because for loop x is int
but eng2pir dict no int key
so output error
#!/usr/bin/env python
# coding:utf-8
'''黄哥Python'''
eng2pir = {}
eng2pir['sir'] = 'matey'
eng2pir['hotel'] = 'fleabag inn'
eng2pir['restauraunt'] = 'galley'
eng2pir['your'] = 'yer'
eng2pir['hello'] = 'avast'
eng2pir['is'] = 'be'
eng2pir['professor'] = 'foul blaggart'
a = input("Please enter a sentence to be translated into pirate:\n ")
lst = a.split()
b = ''
for word in lst:
b += eng2pir.get(word, "")
print(b)
I want users to enter random words/numbers/phrases. If they have entered more then 5 then they get an error message and if the enter 5 or less then I print out the list vertically. I don't know what code to use so that it does not count the white spaces. As well, I want to count the number of words/numbers, NOT the amount of characters. If you could just take a look at my code and give some help, that would be great!
myList = []
myList = raw_input("Enter words,numbers or a phrase (a phrase should be entered between two quotations)...")
if len(myList) > 5:
print('Error')
else:
#print output
for variable in L:
print variable
Try something like this using str.split() to return a list of the words in the string using the default delimiter of a space character:
myList = []
while(True):
myList = raw_input("Please enter words or numbers: ")
if(len(myList.split())) <= 5:
break
else:
print("Error: You entered more than 5 arguments, Try again...")
for item in myList.split():
print(item)
Try it here!
The working code for what you want is the following:
# I separate the input text by the spaces
data = raw_input("Enter something... ").split(" ")
# handle the data
if len(data) > 5:
print("Only 4 or less arguments allowed!")
else:
for variable in data:
print(variable)
Now, this doesn't prevent the user from inserting other characters like !, $%"#$, so to handle that case, you should check for some of the answers in this question: Stripping everything but alphanumeric chars from a string in Python
Have fun!
So I'm making a A1Z26 cipher decoder where I could enter the numbers in and it'll return a corresponding letter, e.g. 8,5,12,12,0 --> h,e,l,l,o.
However, I'm having trouble figuring out how to make python take each number as input as opposed to splitting them into digits.
Any help would be appreciated. Thanks
EDIT:
Here's the code I've written so far:`
dic = {dictionary that translates numbers to letters}
mid = []
output = []
input = raw_input("Enter the code here: ")
splitinput = list(input)
for i in splitinput:
if i != ",":
mid.append(i)
mid = [int(i) for i in buffer]
for i in mid:
output.append(dic[i])
print output
So for it to stop splitting each number into digits I would need to use something other than the list function.
Something like this:
myint = 123456789
mystr = str(myint)
print(','.join(mystr[::2]))
Alright, I found it. This is the code that gives me the desired output if anyone will be interested:
inv_alphabet = {contains the mapping of each number to letter}
output = []
code_input = str(raw_input("Enter your cipher here: "))
split_code = code_input.split(",")
split_code = [int(i) for i in split_code]
for i in split_code:
output.append(inv_alphabet[i])
print output
This is what I have to do https://www.codeeval.com/open_challenges/140/
I've been on this challenge for three days, please help. It it is 85-90 partially solved. But not 100% solved... why?
This is my code:
import sys
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
saver=[]
text=""
textList=[]
positionList=[]
num=0
exists=int()
counter=0
for l in test.strip().split(";"):
saver.append(l)
for i in saver[0].split(" "):
textList.append(i)
for j in saver[1].split(" "):
positionList.append(j)
for i in range(0,len(positionList)):
positionList[i]=int(positionList[i])
accomodator=[None]*len(textList)
for n in range(1,len(textList)):
if n not in positionList:
accomodator[n]=textList[len(textList)-1]
exists=n
for item in positionList:
accomodator[item-1]=textList[counter]
counter+=1
if counter>item:
accomodator[exists-1]=textList[counter]
for word in accomodator:
text+=str(word) + " "
print text
test_cases.close()
This code works for me:
import sys
def main(name_file):
_file = open(name_file, 'r')
text = ""
while True:
try:
line = _file.next()
disordered_line, numbers_string = line.split(';')
numbers_list = map(int, numbers_string.strip().split(' '))
missing_number = sum(xrange(sorted(numbers_list)[0],sorted(numbers_list)[-1]+1)) - sum(numbers_list)
if missing_number == 0:
missing_number = len(disordered_line)
numbers_list.append(missing_number)
disordered_list = disordered_line.split(' ')
string_position = zip(disordered_list, numbers_list)
ordered = sorted(string_position, key = lambda x: x[1])
text += " ".join([x[0] for x in ordered])
text += "\n"
except StopIteration:
break
_file.close()
print text.strip()
if __name__ == '__main__':
main(sys.argv[1])
I'll try to explain my code step by step so maybe you can see the difference between your code and mine one:
while True
A loop that breaks when there are no more lines.
try:
I put the code inside a try and catch the StopIteracion exception, because this is raised when there are no more items in a generator.
line = _file.next()
Use a generator, so that way you do not put all the lines in memory from once.
disordered_line, numbers_string = line.split(';')
Get the unordered phrase and the numbers of every string's position.
numbers_list = map(int, numbers_string.strip().split(' '))
Convert every number from string to int
missing_number = sum(xrange(sorted(numbers_list)[0],sorted(numbers_list)[-1]+1)) - sum(numbers_list)
Get the missing number from the serial of numbers, so that missing number is the position of the last string in the phrase.
if missing_number == 0:
missing_number = len(unorder_line)
Check if the missing number is equal to 0 if so then the really missing number is equal to the number of the strings that make the phrase.
numbers_list.append(missing_number)
Append the missing number to the list of numbers.
disordered_list = disordered_line.split(' ')
Conver the disordered phrase into a list.
string_position = zip(disordered_list, numbers_list)
Combine every string with its respective position.
ordered = sorted(string_position, key = lambda x: x[1])
Order the combined list by the position of the string.
text += " ".join([x[0] for x in ordered])
Concatenate the ordered phrase, and the reamining code it's easy to understand.
UPDATE
By looking at your code here is my opinion tha might solve your problem.
split already returns a list so you do not have to loop over the splitted content to add that content to another list.
So these six lines:
for l in test.strip().split(";"):
saver.append(l)
for i in saver[0].split(" "):
textList.append(i)
for j in saver[1].split(" "):
positionList.append(j)
can be converted into three:
splitted_test = test.strip().split(';')
textList = splitted_test[0].split(" ")
positionList = map(int, splitted_test[1].split(" "))
In this line positionList = map(int, splitted_test[0].split(" ")) You already convert numbers into int, so you save these two lines:
for i in range(0,len(positionList)):
positionList[i]=int(positionList[i])
The next lines:
accomodator=[None]*len(textList)
for n in range(1,len(textList)):
if n not in positionList:
accomodator[n]=textList[len(textList)-1]
exists=n
can be converted into the next four:
missing_number = sum(xrange(sorted(positionList)[0],sorted(positionList)[-1]+1)) - sum(positionList)
if missing_number == 0:
missing_number = len(textList)
positionList.append(missing_number)
Basically what these lines do is calculate the missing number in the serie of numbers so the len of the serie is the same as textList.
The next lines:
for item in positionList:
accomodator[item-1]=textList[counter]
counter+=1
if counter>item:
accomodator[exists-1]=textList[counter]
for word in accomodator:
text+=str(word) + " "
Can be replaced by these ones:
string_position = zip(textList, positionList)
ordered = sorted(string_position, key = lambda x: x[1])
text += " ".join([x[0] for x in ordered])
text += "\n"
From this way you can save, lines and memory, also use xrange instead of range.
Maybe the factors that make your code pass partially could be:
Number of lines of the script
Number of time your script takes.
Number of memory your script uses.
What you could do is:
Use Generators. #You save memory
Reduce for's, this way you save lines of code and time.
If you think something could be made it easier, do it.
Do not redo the wheel, if something has been already made it, use it.