My for loop is printing in the wrong order - python

Long story short I'm making an ASCII Art generator and having problems with my loops. It prints the right letters just in the wrong order. My input loop has another loop inside that is supposed to print the 1st line of the artwork based off each letter from the user's input but doesn't print them together if that makes any sense...
I've tried the following loop before and rearranging the statements in the loop, I honestly think I just need a pair of fresh eyes.
In advance I'm very sorry for any grammar, broken syntax talk/not making sense, and missing information. It's my first time using overflow and I haven't touched my IDE in ages. Any help is greatly appreciated!
boss = input("Text here: ")
for z in range(len(boss)):
for i in range(6):
if boss[z] == 'a':
print(ASCII["a" + str(i)], end='')
if boss[z] == 'b':
print(ASCII["b" + str(i)], end='')
print('')
z += 1
Here is the dict
ASCII = {
"a0" : " █████╗ ",
"a1" : "██╔══██╗",
"a2" : "███████║",
"a3" : "██╔══██║",
"a4" : "██║ ██║",
"a5" : "╚═╝ ╚═╝",
"b0" : "██████╗ ",
"b1" : "██╔══██╗",
"b2" : "██████╔╝",
"b3" : "██╔══██╗",
"b4" : "██████╔╝",
"b5" : "╚═════╝ "
}
Input:
Text here: ab
this is the desired output:
█████╗ ██████╗
██╔══██╗██╔══██╗
███████║██████╔╝
██╔══██║██╔══██╗
██║ ██║██████╔╝
╚═╝ ╚═╝╚═════╝
this is what I'm getting back:
█████╗
██╔══██╗
███████║
██╔══██║
██║ ██║
╚═╝ ╚═╝
██████╗
██╔══██╗
██████╔╝
██╔══██╗
██████╔╝
╚═════╝
Just for reference, it is very important that it prints like this:
a0 + b0
print('')
a1 + b1
print('')
a2 + b2
█████╗ ██████╗
then
█████╗ ██████╗
██╔══██╗██╔══██╗
then
█████╗ ██████╗
██╔══██╗██╔══██╗
███████║██████╔╝
etc.

The outer loop should iterate over the lines of the image, and the inner over letters in the input string:
ASCII = {
"a0" : " █████╗ ",
"a1" : "██╔══██╗",
"a2" : "███████║",
"a3" : "██╔══██║",
"a4" : "██║ ██║",
"a5" : "╚═╝ ╚═╝",
"b0" : "██████╗ ",
"b1" : "██╔══██╗",
"b2" : "██████╔╝",
"b3" : "██╔══██╗",
"b4" : "██████╔╝",
"b5" : "╚═════╝ "
}
boss = "abba"
for i in range(6):
for x in boss:
print(ASCII[x + str(i)], end='')
print('')
This prints:

Related

wrong key selection from dictionary

So I wrote a program that converted alphabets from a sentence to numbers. To understand whether the number was in the same word or another I made a distinction with "-" and "-". If a word is in the same line the numbers are separated by a "-" and if they are in another word they are separated by a "-". Like hi hi => 8-5-*-8-5-.
Now I was writing a program to do the opposite i.e convert numbers to alphabets using a dictionary. I wrote the dictionary like this -
Dictionary = {"26" : "z","25" : "y","24" : "x","23" : "w","22" : "v","21" : "u","20" : "t","19" : "s","18" : "r","17" : "q","16" : "p","15" : "o","14" : "n","13" : "m","12" : "l","11" : "k","10" :"j","1" : "a","2" : "b","3" : "c","4" : "d","5" : "e","6" : "f","7" : "g","8" : "h","9" : "i","*" : " "}
user_input = input("Please Enter a message: ")
count = user_input.count("-")
individual_number = user_input.split("-")
for i in range(0 , count):
for number in individual_number[i]:
individual_number[i] = individual_number[i].replace(number, Dictionary[number])
print(individual_number[i])
Now it Works for numbers from 1 - 9 but for 10 - 26, it does not work. For Example -
8-9-*-2-6- => h
i
b
f
But the same is for this one as well -
8-9-*-26- => h
i
bf (This should have been "Z")
I don't understand why it does that. it should take the whole number instead of taking each number one by one. Please help.
Also, I want it to print the whole sentence in one line/string. But I can't get it to do it. Please help with that too.
Thank you
To convert numbers to words use this one.
Dictionary = {"26" : "z","25" : "y","24" : "x","23" : "w","22" : "v","21" : "u","20" : "t","19" : "s","18" : "r","17" : "q","16" : "p","15" : "o","14" : "n","13" : "m","12" : "l","11" : "k","10" :"j","1" : "a","2" : "b","3" : "c","4" : "d","5" : "e","6" : "f","7" : "g","8" : "h","9" : "i","*" : " "}
user_input = input("Please Enter a message: ")
user_input = user_input.split('-')
output = ''
for a in user_input:
try:
output+=Dictionary[a]
except KeyError:
output+=''
print(output)
And for words to numbers use this one.
Dictionary = {"26" : "z","25" : "y","24" : "x","23" : "w","22" : "v","21" : "u","20" : "t","19" : "s","18" : "r","17" : "q","16" : "p","15" : "o","14" : "n","13" : "m","12" : "l","11" : "k","10" :"j","1" : "a","2" : "b","3" : "c","4" : "d","5" : "e","6" : "f","7" : "g","8" : "h","9" : "i","*" : " "}
Dictionary_ = {value:key for key,value in Dictionary.items()}
user_input = input("Please Enter a message: ")
output = ''
for a in user_input:
try:
output+=Dictionary_[a]
output+='-'
except KeyError:
output+=''
output = output[:-1]
print(output)
I think you're over-complicating things. Why the nested loop?
This seems to do what you want:
Dictionary = {"26" : "z","25" : "y","24" : "x","23" : "w","22" : "v","21" : "u","20" : "t","19" : "s","18" : "r","17" : "q","16" : "p","15" : "o","14" : "n","13" : "m","12" : "l","11" : "k","10" :"j","1" : "a","2" : "b","3" : "c","4" : "d","5" : "e","6" : "f","7" : "g","8" : "h","9" : "i","*" : " "}
user_input = input("Please Enter a message: ")
individual_number = user_input.split("-")
for number in individual_number:
print(Dictionary[number],end='')

create dict keys depending on the number of times the same value occurs

I have a dict as below, if the same value is found more tahn once then the dict key must be created with incremental numbering.
TT = {
"TYPE_1" : ['ERROR'],
"TYPE_2": ['FATAL'],
"TYPE_3" : ["TIME_OUT"],
"TYPE_4" : ['SYNTAX'],
"TYPE_5" : ['COMPILE'],
}
m1 = "ERROR the input is not proper"
m2 = "This should have not occured FATAL"
m3 = "Sorry TIME_OUT"
m4 = "SYNTAX not proper"
m5 = "u r late its TIME_OUT"
The value "TIME_OUT" occur twice in the search.
count = 0
for key in TT.keys():
print(key)
Key_1 = key
while key_1 in TT:
count = count+1
key_1 = key + "_{}".format(count)
The above code gives error Key_1 not defined.
Expected OUTPUT:
if the same value is occuring more than once then the dict key should be created with incremental numbering "TYPE_3_1" : ["TIME_OUT"],
TT = {
"TYPE_1" : ['ERROR'],
"TYPE_2": ['FATAL'],
"TYPE_3" : ["TIME_OUT"],
"TYPE_3_1" : ["TIME_OUT"],
"TYPE_4" : ['SYNTAX'],
"TYPE_5" : ['COMPILE'],
}
Please suggest on this.
There can be a much efficient way of solving this if you can rethink about some of the data structure but if that is not an option you may be able to try this.
inputs = ["ERROR the input is not proper",
"This should have not occured FATAL",
"Sorry TIME_OUT",
"SYNTAX not proper",
"u r late its TIME_OUT"]
basic_types = {
"TYPE_1" : ['ERROR'],
"TYPE_2": ['FATAL'],
"TYPE_3" : ["TIME_OUT"],
"TYPE_4" : ['SYNTAX'],
"TYPE_5" : ['COMPILE'],
}
type_counts = {}
results = {}
for sentence in inputs:
for basic_type in basic_types:
if basic_types.get(basic_type)[0] in sentence:
type_counts[basic_type] = type_counts.get(basic_type, 0) + 1
if type_counts[basic_type] == 1:
results[basic_type] = [basic_types.get(basic_type)[0]]
else:
results[basic_type+"_{}".format(type_counts[basic_type] - 1)] = [basic_types.get(basic_type)[0]]
print(results)

foreign language translation dictionary

I am trying to compile a dictionary on Python of new words which I have learnt. The program will then test my knowledge of the words by asking me to translate random keys from the dictionary.
Here is what I have at the moment:
import random
witcher_dic = {'bridles' : 'уздцы' , 'hum' : 'гул' , 'to become deserted' : 'опустеть', 'linen' : 'полотяный' , 'apron' : 'фартук' ,
'pockmarked (object)' : 'щербатый' , 'quiver (arrow)' : 'колчан' , 'to take a sip' : 'обхлебнуть' ,
'to grunt' : 'буркнуть' , 'vile/foul' : 'паскудный' , 'pockmarked (person)' : 'рябой' , 'big-man' : 'верзила' ,
'punk' : 'шпана' , 'to bark (person)' : 'гархнуть' , 'bastard, premature child' : 'недосонок' ,
'to mumble' : 'промямлить' , 'to bark (person2)' : 'рявкнуть' , 'to look around oneself' : 'озираться' ,
'oliquely' : 'наискось' , 'a mess/fuss' : 'кутерьма' , 'bolt (sound)' : 'грохот' , 'to blink' : 'шмяхнуться' ,
'dissected' : 'рассеченный' , 'to wriggle' : 'извиваться', 'tender/sensitive' : 'чуткий' , 'to hang to' : 'облепить',
'a clang/clash' : 'лязг' , 'to snuggle up to' : 'прильнуть' , 'boot-leg' : 'голенищ' , 'stuffing' : 'набивки' ,
'cuffs' : 'манжеты' , 'to jump up' : 'вскочить' , 'to dart off' : 'помчаться' , 'to scream' : 'заволить' , 'shrilly' : 'пронзительно',
'to back away' : 'пятиться' , 'loaded (horse)' : 'навьюченный'}
def ranWord():
word = random.choice(list(witcher_dic.keys()))
return word
while True:
print(ranWord())
guess = input('Please enter the translation for this word: ')
if guess == witcher_dic[word]:
print('Well done!')
else:
input(print('Please try again: '))
input('Press any key to exit')
Apologies for format and indentation but am new to stackoverflow and still learning the ropes!
I suppose the problem is on the line: if guess == witcher_dic[word]
The program should match the user entry to the dictionary value.
There were a few problems with your code.
1.) to use non ascii characters you need to declare the encoding with a "magic" comment
2.) ranWord only defines word in its own scope so you cant use it outside the function. I would recommend learning about scope
3.) input(print(str)) is invalid syntax. use input(str)
4.) this is not really a problem but you never exit the while loop so you would be translating words forever. You can decide how you want handle that
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#include these!^
import random
witcher_dic = {'bridles' : 'уздцы' , 'hum' : 'гул' , 'to become deserted' : 'опустеть', 'linen' : 'полотяный' , 'apron' : 'фартук' ,
'pockmarked (object)' : 'щербатый' , 'quiver (arrow)' : 'колчан' , 'to take a sip' : 'обхлебнуть' ,
'to grunt' : 'буркнуть' , 'vile/foul' : 'паскудный' , 'pockmarked (person)' : 'рябой' , 'big-man' : 'верзила' ,
'punk' : 'шпана' , 'to bark (person)' : 'гархнуть' , 'bastard, premature child' : 'недосонок' ,
'to mumble' : 'промямлить' , 'to bark (person2)' : 'рявкнуть' , 'to look around oneself' : 'озираться' ,
'oliquely' : 'наискось' , 'a mess/fuss' : 'кутерьма' , 'bolt (sound)' : 'грохот' , 'to blink' : 'шмяхнуться' ,
'dissected' : 'рассеченный' , 'to wriggle' : 'извиваться', 'tender/sensitive' : 'чуткий' , 'to hang to' : 'облепить',
'a clang/clash' : 'лязг' , 'to snuggle up to' : 'прильнуть' , 'boot-leg' : 'голенищ' , 'stuffing' : 'набивки' ,
'cuffs' : 'манжеты' , 'to jump up' : 'вскочить' , 'to dart off' : 'помчаться' , 'to scream' : 'заволить' , 'shrilly' : 'пронзительно',
'to back away' : 'пятиться' , 'loaded (horse)' : 'навьюченный'}
def ranWord():
word = random.choice(list(witcher_dic.keys()))
return word
while True:
wrd = ranWord()
print(wrd)
guess = input('Please enter the translation for this word: ')
if guess == witcher_dic[wrd]:
print('Well done!') # maybe break here after a certain amount correct?
else:
input('Please try again: ') #or instead of trying again you can just lose when you answer incorrectly
input('Press any key to exit')
Here are the problems I can see:
The result of the call to ranWord is not saved anywhere. You use word a bit later on but it will not be defined. You should do word = ranWord() and then something like guess = input(f'Please enter the translation for {word}: ').
If the player guesses correctly, the loop continues anyway. Add a break statement to terminate the loop after printing Well done!.
The Please try again line seems unnecessary; when the loop restarts it will prompt the player for a new guess. Remove the else, or replace the second input call with print(Your guess was incorrect.).

printing from nested dictionaries in classes

Having isues figuring out why this particular setup isnt working.
class market(object):
def __init__(self, market, coin):
self.coin = coin
self.market = market
req = requests.get(f"http://bittrex.com/api/v1.1/public/getticker?market={market}-{coin}")
sum = requests.get(f"https://bittrex.com/api/v1.1/public/getmarketsummary?market={market}-{coin}")
self.address = req.json()
self.marketsum = sum.json()
def ticker(self):
while True:
print(self.address["result"])
time.sleep(5)
def marketsummary(self):
print(f"Market Summary for {coin}")
print('_' * 20)
print("Market Name: ", self.marketsum['result']['MarketName'])
print("High: ", self.marketsum['result']['High']))
print("Low: ", self.marketsum['result']['Low'])
print("Volume: ", self.marketsum['result']['Volume'])
print("Last: ", self.marketsum['result']['Last'])
print("BaseVolume: ", self.marketsum['result']['BaseVolume'])
print("TimeStamp: ", self.marketsum['result']['TimeStamp'])
print("Bid: ", self.marketsum['result']['Bid'])
print("Ask: ", self.marketsum['result']['Ask'])
print("OpenBuyOrders: ", self.marketsum['result']['OpenBuyOrders'])
print("OpenSellOrders: ", self.marketsum['result']['OpenSellOrders'])
print("Previous Day: ", self.marketsum['result']['PrevDay'])
print("Created: ", self.marketsum['result']['Created'])
print("DisplayMarketName: ", self.marketsum['result']['DisplayMarketName'])`
Ive previously used this method with static(?jaron?) variables in if statements, such as
usdt_ticker = requests.get("https://bittrex.com/api/v1.1/public/getticker?market=USDT-ADA")
btc_ticker = requests.get("https://bittrex.com/api/v1.1/public/getticker?market=BTC-ADA")
eth_ticker = requests.get("https://bittrex.com/api/v1.1/public/getticker?market=ETH-ADA")
print("Which trade pairing would you like for this coin?")
tradepair = input("> ")
if str.lower(tradepair) == "usdt" or "tether":
actual_ticker = usdt_ticker.json()
elif str.lower(tradepair) == "btc" or "bitcoin":
actual_ticker = btc_ticker.json()
elif str.lower(tradepair) == "eth" or "ethereum":
actual_ticker = eth_ticker.json()
else:
print("Sorry that trading pair isnt currently being monitored by this system")
print("Now viewing Cardano /", str.upper(tradepair), " trading." )
current_price = actual_ticker["result"]["Last"]
but with the self.marketsum['result']['MarketName'] its not working. If theres any input as to why this is happening and how to fix it I would be greatly appreciative. The error I am getting is
TypeError: list indicies must be integers or slices, not str
From the developer's guide, the json structure of a response from /public/getmarketsummary looks like:
{
"success" : true,
"message" : "",
"result" : [{
"MarketName" : "BTC-LTC",
"High" : 0.01350000,
"Low" : 0.01200000,
"Volume" : 3833.97619253,
"Last" : 0.01349998,
"BaseVolume" : 47.03987026,
"TimeStamp" : "2014-07-09T07:22:16.72",
"Bid" : 0.01271001,
"Ask" : 0.01291100,
"OpenBuyOrders" : 45,
"OpenSellOrders" : 45,
"PrevDay" : 0.01229501,
"Created" : "2014-02-13T00:00:00",
"DisplayMarketName" : null
}
]
}
Notice the result is actually a list containing a single element. They don't state why it is in a list and I can't get it to return a list with more than one element.
For now, it should be fine to change the lines accessing marketsum from
self.marketsum['result']['last']
to
self.marketsum['result'][0]['last']
Probably also add a check that the list is not empty.

python with SQL (NEWBIE WARNING)

counter=cur.rowcount
if(counter !=0):
values =[]
x=0
for row in content:
dValue, dYearOf, dMonthOf, Department = row
sent = str(dValue)
x=x+1
q=0
NounNum = 0
for noun in Noun:
AdjectiveNum=0
if " "+noun+" " in sent:
for adjective in Adjective:
AdjectiveNum=AdjectiveNum+1
if " "+adjective+" " in dValue:
sup=[]
for support in Support:
if " "+support+" " in sent:
sup=sup+[support]
supp = '-'.join(map(str, sup))
values.append(x.to_bytes)
values.append(noun)
values.append(NA[NounNum])
values.append(adjective)
values.append(supp)
values.append(dMonthOf)
values.append(dYearOf)
values.append(Department[:2])
f_value= ','.join(map(str, values))
sql=("""NSERT INTO `text_mining`(`Count`, `Noun`, `Noun_Code`, `Support`, `Adjective`, `Month`, `Year`, `Division`) VALUES (%s)""")
print(sql,f_value)
cur.execute(sql,f_value)
how can I put the an array value in my insert query? i tried some ways but I am trying to make an string that will combine all of my variable into 1 including with my array. obviously i am new with this so please help

Categories

Resources