String iteration matched to lookup table - python

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.

Related

How do I write a function that accepts a string and will return a total number of certain characters in the string, without using .count?

beginner here. Trying to figure out how I can define a function that counts the total number of occurrences of certain characters in a string. Say, we want to count the number of occurrences of the letters a and b. I need to do it within a for loop. What I have so far is this. Please let me know what I can do to make this work!
#define functions
def ch_count(word):
total=0
for letter in word:
if letter==L1:
total=total+1
return total
#main program
L1=["a","e","y"]
print(ch_count("Merry Christmas")
You can try using a default dictionary. Unlike a normal dictionary, it provides a default value is a key does not exist in a dictionary.
from collections import defaultdict
string = 'quick brown fox'
letter_count = defaultdict(int)
for letter in string:
letter_count[letter] += 1
print(letter_count)
you could write a function which takes 2 arguments. The string to check, and the letter that we want to use to count occurrencies in the string.
# I will use a as a default letter
def count_occurrencies(s, letter='a'):
return sum([i == letter for i in s])
You can use sum:
string = 'Some test string'
c = 'a'
sum(x == c for x in string)
Checking for multiple characters instead:
c = 'abc'
sum(x in c for x in string)
Or you can use collections.Counter to find the count of each character:
from collections import Counter
counts = Counter(string)
counts[letter]

Definition help count_engcons

Define a function called count_engcons() which takes a string and
returns the number of consonants in the string (uppercase or
lowercase). For this problem, you may consider only letters in the
English language alphabet only. Also, for this problem "Y" is
considered a consonant (...not a vowel!). So for example
count_engcons("Tessellated?") should return 7, and
count_engcons("Aeiou!") should return 0. You must use a for loop, and
you are not allowed to use the .count() method on this problem.
I tried this:
def count_engcons(x):
vowels = ("aeiou")
count = 0
for count_engcons in text:
if not count_engcons in vowels:
count += 1
return x
However, it causes an error.
Thanks, jonrsharpe for the downvote.
You were checking if a character wasn't a vowel, so it would give bad results for characters such as ! or ?, you were also trying to access the string with different variable names (x and text), which makes no sense.
def count_engcons(text):
consonants = "bcdfghijklmnpqrstvwxyz"
count = 0
for c in text.lower():
if c in consonants:
count += 1
return count

How to make a program separate words by the end of the word?

I know the question sounds a little tricky or not really clear but I need a program, which would separate names. Since I am not from an English speaking country, our names either end in s (for males) or in e and a (for girls)
How do I make Python separate words by their last letter?
I guess this would explain more.
Like there are three names: "Jonas", "Giedre", "Anastasija".
And I need the program to print out like this
MALE: Jonas
FEMALE: Anastasija, Giedre
I started up the program and so far I have this:
mname = []
fname = []
name = input("Enter a name: ")
That's really all I can understand. Because I'm not familiar with how to work the if function with the last letter.
You could use negative indexes to acess the last element of the string
name = input("Enter a name: ")
if name[-1] in ('a','e'):
fname.append(name)
elif name[-1] == 's':
mname.append(name)
As you can see, -1 is the last character of a string.
Quoting from the python tutorial
Indices may also be negative numbers, to start counting from the
right:
>>> word[-1] # last character 'n'
If you're entering the names at once, you'll need to split them by whitespace checking the ends:
names = input('Enter names: ') # string of names to split by spaces
fname = [n for n in names.split() if n[-1] in ('a', 'e')] # females
mname = [n for n in names.split() if n[-1] == 's'] # now male names

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

Python structure mistake

I'm writing a program in which I can Reverse the sequence and Replace all As with Ts, all Cs with Gs, all Gs with Cs, and all Ts with As. the program is to read a sequence of bases and output the reverse complement sequence. I am having trouble to do it so can anyone please help me with this by having a look on my code:
word = raw_input("Enter sequence: ")
a = word.replace('A', 'T')
b = word.replace('C', 'G')
c = word.replace('G', 'C')
d = word.replace('T', 'A')
if a == word and b == word and c == word and d == word:
print "Reverse complement sequence: ", word
And I want this sort of output:
Enter sequence: CGGTGATGCAAGG
Reverse complement sequence: CCTTGCATCACCG
Regards
I would probably do something like:
word = raw_input("Enter sequence:")
# build a dictionary to know what letter to switch to
swap_dict = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
# find out what each letter in the reversed word maps to and then join them
newword = ''.join(swap_dict[letter] for letter in reversed(word))
print "Reverse complement sequence:", newword
I don't quite understand your if statement, but the above code avoids needing one by looping over each letter, deciding what it should become, and then combining the results. That way each letter only gets converted once.
Edit: oops, I didn't notice that you wanted to reverse the string too. Fixed.
Your code as written is problematic, because steps 1 and 4 are the opposite of each other. Thus they can't be done in completely separate steps: you convert all As to Ts, then convert those (plus the original Ts) to As in step 4.
For something simple, built-in, and- hopefully- efficient, I'd consider using translation tables from the string module:
import string
sequence = "ATGCAATCG"
trans_table = string.maketrans( "ATGC" , "TACG")
new_seq = string.translate( sequence.upper() , trans_table )
print new_seq
This gives the output desired:
'TACGTTAGC'
Although I doubt that your users will ever forget to capitalize all letters, it's good practice to ensure that the input is in the form expected; hence the use of sequence.upper(). Any letters/bases with conversions not included in the translation table will be unaffected:
>>> string.translate( "AEIOUTGC" , trans_table )
'TEIOUACG'
As for the reverse complement sequence? You can do that concisely using slice notation on the output string, with a step of -1:
>>> new_seq[::-1]
'CGATTGCAT'
So if I understand what you want to do, you want to swap all Ts and As as well as swap all Gs and Cs and you want to reverse the string.
OK, well first, let's work on reversing the string, something you don't have implemented. Unfortunately, there's no obvious way to do it but this SO question about how to reverse strings in python should give you some ideas. The best solution seems to be
reversedWord = word[::-1]
Next, you need to swap the letters. You can't call replace("T", "A") and replace("A","T") on the same string because that will make both you As and Ts all be set to T. You seem to have recognized this but you use separate strings for each swap and don't ever combine them. Instead you need to go through the string, one letter at a time and check. Something like this:
swappedWord = "" #start swapped word empty
for letter in word: #for every letter in word
if letter == "A": #if the letter is "A"
swappedWord += "T" #add a "T
elif letter == "T": #if it's "T"
swappedWord += "A" #add an "A"
elif letter == "C": #if it's "C"
... #you get the idea
else: #if it isn't one of the above letters
swappedWord += letter #add the letter unchanged
(EDIT - DSM's dictionary based solution is better than my solution. Our solutions are very similar though in that we both look at each character and decide what the swapped character should be but DSM's is much more compact. However, I still feel my solution is useful for helping you understand the general idea of what DSM's solution is doing. Instead of my big if statement, DSM uses a dictionary to quickly and simply return the proper letter. DSM also collapsed it into a single line.)
The reason why your if statement isn't working is that you're basically saying "if a, b, c, d, and word are all exactly the same" since == means "are equal" and if a is equal to word and b is equal to word then a must be equal to b. This can only be true if the string has no As, Ts, Cs, or Gs (i.e. word is unchanged by the swaps), so you never print out the output.

Categories