function error and getting the code to work - python

def PatternCount(Text,Pattern):
count = 0
for i in range(0,1+len(Text)-len(Pattern)):
if Text[i:i+len(Pattern)] == Pattern:
count = count + 1
return count
def Frequentwords(Text,K):
FrequentPattern = {}
for i in range(0,len(Text)-K):
Pattern = Text(i,K)
Count(i)=PatternCount(Text,Pattern)
maxCount = max(Count)
for i in range(0,len(Text)-K):
if Count(i) == maxCount:
FrequentPattern.add(Text(i,K))
list(set(FrequentPattern))
return FrequentPattern
Text = input("enter DNA sequence: ")
K = int(input("enter the length of the pattern: "))
print(Frequentwords(Text,K))
this code is to find the most frequent K-mers (the length of a short DNA sequence) in a string Text(DNA sequences) checks all k-mers appearing in this string (there are |Text| − k + 1 such k-mers) and then computes how many times each k-mer appears in Text.
there is an error in this line:
Count(i)=PatternCount(Text,Pattern)
it is SyntaxError: can't assign to function call
l want this code to
Input: A string Text DNA Seguence and an integer k.
Output: All most frequent k-mers in Text

This line Count(i)=PatternCount(Text,Pattern) doesn't make sense because you are assigning a function to another function. If Count is an array, then it should be like this:
Count[i]=PatternCount(Text,Pattern)
you should change all Count(i) in your code to Count[i]. Here's the code fixed:
def pattern_count(sequence,pattern):
count = 0
for i in range(0,1+len(sequence)-len(pattern)):
if sequence[i:i+len(pattern)] == pattern:
count = count + 1
return count
def frequent_words(sequence,t):
counters = [0]*len(sequence)
for i in range(0,len(sequence)-k):
pattern = sequence[i:i+k]
counters[i] = pattern_count(sequence,pattern)
maxCounter = max(counters)
print(counters)
for i in range(0,len(sequence)-k):
if counters[i] == maxCounter:
frequent_pattern = sequence[i:i+k]
return frequent_pattern
sequence = input("enter DNA sequence: ")
k = int(input("enter the length of the pattern: "))
print(frequent_words(sequence,k))
The base idea was fine, but there were some syntax errors. I also changed some variables names to fit standards.
You could optimize this by doing like this:
def frequent_words(sequence,t):
counters = [0]*len(sequence)
for i in range(0,len(sequence)-k):
pattern = sequence[i:i+k]
counters[i] = pattern_count(sequence,pattern)
max_index = counters.index(max(counters))
return sequence[max_index:max_index+k]
I hope this works for you.

Related

Python: count string and output letters that match a number

I want to take any string and have the user input a number. the output should then be the letters that appear as many times as that number. For example, if the user inputs "apple" and the number is 2 then the output should be "p". any advice? as far as I've gotten is being able to count the letters
You could make use of the set() function to get all the unique characters, iterate through the resultant set, and match the character count for each of the values retrieved. You can use the following code to achieve the desired output.
userInput = input('Enter a string: ')
matchNumValue = int(input('Enter a number: '))
matchingCharacters = [charValue for charValue in list(set(userInput)) if userInput.count(charValue) == matchNumValue]
print(matchingCharacters)
Hope this helps! 😊
You can use the count method.
Here an example:
word = input('Enter a string: ')
number = int(input('Enter a number: '))
usedLetters = []
for letter in word:
if letter not in usedLetters:
n = word.count(letter)
usedLetters.append(letter)
if n == number:
print(n)
The output will be:
2
Most intuitive without any extra libraries is just to use a dict to keep track of the number of occurrences of each letter. Then iterate through to see which ones have the correct number of occurrences.
def countString(string, num):
counter = {}
res = []
for char in string:
if char in counter.keys():
counter[char] += 1
else:
counter[char] = 1
for k,v in counter.items():
if v == num:
res.append(k)
return res
print(countString('apple', 2))
You could use a collections.Counter to count the characters in the string and then reverse it to a dictionary mapping counts to a list of characters with that count. collection.defaultdict creates new key/value pairs for you, to keep the line count down.
import collections
def count_finder(string, count):
counts = collections.defaultdict(list)
for char,cnt in collections.Counter(string).items():
counts[cnt].append(char)
return counts.get(count, [])
#If you don't want to import anything just use this code.
a = int(input('Enter the number'))
b='banana'
l=[]
for i in b:
if a==b.count(i):
l.append(i)
else:
pass
print(l.pop())

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

Python Convert String Literal to Float

I am working through the book "Introduction to Computation and Programming Using Python" by Dr. Guttag. I am working on the finger exercises for Chapter 3. I am stuck. It is section 3.2, page 25. The exercise is: Let s be a string that contains a sequence of decimal numbers separated by commas, e.g., s = '1.23,2.4,3.123'. Write a program that prints the sume of the numbers in s.
The previous example was:
total = 0
for c in '123456789':
total += int(c)
print total.
I've tried and tried but keep getting various errors. Here's my latest attempt.
total = 0
s = '1.23,2.4,3.123'
print s
float(s)
for c in s:
total += c
print c
print total
print 'The total should be ', 1.23+2.4+3.123
I get ValueError: invalid literal for float(): 1.23,2.4,3.123.
Floating point values cannot have a comma. You are passing 1.23,2.4,3.123 as it is to float function, which is not valid. First split the string based on comma,
s = "1.23,2.4,3.123"
print s.split(",") # ['1.23', '2.4', '3.123']
Then convert each and and every element of that list to float and add them together to get the result. To feel the power of Python, this particular problem can be solved in the following ways.
You can find the total, like this
s = "1.23,2.4,3.123"
total = sum(map(float, s.split(",")))
If the number of elements is going to be too large, you can use a generator expression, like this
total = sum(float(item) for item in s.split(","))
All these versions will produce the same result as
total, s = 0, "1.23,2.4,3.123"
for current_number in s.split(","):
total += float(current_number)
Since you are starting with Python, you could try this simple approach:
Use the split(c) function, where c is a delimiter. With this you will have a list numbers (in the code below). Then you can iterate over each element of that list, casting each number to a float (because elements of numbers are strings) and sum them:
numbers = s.split(',')
sum = 0
for e in numbers:
sum += float(e)
print sum
Output:
6.753
From the book Introduction to Computation and Programming using Python at page 25.
"Let s be a string that contains a sequence of decimal numbers separated by commas, e.g., s
= '1.23,2.4,3.123'. Write a program that prints the sum of the numbers in s."
If we use only what has been taught so far, then this code is one approach:
tmp = ''
num = 0
print('Enter a string of decimal numbers separated by comma:')
s = input('Enter the string: ')
for ch in s:
if ch != ',':
tmp = tmp + ch
elif ch == ',':
num = num + float(tmp)
tmp = ''
# Also include last float number in sum and show result
print('The sum of all numbers is:', num + float(tmp))
total = 0
s = '1.23,2.4,3.123'
for c in s.split(','):
total = total + float(c)
print(total)
Works Like A Charm
Only used what i have learned yet
s = raw_input('Enter a string that contains a sequence of decimal ' +
'numbers separated by commas, e.g. 1.23,2.4,3.123: ')
s = "," + s+ ","
total =0
for i in range(0,len(s)):
if s[i] == ",":
for j in range(1,(len(s)-i)):
if s[i+j] == ","
total = total + float(s[(i+1):(i+j)])
break
print total
This is what I came up with:
s = raw_input('Enter a sequence of decimal numbers separated by commas: ')
aux = ''
total = 0
for c in s:
aux = aux + c
if c == ',':
total = total + float(aux[0:len(aux)-1])
aux = ''
total = total + float(aux) ##Uses last value stored in aux
print 'The sum of the numbers entered is ', total
I think they've revised this textbook since this question was asked (and some of the other's have answered.) I have the second edition of the text and the split example is not on page 25. There's nothing prior to this lesson that shows you how to use split.
I wound up finding a different way of doing it using regular expressions. Here's my code:
# Intro to Python
# Chapter 3.2
# Finger Exercises
# Write a program that totals a sequence of decimal numbers
import re
total = 0 # initialize the running total
for s in re.findall(r'\d+\.\d+','1.23, 2.2, 5.4, 11.32, 18.1,22.1,19.0'):
total = total + float(s)
print(total)
I've never considered myself dense when it comes to learning new things, but I'm having a hard time with (most of) the finger exercises in this book so far.
s = input('Enter a sequence of decimal numbers separated by commas: ')
x = ''
sum = 0.0
for c in s:
if c != ',':
x = x + c
else:
sum = sum + float(x)
x = ''
sum = sum + float(x)
print(sum)
This is using just the ideas already covered in the book at this point. Basically it goes through each character in the original string, s, using string addition to add each one to the next to build a new string, x, until it encounters a comma, at which point it changes what it has as x to a float and adds it to the sum variable, which started at zero. It then resets x back to an empty string and repeats until all the characters in s have been covered
Here's a solution without using split:
s='1.23,2.4,3.123,5.45343'
pos=[0]
total=0
for i in range(0,len(s)):
if s[i]==',':
pos.append(len(s[0:i]))
pos.append(len(s))
for j in range(len(pos)-1):
if j==0:
num=float(s[pos[j]:pos[j+1]])
total=total+num
else:
num=float(s[pos[j]+1:pos[j+1]])
total=total+num
print total
My way works:
s = '1.23, 211.3'
total = 0
for x in s:
for i in x:
if i != ',' and i != ' ' and i != '.':
total = total + int(i)
print total
My answer is here:
s = '1.23,2.4,3.123'
sum = 0
is_int_part = True
n = 0
for c in s:
if c == '.':
is_int_part = False
elif c == ',':
if is_int_part == True:
total += sum
else:
total += sum/10.0**n
sum = 0
is_int_part = True
n = 0
else:
sum *= 10
sum += int(c)
if is_int_part == False:
n += 1
if is_int_part == True:
total += sum
else:
total += sum/10.0**n
print total
I have managed to answer the question with the knowledge gained up until 3.2 the section for loop
s = '1.0, 1.1, 1.2'
print 'List of decimal number'
print s
total = 0.0
for c in s:
if c == ',':
total += float(s[0:(s.index(','))])
d = int(s.index(','))+1
s = s[(d+1) : len(s)]
s = float(s)
total += s
print '1.0 + 1.1 + 1.2 = ', total
This is the answer to the question i feel that the split function is not good for beginner like you and me.
Considering the fact that you might not yet be exposed to more complex functions, simply try these out.
total = 0
for c in "1.23","2.4",3.123":
total += float(c)
print total
My answer:
s = '2.1,2.0'
countI = 0
countF = 0
totalS = 0
for num in s:
if num == ',' or (countF + 1 == len(s)):
totalS += float(s[countI:countF])
if countF < len(s):
countI = countF + 1
countF += 1
print(totalS) # 4.1
This only works if the numbers are floats
Here is my answer. It is similar to the one by user5716300 above, but since I am also a beginner I explicitly created a separate variable s1 for the split string:
s = "1.23,2.4,3.123"
s1 = s.split(",") #this creates a list of strings
count = 0.0
for i in s1:
count = count + float(i)
print(count)
If we are just sticking with the content for that chapter, I came up with this: (though using that sum method mentioned by theFourthEye is also pretty slick):
s = '1.23,3.4,4.5'
result = s.split(',')
result = list(map(float, result))
n = 0
add = 0
for a in result:
add = add + result[n]
n = n + 1
print(add)
I just wanna to post my answer because I am reading this book now.
s = '1.23,2.4,3.123'
ans = 0.0
i = 0
j = 0
for c in s:
if c == ',':
ans += float(s[i:j])
i = j + 1
j += 1
ans += float(s[i:j])
print(str(ans))
Using knowledge from the book:
s = '4.58,2.399,3.1456,7.655,9.343'
total = 0
index = 0
for string in s:
index += 1
if string == ',':
temp = float(s[:index-1])
s = s[index:]
index = 0
total += temp
temp = 0
print(total)
Here I used string slicing, and by slicing the original string every time our 'string' variable is equal to ','. Also using an index variable to keep track of the number that is before the comma. After slicing the string, the number that gets input into tmp is cleared with the comma in front of it, the string becoming another string without that number.
Because of this, the index variable needs to be reset every time this happens.
Here's mine using the exact string in the question and only what has been taught so far.
total = 0
temp_num = ''
for char in '1.23,2.4,3.123':
if char == ',':
total += float(temp_num)
temp_num = ''
else:
temp_num += char
total += float(temp_num) #to catch the last number that has no comma after it
print(total)
I know this isn't covered in the book up to this point but I happened to learn the use of the eval() function on my own prior to getting to this question and used it to solve.
total = 0
s = "1.23,2.4,3.123"
x = eval(s)
y = sum(x)
print(y)
I think this is the easiest way to answer the question. It uses the split command, which is not introduced in the book at this moment but a very useful command.
s = input('Insert string of decimals, e,g, 1.4,5.55,12.651:')
sList = s.split(',') #create a list of these values
print(sList) #to check if list is correctly created
total = 0 #for creating the variable
for each in sList:
total = total + float(each)
print(total)
total =0
s = {1.23,2.4,3.123}
for c in s:
total = total+float(c)
print(total)

Can't get my count function to work in Python

I'm trying to create a function where you can put in a phrase such as "ana" in the word "banana", and count how many times it finds the phrase in the word. I can't find the error I'm making for some of my test units not to work.
def test(actual, expected):
""" Compare the actual to the expected value,
and print a suitable message.
"""
import sys
linenum = sys._getframe(1).f_lineno # get the caller's line number.
if (expected == actual):
msg = "Test on line {0} passed.".format(linenum)
else:
msg = ("Test on line {0} failed. Expected '{1}', but got '{2}'.".format(linenum, expected, actual))
print(msg)
def count(phrase, word):
count1 = 0
num_phrase = len(phrase)
num_letters = len(word)
for i in range(num_letters):
for x in word[i:i+num_phrase]:
if phrase in word:
count1 += 1
else:
continue
return count1
def test_suite():
test(count('is', 'Mississippi'), 2)
test(count('an', 'banana'), 2)
test(count('ana', 'banana'), 2)
test(count('nana', 'banana'), 1)
test(count('nanan', 'banana'), 0)
test(count('aaa', 'aaaaaa'), 4)
test_suite()
Changing your count function to the following passes the tests:
def count(phrase, word):
count1 = 0
num_phrase = len(phrase)
num_letters = len(word)
for i in range(num_letters):
if word[i:i+num_phrase] == phrase:
count1 += 1
return count1
Use str.count(substring). This will return how many times the substring occurs in the full string (str).
Here is an interactive session showing how it works:
>>> 'Mississippi'.count('is')
2
>>> 'banana'.count('an')
2
>>> 'banana'.count('ana')
1
>>> 'banana'.count('nana')
1
>>> 'banana'.count('nanan')
0
>>> 'aaaaaa'.count('aaa')
2
>>>
As you can see, the function is non-overlapping. If you need overlapping behaviour, look here: string count with overlapping occurrences
You're using the iteration wrong, so:
for i in range(num_letters): #This will go from 1, 2, ---> len(word)
for x in word[i:i+num_phrase]:
#This will give you the letters starting from word[i] to [i_num_phrase]
#but one by one, so : for i in 'dada': will give you 'd' 'a' 'd' 'a'
if phrase in word: #This condition doesnt make sense in your problem,
#if it's true it will hold true trough all the
#iteration and count will be
#len(word) * num_phrase,
#and if it's false it will return 0
count1 += 1
else:
continue
I guess, str.count(substring) is wrong solution, because it doesn't count overlapping substrings and test suite fails.
There is also builtin str.find method, which could be helpful for the task.
Another way :
def count(sequence,item) :
count = 0
for x in sequence :
if x == item :
count = count+1
return count
A basic question rais this times.
when u see a string like "isisisisisi" howmany "isi" do u count?
at first state you see the string "isi s isi s isi" and return 3 as count.
at the second state you see the string "isisisisisi" and counts the "i" tow times per phrase like this "isi isi isi isi isi".
In other word second 'i' is last character of first 'isi' and first character of second 'isi'.
so you have to return 5 as count.
for first state simply can use:
>>> string = "isisisisisi"
>>> string.count("isi")
3
and for second state you have to recognize the "phrase"+"anything"+"phrase" in the search keyword.
the below function can do it:
def find_iterate(Str):
i = 1
cnt = 0
while Str[i-1] == Str[-i] and i < len(Str)/2:
i += 1
cnt += 1
return Str[0:cnt+1]
Now you have many choice to count the search keyword in the string.
for example I do such below:
if __name__ == "__main__":
search_keyword = "isi"
String = "isisisisisi"
itterated_part = find_iterate(search_keyword)
c = 0
while search_keyword in String:
c += String.count(search_keyword)
String = String.replace(search_keyword, itterated_part)
print c
I do not know if a better way be in python.but I tried to do this with help of Regular Expressions but found no way.

Categories