Palindrome and as well as anagrammatism? - python-3.x

How can we create a program that checks if the input we give(for example: EXAMPLE) has the same length and the same letters with (XAMPLEE)?

this is efficient python code for it
NO_OF_CHARS = 256
def areAnagram(str1, str2):
# Create two count arrays and initialize all values as 0
count1 = [0] * NO_OF_CHARS
count2 = [0] * NO_OF_CHARS
# For each character in input strings, increment count
# in the corresponding count array
for i in str1:
count1[ord(i)]+=1
for i in str2:
count2[ord(i)]+=1
# If both strings are of different length. Removing this
# condition will make the program fail for strings like
# "aaca" and "aca"
if len(str1) != len(str2):
return 0
# Compare count arrays
for i in xrange(NO_OF_CHARS):
if count1[i] != count2[i]:
return 0
return 1
str1 = "EXAMPLE"
str2 = "XAMPLEE"
if areAnagram(str1, str2):
print "The two strings are anagram of each other"
else:
print "The two strings are not anagram of each other"

import array
word1 = "EXAMPLE"
word2 = "XAMPLEE"
letters = array.array('i',(0,)*26)
# Count letters of word1
for c in word1:
charIndex = ord(c) - ord('A')
letters[charIndex] = letters[charIndex]+1
# Count letters of word2 and substract them from word1 count
for c in word2:
charIndex = ord(c) - ord('A')
letters[charIndex] = letters[charIndex]-1
# letters contains only 0 if words are the same
if letters.count(0) < 26:
print("Words are different")
else:
print("Words are anagrams")

Related

Capitalize a character Before and After Nth character in a string in a Python list

Here is my code I am trying uppercase letters before and after a specific letter in a list. Uppercase any letter before and after
uppercase the previous and next letters that come before and after each "z" in a capital city. All other letters are lowercase. All cities that contain that letter will be stored in a list and returned. If I could get some input that would be great. Also if I need to change the code completely please let me know of other ways. I am new to this any input would be appreciated. Thanks
lst = ['brazzaville', 'zagreb', 'vaduz']
lst2 = []
for wrd in lst:
newwrd = ''
for ltr in wrd:
if ltr in 'ua':
newwrd += ltr.capitalize()
else:
newwrd += ltr
lst2.append(newwrd)
print(lst2)
I keep getting this:
['brAzzAville', 'zAgreb', 'vAdUz']
But I need this:
['brAzzAville', 'zAgreb', 'vadUz']
The following strategy consists of iterating through the word and replacing the letters at index-1 and index+1 of z (if they exist) with upper case letters:
lst2 = []
for wrd in lst:
wrd = wrd.lower()
for idx, letter in enumerate(wrd):
if letter == 'z':
if idx-1 > 0 and wrd[idx - 1] != 'z':
wrd = wrd.replace(wrd[idx - 1], wrd[idx - 1].upper())
if idx+1 < len(wrd) and wrd[idx + 1] != 'z':
wrd = wrd.replace(wrd[idx + 1], wrd[idx + 1].upper())
if "z" in wrd:
lst2.append(wrd)
print(lst2)
#['brAzzAville', 'zAgreb', 'vadUz']
I think this code gives correct answer , verify once
def findOccurrences(s, ch):
return [i for i, letter in enumerate(s) if letter == ch]
lst = ['brazzaville', 'zagreb', 'vaduz']
lst2 = []
result = []
for wrd in lst:
newwrd = ''
result = findOccurrences(wrd, 'z')
for i in range(len(wrd)):
if (i + 1 in result or i - 1 in result) and wrd[i] != 'z':
newwrd += wrd[i].capitalize()
else:
newwrd += wrd[i]
lst2.append(newwrd)
print(lst2)
Capitalize Nth character in a string
res = lambda test_str,N: test_str[:N] + test_str[N].upper() + test_str[N + 1:] if test_str else ''
Pseudocode
Loop through the list and filter the list for strings that contain 'z'.
[check(i) for i in lst if 'z' in i]
For each item in the list:
find the index and capitalize the preceding character to the first occurence of 'z' without rotation.
preind = list(i).index('z')-1 if list(i).index('z')-1>0 else None
k = res(stri,preind) if(preind) else i
find the index and capitalize the succeeding character to the last occurence of 'z' without rotation.
postind = i.rfind('z')+1 if i.rfind('z')+1<len(i) else None
stri = res(i,preind) if(preind) else stri
Code
lst = ['brazzaville', 'zagreb', 'vaduz']
def check(i):
stri = ""
k = ""
i = i.lower()
# lambda expression to capitalise Nth character in a string
res = lambda test_str,N: test_str[:N] + test_str[N].upper() + test_str[N + 1:] if test_str else ''
# find index of the preceeding character to 'z'
preind = list(i).index('z')-1 if list(i).index('z')-1>0 else None
# find index of the succeeding character to 'z'
postind = i.rfind('z')+1 if i.rfind('z')+1<len(i) else None
# capitalise preceeding character to 'z'
stri = res(i,preind) if(preind) else i
# capitalise succeeding character to 'z'
k = res(stri,postind) if(postind) else stri
# return the processed string
return k
print([check(i) for i in lst if 'z' in i ])
#output
['brAzzAville', 'zAgreb', 'vadUz']

Speeding up my code for pset6 DNA in cs50x

I am currently doing CS50 DNA pset and I wrote all of my code but it is slower for large files which results in check50 considering it wrong. I have attached my code and the error check50 shows below.
import sys
import csv
def main():
argc = len(sys.argv)
if (argc != 3):
print("Usage: python dna.py [database] [sequence]")
exit()
# Sets variable name for each argv argument
arg_database = sys.argv[1]
arg_sequence = sys.argv[2]
# Converts sequence csv file to string, and returns as thus
sequence = get_sequence(arg_sequence)
seq_len = len(sequence)
# Returns STR patterns as list
STR_array = return_STRs(arg_database)
STR_array_len = len(STR_array)
# Counts highest instance of consecutively reoccurring STRs
STR_values = STR_count(sequence, seq_len, STR_array, STR_array_len)
DNA_match(STR_values, arg_database, STR_array_len)
# Reads argv2 (sequence), and returns text within as a string
def get_sequence(arg_sequence):
with open(arg_sequence, 'r') as csv_sequence:
sequence = csv_sequence.read()
return sequence
# Reads STR headers from arg1 (database) and returns as list
def return_STRs(arg_database):
with open(arg_database, 'r') as csv_database:
database = csv.reader(csv_database)
STR_array = []
for row in database:
for column in row:
STR_array.append(column)
break
# Removes first column header (name)
del STR_array[0]
return STR_array
def STR_count(sequence, seq_len, STR_array, STR_array_len):
# Creates a list to store max recurrence values for each STR
STR_count_values = [0] * STR_array_len
# Temp value to store current count of STR recurrence
temp_value = 0
# Iterates over each STR in STR_array
for i in range(STR_array_len):
STR_len = len(STR_array[i])
# Iterates over each sequence element
for j in range(seq_len):
# Ensures it's still physically possible for STR to be present in sequence
while (seq_len - j >= STR_len):
# Gets sequence substring of length STR_len, starting from jth element
sub = sequence[j:(j + (STR_len))]
# Compares current substring to current STR
if (sub == STR_array[i]):
temp_value += 1
j += STR_len
else:
# Ensures current STR_count_value is highest
if (temp_value > STR_count_values[i]):
STR_count_values[i] = temp_value
# Resets temp_value to break count, and pushes j forward by 1
temp_value = 0
j += 1
i += 1
return STR_count_values
# Searches database file for DNA matches
def DNA_match(STR_values, arg_database, STR_array_len):
with open(arg_database, 'r') as csv_database:
database = csv.reader(csv_database)
name_array = [] * (STR_array_len + 1)
next(database)
# Iterates over one row of database at a time
for row in database:
name_array.clear()
# Copies entire row into name_array list
for column in row:
name_array.append(column)
# Converts name_array number strings to actual ints
for i in range(STR_array_len):
name_array[i + 1] = int(name_array[i + 1])
# Checks if a row's STR values match the sequence's values, prints the row name if match is found
match = 0
for i in range(0, STR_array_len, + 1):
if (name_array[i + 1] == STR_values[i]):
match += 1
if (match == STR_array_len):
print(name_array[0])
exit()
print("No match")
exit()
main()
Check50 error link:
https://submit.cs50.io/check50/fd890301a0dc9414cd29c2b4dcb27bd47e6d0a48
If you wait for long, then you get the answer but since my program is running slow check50 is considering it wrong
Well, I solved it just by adding a break statement.

How to count consecutive characters?

Need to find the count of each consecutive character in a row.
Ex: aaaabbBBccaa
output: a4b2B2c2a2
The character may repeat but need to count only consecutive ones. I also need to maintain the original sequence.
I tried to do this by code below but it doesn't work.
l = input()
counter = dict()
if l.isalpha() == True:
for letter in l:
if letter in counter:
counter[letter] += 1
else:
counter[letter] = 1
for this_one in list(counter.keys()):
print(this_one,counter[this_one],sep ="",end="")
Solution if you are interested in the while loop mechanics :
l = 'aaaabbBBccaazzZZZzzzertTTyyzaaaAA'
output = ''
index = 0
while index < len(l):
incr = index
count = 1
output += l[incr]
while incr < len(l)-1 and l[incr]==l[incr+1]:
count += 1
incr += 1
index += 1
output += str(count)
index += 1
print(output)
itertools.groupby allows you to express this quite concisely using a generator expression.
from itertools import groupby
''.join(f'{x}{len(list(y))}' for x, y in groupby('aaaabbBBccaa'))
# outputs:
'a4b2B2c2a2'

list index error python (numeric words program)

I'm trying to write a program in Python 3.
This is how it works:
The input is a word.
And the program has to look if the word contains a dutch numeric word.
A word cannot contain more than 1 numeric word and if a word doesn't contain a numeric word than it has to print 'geen' (none in dutch).
example:
Input = BETWEEN
Output = TWEE (two in dutch)
Input = ZEEVERS
Output = ZES (six in dutch)
Here is my code:
import sys
invoer = input()
letterwoorden = [['T','W','E','E'], ['D','R','I','E'], ['V','I','E','R'],
['V','I','J','F'], ['Z','E','S'], ['Z','E','V','E','N'], ['A','C','H','T'],
['N','E','G','E','N']]
antwoord = []
woord = [str(a) for a in str(invoer)]
L = len(woord)
a = 0
b = 0
c = 0
for i in range(0, 8):
for j in range(0, len(letterwoorden[a])):
if letterwoorden[a][b] == woord[c]:
antwoord.append(letterwoorden[a][b])
b = b + 1
c = c + 1
else:
c = c + 1
if antwoord == letterwoorden[a]:
print(antwoord)
break
else:
a = a + 1
antwoord.clear()
if antwoord != letterwoorden[a]:
print('geen')
Could someone help me with the error on line 21? (list index out of range)
Thanks!
The code is not fully done but when the input is TWEET the output is TWEE,
when the input is BETWEEN it gives the error.
Even though usr2564301's first solution looks good, I wanted to add a couple things. You'll find this in the comments in the code.
Here's how I'd modify your code:
## use strings instead of list of strings
## ['T', 'W', 'E', 'E'] ==> 'TWEE'
## they are also iterable (you can loop through them)
## as well as indexable (['T', 'W', 'E', 'E'][0] == 'TWEE'[0])
letterwoorden = ['TWEE', 'DRIE', 'VIER', 'VIJF', 'ZES', 'ZEVEN', 'ACHT', 'NEGEN']
## keep the string
woord = input()
print('Input:', woord)
## answer should be string as well
antwoord = ''
## name your variables something meaningful
## how does one differentiate between b and c? smh
letterWoordenIndex = 0
woordenIndex = 0
## for-loops can be powerful in Python
## you might've been used to index-based loops from other languages :|
## this way, tempWord can replace all occurrences of letterwoorden[a]
for tempWord in letterwoorden:
## reset your variables at the beginning of the loop
letterWoordenIndex = woordenIndex = 0
# """ ## debug output printing word
print('Word:', tempWord, '?')
# """
## loop through the length of word
## use _ to indicate that the variable won't be used
for _ in range(len(woord)):
# """ ## debug output comparing letters/indices
print(tempWord[letterWoordenIndex],
'({})'.format(letterWoordenIndex),
'<=>', woord[woordenIndex],
'({})'.format(woordenIndex))
# """
## check current indices equals match
if tempWord[letterWoordenIndex] == woord[woordenIndex]:
antwoord += tempWord[letterWoordenIndex] ## append char to string using +
## increment indices
letterWoordenIndex += 1
woordenIndex += 1
## check if index is filled
if letterWoordenIndex == len(tempWord):
break
else:
woordenIndex += 1
# """ ## debug output comparing final results
print(antwoord, '>==<', tempWord)
# """
## assert that the accumulated result (antwoord)
## equates to the tempWord
if antwoord == tempWord:
# """ ## debug assert true
print('Yep\n')
# """
print(antwoord)
break
## no need to use else here
## if the code inside the above if executes, then it's already game-over
antwoord = '' ## empty the string
# """ ## debug assert false
print('Nope\n')
# """
## antwoord would be empty if everything failed
if antwoord == '':
print('GEEN')
You are iterating over the wrong list with your line
for j in range(0, len(letterwoorden[a])):
as this increases a for all letterwoordenagain – you already iterate over letterwoorden with the first loop, for i in range(0, 8):. Changing that to iterate over the word in question led to another error if you run out of 'source' characters (the length of invoer) OR of 'compare' characters (the word woord[c]). You must also take care to reset your b and c counters when restarting a compare.
At the very end, you test antwoord[a] but a may be out of range
The following code works
import sys
invoer = input()
letterwoorden = [['T','W','E','E'], ['D','R','I','E'], ['V','I','E','R'],
['V','I','J','F'], ['Z','E','S'], ['Z','E','V','E','N'], ['A','C','H','T'],
['N','E','G','E','N']]
antwoord = []
woord = [str(a) for a in str(invoer)]
L = len(woord)
a = 0
b = 0
c = 0
for i in range(len(letterwoorden)):
b = 0
c = 0
for j in range(len(woord)):
print ('test', a,b,c, letterwoorden[a][b], woord[c])
if letterwoorden[a][b] == woord[c]:
antwoord.append(letterwoorden[a][b])
b = b + 1
if b >= len(letterwoorden[a]):
break
c = c + 1
else:
c = c + 1
if antwoord == letterwoorden[a]:
print(antwoord)
break
else:
a = a + 1
antwoord = []
if antwoord == []:
print('geen')
A few additional notes: you don't need to maintain separate variables if you already have a loop variable. Where you use a, for example, you can also use the loop i; and the same with j.
About all of your comparing can be done much more efficiently, since Python can immediately check if a phrase contains another phrase: if straw in haystack. So, basically,
invoer = 'ZEEVERS'
letterwoorden = ['TWEE', 'DRIE', 'VIER', 'VIJF', 'ZES', 'ZEVEN', 'ACHT', 'NEGEN']
for word in letterwoorden:
if word in invoer:
print (word)
break
else:
print ('geen')
where the else is linked to the for and not to the else, to check if the loop stopped for a result.

Slicing strings and adding the integers, Loop trouble

My assignment is to chop apart sequences of numbers with dashes and add each piece together (ex: 1-1-1 = 3, 2-2 = 4). I don't know why my loop terminates after the first run through though. The output right now is
3
456
456
56-234
0
456
Here is the function:
def SSN(str):
total = 0
y = -1
dash = 0
while dash >= 0:
dash = str.find("-")
print(dash)
if dash > -1:
section = str[0:dash]
str = str[dash+1:]
section = int(section)
print(section)
total += section
print(total)
print(str)
else:
total = str
y+=1
print(y)
return total
print(SSN("456-56-234"))

Resources