how to fix self create module not working - python-3.x

My self made module is not returning an expected result( I want to input ABC and get back 123, But it is not doing that)
I am doing this to learn how to do this and so I can make my code look cleaner.(I am trying to make a very complicated message encoder and this is my first step)
def counter(key):
length = len(key)
counting = 0
word = []
try:
while length != counting:
if key[counting] == 'A' or 'a' :
word += '1'
counting += 1
if key[counting] == 'B' or 'b' :
word += '2'
counting += 1
if key[counting] == 'C' or 'c' :
word += '3'
counting += 1
if key[counting] == 'D' or 'd' :
word += '4'
counting += 1
if key[counting] == 'E' or 'e' :
word += '5'
counting += 1
if key[counting] == 'F' or 'f' :
word += '6'
counting += 1
if key[counting] == 'G' or 'g' :
word += '7'
counting += 1
if key[counting] == 'H' or 'h' :
word += '8'
counting += 1
if key[counting] == 'I' or 'i' :
word += '9'
counting += 1
if key[counting] == 'J' or 'j' :
word += '10'
counting += 1
if key[counting] == 'K' or 'k' :
word += '11'
counting += 1
if key[counting] == 'L' or 'l' :
word += '12'
counting += 1
if key[counting] == 'M' or 'm' :
word += '13'
counting += 1
if key[counting] == 'N' or 'n' :
word += '14'
counting += 1
if key[counting] == 'O' or 'o' :
word += '15'
counting += 1
if key[counting] == 'P' or 'p' :
word += '16'
counting += 1
if key[counting] == 'Q' or 'q' :
word += '17'
counting += 1
if key[counting] == 'R' or 'r' :
word += '18'
counting += 1
if key[counting] == 'S' or 's' :
word += '19'
counting += 1
if key[counting] == 'T' or 't' :
word += '20'
counting += 1
if key[counting] == 'U' or 'u' :
word += '21'
counting += 1
if key[counting] == 'V' or 'v' :
word += '22'
counting += 1
if key[counting] == 'W' or 'w' :
word += '23'
counting += 1
if key[counting] == 'X' or 'x' :
word += '24'
counting += 1
if key[counting] == 'Y' or 'y' :
word += '25'
counting += 1
if key[counting] == 'Z' or 'z' :
word += '26'
counting += 1
if key[counting] == ' ' :
word += '#'
counting += 1
finally:
return word
I want this module to let you input any phrase and convert the letters to numbers(A = 1, B =2, C = 3, etc.) and return the phrase back translated in numbers.
( I am not importing wrong)
To test I imputed 'Hello I am Sam' and I got back
['1', '2', '3', '4', '5', '6', '7', '8', '9', '1', '0', '1', '1', '1', '2', '1', '3', '1', '4'] This is obviously not right, so what is the problem.
This is the way my import looks
import random
from h import counter
key = "Hello I am Sam"
keyascii = counter(key)
print(key)
print(keyascii)

I am using ord to get the integer representation, and subtracting it with 64 to get the integer equivalent you specified in your code.
I am converting each character into uppercase, since you want both A and a to be 1, B and b to be 2 and so on. I am appending a whitespace character as it is
def counter(s):
result = ''
for c in s:
if c != ' ':
result += str(ord(c.upper())-64)
else:
result += ' '
return result
print(counter('ABC'))
print(counter('Hello I am Sam'))
#123
#85121215 9 113 19113

Related

Changing utf-8 string to cp1251 (Python)

I'm trying to convert Excel file with polish chars such as "ęśążćółń" to normal letters "esazcoln". Firstly I've menaged to convert xlsx file to txt, then:
f = open("PATH_TO_TXT_FILE")
r = f.read()
r.upper()
new_word = ""
for char in r:
if char == "Ą":
new_word += "A"
elif char == "Ć":
new_word += "C"
elif char == "Ę":
new_word += "E"
elif char == "Ł":
new_word += "L"
elif char == "Ó":
new_word += "O"
elif char == "Ż" "Ź":
new_word += "Z"
elif char == "Ź":
new_word += "Z"
elif char == "Ś":
new_word += "S"
else:
new_word += char
encoded_bytes = r.encode('utf-8', "replace")
decoded = encoded_bytes.decode(
"cp1252", "replace")
print(decoded)
in file is written : asdżółć
Output: asdżółć
I'd like to recive: asdzolc
Is there anybody who can help me?
I can't find the stack overflow page from which I got the pattern/sub template, but this is the general idea:
#!/usr/bin/env python3
# coding: UTF-8
import re
mapping = {
'Ą': 'A',
'Ć': 'C',
'Ę': 'E',
'Ł': 'L',
'Ó': 'O',
'Ż': 'Z',
'Ź': 'Z',
'Ś': 'S',
'ą': 'a',
'ć': 'c',
'ę': 'e',
'ł': 'l',
'ó': 'o',
'ż': 'z',
'ź': 'z',
'ś': 's',
}
pattern = re.compile("|".join(mapping.keys()))
def replace_by_mapping(text):
return pattern.sub(lambda m: mapping[re.escape(m.group(0))], text)
if __name__ == '__main__':
with open('polish_test.txt', 'r') as f:
contents = f.read()
contents = replace_by_mapping(contents)
print(contents)

converting phone letters to numbers and using while loop

I am currently writing function that takes in a string and converts that string (which is a phone number) into numbers only. In addition I am also using a while loop asking the user if they want to continue. My output is only showing me the first number or letter I type in, I want to know why. This is what I have so far:
def translate_num(convert):
answer=input('insert y to continue')
convert=input('Enter phone number here')
while answer=='y':
for word in convert:
phone_num=[]
if word == 'A' or word == 'B' or word == 'C':
phone_num.append('2')
elif word == 'D' or word == 'E' or word == 'F':
phone_num.append('3')
elif word == 'G' or word == 'H' or word == 'I':
phone_num.append('4')
elif word == 'J' or word == 'K' or word == 'L':
phone_num.append('5')
elif word == 'M' or word == 'N' or word == 'O':
phone_num.append('6')
elif word == 'P' or word == 'Q' or word == 'R' or word== 'S':
phone_num.append('7')
elif word == 'T' or word == 'U' or word == 'V':
phone_num.append('8')
elif word == 'W' or word == 'X' or word == 'Y' or word=='Z':
phone_num.append('9')
else:
phone_num.append(word)
print(phone_num)
answer=input('insert y to continue')
return
translate_num('555-361-FOOD')
you are re-initializing the phone_num with phone_num=[] value after going through each value in convert. Instead declare phone_num=[] once at the start of the function, also as pointed out by kabanus the return statement needs to be de-intended by a block. My implementation below seems to work (I have removed the redundant input statements since you are already calling the function, I have also added code to convert the number list back to a string :
def translate_num(convert):
#answer=input('insert y to continue')
#convert=input('Enter phone number here')
phone_num=[]
while True:
for word in convert:
if word == 'A' or word == 'B' or word == 'C':
phone_num.append('2')
elif word == 'D' or word == 'E' or word == 'F':
phone_num.append('3')
elif word == 'G' or word == 'H' or word == 'I':
phone_num.append('4')
elif word == 'J' or word == 'K' or word == 'L':
phone_num.append('5')
elif word == 'M' or word == 'N' or word == 'O':
phone_num.append('6')
elif word == 'P' or word == 'Q' or word == 'R' or word== 'S':
phone_num.append('7')
elif word == 'T' or word == 'U' or word == 'V':
phone_num.append('8')
elif word == 'W' or word == 'X' or word == 'Y' or word=='Z':
phone_num.append('9')
else:
phone_num.append(word)
#print(phone_num)
#answer=input('insert y to continue')
number=''
for item in phone_num:
number=number+str(item)
return (number)
print (translate_num('555-361-FOOD'))

My for loop is not iterating through all possible values

I'm trying to store substrings of letters in 's' that are in alphabetical order in a list
s = 'azcbobobegghakl'
string = ''
List = []
i = -1
for letter in s:
if letter == s[0]:
string += letter
elif letter >= s[i]:
string += letter
elif letter < s[i]:
List.append(string)
string = letter
i += 1
print(List)
My expected result:
['az', 'c', 'bo', 'bo', 'beggh', 'akl']
And my actual Output:
['az', 'c', 'bo', 'bo']
Firstly, your first if statement is incorrect. It should be if i == -1:. Because of this bug, you are ignoring the second a character in s.
Secondly, at the end of the string you don't add what's left of string into List.
As such, the following is what you want:
s = 'azcbobobegghakl'
string = ''
List = []
i = -1
for letter in s:
if i == -1:
string += letter
elif letter >= s[i]:
string += letter
elif letter < s[i]:
List.append(string)
string = letter
i += 1
List.append(string)
print(List)
An example is available here.

Why is this program not giving the expected output

MY CODE :
n = int(input())
arr = []
for i in range(0,n):
s = input().split()
for i in range(1,len(s)) :
s[i] = int(s[i])
if s[0] == "append" :
arr.append(s[1])
elif s[0] == "insert" :
arr.insert(s[1],s[2])
elif s[0] == "print" :
print(arr)
elif s[0] == "reverse" :
arr.reverse()
elif s[0] == "sort" :
arr.sort()
elif s[0] == "pop" :
arr.pop()
elif s[0] == "remove" :
arr.remove(s[1])
INPUT :
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
EXPECTED OUTPUT :
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
MY OUTPUT :
(No Output)
All of your lines from if s[0] == "append" to the end of the code are indented one level too many, making them part of the loop that converts the parameters to ints. This loop executes zero times for commands with no parameters, so in particular the "print" command does nothing.

NameError: name '' is not defined Python

i would like to make a blackjack algorithm and i have almost finished the code. Although i get all the time the error NameError: name 'pointCoint' is not defined. I found out on the internet that i should change raw_input into input due to the python version 3.6 which i am using. Can somebody help me and have a look at my code whether i am missing something? dealerCount = pointCoint(dealer)
NameError: name 'pointCoint' is not defined
Thanks
You have created a function called pointCount(...), not pointCoint. Change pointCoint to pointCount.
Complete code:
from random import shuffle
def deck():
deck = []
for suit in ['H', 'D', 'S', 'C']:
for rank in ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']:
deck.append(suit+rank)
shuffle(deck)
return deck
def pointCount(myCards):
myCount = 0
aceCount = 0
for i in myCards:
if(i[1] == 'J' or i[1] == 'Q' or i[1] == 'K' or i[1] == 'T'):
myCount += 10
elif(i[1] != 'A'):
myCount += int(i[1])
else:
aceCount += 1
if(aceCount == 1 and myCount >= 10):
myCount += 11
elif(aceCount != 0):
myCount += 1
return myCount
def createPlayingHands(myDeck):
dealerHand = []
playerHand = []
dealerHand.append(myDeck.pop())
dealerHand.append(myDeck.pop())
playerHand.append(myDeck.pop())
playerHand.append(myDeck.pop())
while(pointCount(dealerHand) <= 16):
dealerHand.append(myDeck.pop())
return [dealerHand, playerHand]
game = ""
myDeck = deck()
hands = createPlayingHands(myDeck)
dealer = hands[0]
player = hands[1]
while(game != "exit"):
dealerCount = pointCount(dealer)
playerCount = pointCount(player)
print("Dealer has:")
print(dealer[0])
print("Player1, you have:")
print(player)
if(playerCount == 21):
print("Blackjack Player wins")
break
elif(playerCount > 21):
print("player Busts with " + str(playerCount) + "points")
break
elif(playerCount > 21):
print("Dealer Busts with " + str(dealerCount) + "points")
break
game = input("What would you like to do? M: Hit me, S: Stand? ")
if(game == 'H'):
player.append(myDeck.pop())
elif(playerCount > dealerCount):
print("Player wins with " + str(playerCount) + "points")
print("Dealer has: " + str(dealer) + "or" + str(dealerCount) + "points")
break
else:
print("Dealer wins")
print("Dealer has: " + str(dealer) + "or" + str(dealerCount) + "points")
break

Resources