Adding items in a loop on Python - python

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...

Related

Why is my function not prompting me to enter input?

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: "))

finding duplicates in a string at python 3

def find_duplicate():
x =input("Enter a word = ")
for char in x :
counts=x.count(char)
while counts > 1:
return print(char,counts)
I've got small problem in there i want to find all duplicates in string but this program give me only one duplicate ex: aassdd is my input function gave me only a : 2 but it need to be in that form a : 2 s : 2 d : 2 thanks for your answers.
return is a keyword that works more or less as immediately exit this function (and optionally carry some output with you). You thus need to remove the return statement:
def find_duplicate():
x =input("Enter a word = ")
for char in x :
counts=x.count(char)
print(char,counts)
Furthermore you also have to remove the while loop (or update the counter if you want to print multiple times), otherwise you will get stuck in an infinite loop since count is not updated and the test will thus always succeed.
Mind however that in this case a will be printed multiple times (in this case two) if it is found multiple times in the string. You can solve this issue by first constructing a set of the characters in the string and iterate over this set:
def find_duplicate():
x =input("Enter a word = ")
for char in set(x):
counts=x.count(char)
print(char,counts)
Finally it is better to make a separation between functions that calculate and functions that do I/O (for instance print). So you better make a function that returns a dictionary with the counts, and one that prints that dictionary. You can generate a dictionary like:
def find_duplicate(x):
result = {}
for char in set(x):
result[char]=x.count(char)
return result
And a calling function:
def do_find_duplicates(x):
x =input("Enter a word = ")
for key,val in find_duplicate(x).items():
print(key,val)
And now the best part is: you actually do not need to write the find_duplicate function: there is a utility class for that: Counter:
from collections import Counter
def do_find_duplicates(x):
x =input("Enter a word = ")
for key,val in Counter(x).items():
print(key,val)
This will help you.
def find_duplicate():
x = input("Enter a word = ")
for char in set(x):
counts = x.count(char)
while counts > 1:
print(char, ":", counts, end=' ')
break
find_duplicate()
Just because this is fun, a solution that leverages the built-ins to avoid writing any more custom code than absolutely needed:
from collections import Counter, OrderedDict
# To let you count characters while preserving order of first appearance
class OrderedCounter(Counter, OrderedDict): pass
def find_duplicate(word):
return [(ch, cnt) for ch, cnt in OrderedCounter(word).items() if cnt > 1]
It's likely more efficient (it doesn't recount each character over and over), only reports each character once, and uses arguments and return values instead of input and print, so it's more versatile (your main method can prompt for input and print output if it chooses).
Usage is simple (and thanks to OrderedCounter, it preserves order of first appearance in the original string too):
>>> find_duplicate('aaacfdedbfrf')
[('a', 3), ('f', 3), ('d', 2)]
def find_duplicate():
x = input("Enter a word = ")
dup_letters = []
dup_num = []
for char in x:
if char not in dup_letters and x.count(char) > 1:
dup_letters.append(char)
dup_num.append(x.count(char))
return zip(dup_letters, dup_num)
dup = find_duplicate()
for i in dup:
print(i)
This version should be fast as I am not using any library or more than one cycle, do you have any faster options?
import datetime
start_time = datetime.datetime.now()
some_string = 'Laptop' * 99999
ans_dict = {}
for i in some_string:
if i in ans_dict:
ans_dict[i] += 1
else:
ans_dict[i] = 1
print(ans_dict)
end_time = datetime.datetime.now()
print(end_time - start_time)
def find_duplicate():
x = input("Enter a word = ")
y = ""
check = ""
for char in x:
if x.count(char) > 1 and char not in y and char != check:
y += (char + ":" + str(x.count(char)) + " ")
check = char
return y.strip()

Write a program that lets the user enter a string and displays the character that appears most frequently in the string

I am currently working on python, and I do not understand this much. I am looking for help with this question, before the dictionaries. This question is to be completed without any dictionaries. The problem is I do not know much about the max function.
So Far I have:
AlphaCount = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for ch in text:
ch = ch.upper()
index=Alpha.find(ch)
if index >-1:
AlphaCount[index] = AlphaCount[index]+1
You can use Counter
from collections import Counter
foo = 'wubalubadubdub'
Counter(list(foo))
To get the most frequent letter
Counter(list(foo)).most_common(1)
You can use set which will get only unique characters from the input. Then iterate over them and count how many times it occurs in the input with count. If it occurs more often then the max and isalpha (not a space) then set max to the count.
text='This is a test of tons of tall tales'
un=set(text.upper())
max=0
fav=''
for u in un:
c=text.upper().count(u)
if c>max and u.isalpha():
max=c
fav=u
print(fav) # T
print(max) # 6
EDIT
To do this from your code: fix capitalization(for, if) and then find and print/return the most common letter. Also AlphaCount has an extra 0, you only need 26.
text='This is a test of tons of tall talez'
AlphaCount=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Alpha='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for ch in text:
ch= ch.upper()
index=Alpha.find(ch)
if index >-1:
AlphaCount[index]+=1
print(AlphaCount) # the count of characters
print(max(AlphaCount)) # max value in list
print(AlphaCount.index(max(AlphaCount))) # index of max value
print(Alpha[AlphaCount.index(max(AlphaCount))]) # letter that occurs most frequently
def main():
string = input('Enter a sentence: ')
strings=string.lower()
counter = 0
total_counter = 0
most_frequent_character = ""
for ch in strings:
for str in strings:
if str == ch:
counter += 1
if counter > total_counter:
total_counter = counter
most_frequent_character = ch
counter = 0
print("The most frequent character is", most_frequent_character, "and it appears", total_counter, "times.")
main()

Using while loop to output input name backwards

I am on a step of a question that I cannot answer. The first part is:
full_name = input('Enter your full name ')
The second part is to use a while loop to print the name out backwards like from 'John Finger' to 'regniF nhoJ'.
It has to be done using a while loop, which is kind of weird to me since nothing I have read demonstrates anything like that with a while loop.
This is the usual way to do this:
print(full_name[::-1])
But this is probably what is meant:
full_name = input('Enter your full name ')
pos = len(full_name) - 1
while pos >= 0:
print(full_name[pos], end="")
pos -= 1
print()
There are several different way to do this, and it is a standard programming exercise which would work (in principle) in many languages. It is not Pythonic though. The problem is that a new string object is created for each character, which is inefficient.
reverse_name =""
i = len(full_name)
while i > 0:
reverse_name += full_name[i-1]
i -=1
Length: Get Length of string by len in-build function.
Decrement count by 1 because string index start from the 0
Apply while loop with condition count greater then -1.
String Concatenation: Add two string variables.
Print result.
Demo:
>>> full_name = "John Finger"
>>> result = ""
>>> count = len(full_name)
>>> print "lenght:", count
lenght: 11
>>> count -= 1
>>> while count>-1:
... result +=full_name[count]
... count -= 1
...
>>> result
'regniF nhoJ'
import sys
name = 'John Finger'
index = len(name) - 1
while index >= 0:
sys.stdout.write(name[index])
index -= 1

calculate the numeric value of a name

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))

Categories