I'm trying to write program that calculate the numeric value of a name
this what i wrote
name = input("Enter your full name:")
low = name.lower()
sum = 0
print ()
for ch in name :
print(sum + ord(ch)-96)
the problem is when i entered a name for example anna i got
the output would be
1
14
14
1
How can i get only the sum ? which is going to be in this case 30
You have to update the sum variable everytime in the loop. Change your loop to:
for ch in name :
sum += ord(ch)-96
print(sum)
You can also use sum() function with generator expression:
>>> name='anna'
>>> sum(ord(ch) - 96 for ch in name)
30
You forgot to change your sum variable. Do it like:
low = name.lower()
sum = 0
print ()
for ch in name :
sum = sum + ord(ch)-96
print(sum)
bytearray lets us add the ascii values directly using sum. Then you need to subtract 96 for each character in the string
sum(bytearray(low)) - 96 * len(low)
This works about twice as fast as using ord() for each character on my computer even for short strings, and even better for long strings
First, avoid using python keywords as variables. In your code, you have set the keyword sum which is actually a function to the value 0
Second, observe that you are in a for-loop so there is nothing to store the accumulating sum into as the for-loop progresses.
Here is what I came up with:
name = input("Enter your full name: ").lower() #Convert input to lowercase
print () #Print a newline
print (sum(ord(ch) - 96 for ch in name)) #Use the sum function to compute sum of letters
One-line:
print (sum(ord(ch) - 96 for ch in input("Enter your full name: ").lower()))
You just have to use for ch in name in the right place - use generator expression. It would be more pythonic than using a loop:
name = input("Enter your full name:")
low = name.lower()
print ()
print sum(ord(ch)-96 for ch in name)
You can also use list comprehension, but it would be slower
print sum([ord(ch)-96 for ch in name])
You can use this code for Python 3.
input_name = input("Enter Your Name: ").lower()
print(sum(ord(ch)-96 for ch in input_name))
In fact, I think solution from #gnibbler is the best.
Still, I want to share my idea. I would like use map rather than for loop or list comprehension:
name = input("Enter your full name:")
low = name.lower()
print sum(map(lambda ch: ord(ch)-96, low))
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: "))
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))
So what I'm trying to do is make a code that adds the value of the letters in a name e.g. name: ABCD ---> 1 + 2+ 3+ 4= 10
My code so far is:
def main():
name = input("Please enter your name (all lowercase): ")
print("\nHere is the code: ")
for ch in name:
print(ord(ch)-96,end=" ")
What I want to do is add all the values of the (ord(ch)-96,end=" ")
You could do this:
sum(ord(c) - 96 for c in name)
Relevant documentation
sum
ord
If you don't actually need to print out the value of each character like you currently are, use sum like others have suggested.
However, if you want to keep the loop body which prints out the value of each character as well as summing them all, just create a variable outside the loop and increment it by ord(c)-96 each time:
total = 0
for ch in name:
charValue = ord(ch)-96
print(charValue, end="")
total += charValue
Once the for loop is completed total will hold the sum of all the values of each character.
In [19]: sum(ord(c) - ord('A') + 1 for c in 'ABCD')
Out[19]: 10
One way is to create a mapping of char->value, which you can do using a dict:
>>> from string import ascii_lowercase
>>> lookup = {ch:idx for idx, ch in enumerate(ascii_lowercase, start=1)}
>>> test = 'abcd'
>>> sum(lookup[ch] for ch in test)
10
This saves mucking about with ordinal values and is a bit more explicit...
A newbie question: I have to iterate a name then associate each letter with a number beginning with a=1, b=2, c=3, etc. and then sum the numbers. I've gotten this far but no farther:
def main():
name = input("Enter name ")
sum = 0
for ch in name:
# ?
How about this?
def main():
print sum(ord(c.lower()) - ord('a') + 1 for c in raw_input("Enter name: "))
This will work even if you're dealing with both uppercase and lowercase letters. If you'll only be dealing with lowercase, you can change c.lower() to c (it will still work as is, of course, but making that change will make it faster if you are only working with lowercase letters).
Create a dictionary mapping characters to values, then use the get() method with a default of 0 on the current character.
my input is something like this
23 + 45 = astart
for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this
SyntaxError: invalid syntax
the code is this
k=raw_input()
a,b=(str(i) for i in k.split(' + '))
b,c=(str(i) for i in b.split(' = '))
its always number + number = astar
its just that when i give number+number=astar i am not getting syntax error ..!! but when i give whitespace i get sytax error
Testing with Python 2.5.2, your code ran OK as long as I only had the same spacing
on either side of the + and = in the code and input.
You appear to have two spaces on either side of them in the code, but only one on either
side in the input. Also - you do not have to use the str(i) in a generator. You can do
it like a,b=k.split(' + ')
My cut and pastes:
My test script:
print 'Enter input #1:'
k=raw_input()
a,b=(str(i) for i in k.split(' + '))
b,c=(str(i) for i in b.split(' = '))
print 'Here are the resulting values:'
print a
print b
print c
print 'Enter input #2:'
k=raw_input()
a,b=k.split(' + ')
b,c=b.split(' = ')
print 'Here are the resulting values:'
print a
print b
print c
From the interpreter:
>>>
Enter input #1:
23 + 45 = astart
Here are the resulting values:
23
45
astart
Enter input #2:
23 + 45 = astart
Here are the resulting values:
23
45
astart
>>>
Edit: as pointed out by Triptych, the generator object isn't the problem. The partition solution is still good and holds even for invalid inputs
calling (... for ...) only returns a generator object, not a tuple
try one of the following:
a,b=[str(i) for i in k.split(' + ')]
a,b=list(str(i) for i in k.split(' + '))
they return a list which can be unpacked (assuming one split)
or use str.partition assuming 2.5 or greater:
a, serperator, b = k.partition('+')
which will always return a 3 tuple even if the string isn't found
Edit: and if you don't want the spaces in your input use the strip function
a = a.strip()
b = b.strip()
Edit: fixed str.partition method, had wrong function name for some reason
I think I'd just use a simple regular expression:
# Set up a few regular expressions
parser = re.compile("(\d+)\+(\d+)=(.+)")
spaces = re.compile("\s+")
# Grab input
input = raw_input()
# Remove all whitespace
input = spaces.sub('',input)
# Parse away
num1, num2, result = m.match(input)
You could just use:
a, b, c = raw_input().replace('+',' ').replace('=', ' ').split()
Or [Edited to add] - here's another one that avoids creating the extra intermediate strings:
a, b, c = raw_input().split()[::2]
Hrm - just realized that second one requires spaces, though, so not as good.
Rather than trying to solve your problem, I thought I'd point out a basic step you could take to try to understand why you're getting a syntax error: print your intermediate products.
k=raw_input()
print k.split(' + ')
a,b=(str(i) for i in k.split(' + '))
print b.split(' = ')
b,c=(str(i) for i in b.split(' = '))
This will show you the actual list elements produced by the split, which might shed some light on the problem you're having.
I'm not normally a fan of debugging by print statement, but one of the advantages that Python has is that it's so easy to fire up the interpreter and just mess around interactively, one statement at a time, to see what's going on.