I've been write this practice program for while now, the whole purpose of the code is to get user input and generate passwords, everything almost works, but the replace statements are driving me nuts. Maybe one of you smart programmers can help me, because I'm kinda new to this whole field of programming. The issue is that replace statement only seems to work with the first char in Strng, but not the others one. The other funcs blower the last run first and then the middle one runs.
def Manip(Strng):
#Strng = 'jayjay'
print (Strng.replace('j','h',1))
#Displays: 'hayjay'
print (Strng.replace('j','h',4))
#Displays: 'hayhay'
return
def Add_nums(Strng):
Size=len(str(Strng))
Total_per = str(Strng).count('%')
# Get The % Spots Position, So they only get replaced with numbers during permutation
currnt_Pos = 0
per = [] # % position per for percent
rGen = ''
for i in str(Strng):
if i == str('%'):
per.append(currnt_Pos)
currnt_Pos+=1
for num,pos in zip(str(self.ints),per):
rGen = Strng.replace(str(Strng[pos]),str(num),4);
return rGen
for pos in AlphaB: # DataBase Of The Positions Of Alphabets
for letter in self.alphas: #letters in The User Inputs
GenPass=(self.forms.replace(self.forms[pos],letter,int(pos)))
# Not Fully Formatted yet; you got something like Cat%%%, so you can use another function to change % to nums
# And use the permutations function to generate other passwrds and then
# continue to the rest of this for loop which will generate something like cat222 or cat333
Add_nums(GenPass) # The Function That will add numbers to the Cat%%%
print (rGen);exit()
Related
I have a class for data entry that requires a lot of input from the user. I use it to semi-automate the process of putting stuff in the db where it is possible.
My instinct is to put it in my model classes, and write tests on it, but it would be an insane amount of work, and I have a lot of raw_input() functions and logic loops that I don't know how to test or what to do with.
Should I keep this module separate or try to include it in the model classes?
def define(self, word=False, word_pk=False):
'''Defining a word, there may be language specific elements to edit in here'''
try:
if word_pk:
word = Word.objects.get(id=word_pk)
else:
word = Word.objects.get(language__name=self.language_ISO, name=word)
except:
return "Word lookup failed for word=%s word_pk=%s\n" % (word, word_pk)
print "\n\tThe Word is: '%s'...\n" % (word)
wiktionary_list = word.wiktionary_lookup(self.wiktionary_prefix, self.driver)
wn_tuple = word.wn_lookup()
while choice("Would you like to add a/another definition for '%s'?: " % word):
#Ask the user if they want to use the wn output for definitions, make them select which ones
if choice("Would you like to choose a wordnet definition?: "):
chosen_defs = ask_input("Which ones? (choose all that apply with a space between numbers): ")
chosen_defs = [int(i) for i in (chosen_defs.split())]
#Wornet only gives part of speech and definition information so I need to split that here.
for i in chosen_defs:
#Print_n_save function will return False if it exits successfully, so there is an option to repeat this loop if the user makes a mistake somewhere
repeat = True
while repeat:
tup = wn_tuple[i]
print "\n(%s) - %s\n" % (tup[0], tup[1])
audio_tup = self.add_audio(word)
picture_tup = self.add_picture(word)
new_definition = Definition()
new_definition.word=word
new_definition.part_speech= tup[0]
new_definition.definition=tup[1]
new_definition.def_source="Wordnet"
new_definition.add_pronunciation()
new_definition.word_audio=audio_tup[0]
new_definition.audio_source=audio_tup[1]
new_definition.picture=picture_tup[0]
new_definition.pic_source=picture_tup[1]
repeat = self.print_n_save(new_definition)
elif choice("Would you like to choose a wiktionary definition?: "):
choose_defs = ask_input("Which ones would you like to choose? (Numbers separated by spaces): ")
chosen_defs = [int(i) for i in choose_defs.split()]
for i in chosen_defs:
#Print_n_save function will return False if it exits successfully, so there is an option to repeat this loop if the user makes a mistake somewhere
repeat = True
while repeat:
print "\n%s\n" % (wiktionary_list[i])
audio_tup = self.add_audio(word)
picture_tup = self.add_picture(word)
new_definition = Definition()
new_definition.word=word
new_definition.get_pos()
new_definition.definition=wiktionary_list[i]
new_definition.def_source="Wiktionary"
new_definition.add_pronunciation()
new_definition.word_audio=audio_tup[0]
new_definition.audio_source=audio_tup[1]
new_definition.picture=picture_tup[0]
new_definition.pic_source=picture_tup[1]
repeat = self.print_n_save(new_definition)
else:
#Print_n_save function will return False if it exits successfully, so there is an option to repeat this loop if the user makes a mistake somewhere
repeat = True
while repeat:
#Asking for definition, inputting raw from some internet source
definition = ask_input("What is the definition?: ")
definition_source = ask_input("What is the source of the definition?: ")
audio_tup = self.add_audio(word)
picture_tup = self.add_picture(word)
new_definition = Definition()
new_definition.word=word
new_definition.get_pos()
new_definition.definition=definition
new_definition.def_source=definition_source
new_definition.add_pronunciation()
new_definition.word_audio=audio_tup[0]
new_definition.audio_source=audio_tup[1]
new_definition.picture=picture_tup[0]
new_definition.pic_source=picture_tup[1]
repeat = self.print_n_save(new_definition)
Don't try to force a raw python function into a single box.
What you should have done (a long long time ago), is separate it out into separate functions so it would be easier to test and figure things out.
Since you're asking for user input, websites do that through forms, so you're going to need a form - or a form wizard/set/whatever.
That form is going to need at least one view to handle it, so you might need to write that too, or use a generic view.
Who knows, the model might even need to do something post processing (I didn't really read the code)
I would put this into management/commands. Just wrap your functions into a BaseCommand class and you are good to go. And here is how to make testing.
Im currently trying to code a transposition cipher in python. however i have reached a point where im stuck.
my code:
key = "german"
length = len(key)
plaintext = "if your happy and you know it clap your hands, clap your hands"
Formatted = "".join(plaintext.split()).replace(",","")
split = split_text(formatted,length)
def split_text(formatted,length):
return [formatted[i:i + length] for i in range(0, len(formatted), length)]
def encrypt():
i use that to count the length of the string, i then use the length to determine how many columns to create within the program. So it would create this:
GERMAN
IFYOUR
HAPPYA
NDYOUK
NOWITC
LAPYOU
RHANDS
CLAPYO
URHAND
S
this is know where im stuck. as i want to get the program to create a string by combining the columns together. so it would combine each column to create:
IHNNLRCUSFADOAHLRYPYWPAAH .....
i know i would need a loop of some sort but unsure how i would tell the program to create such a string.
thanks
you can use slices of the string to get each letter of the string in steps of 6 (length)
print(formatted[0::length])
#output:
ihnnlrcus
Then just loop through all the possible start indices in range(length) and link them all together:
def encrypt(formatted,length):
return "".join([formatted[i::length] for i in range(length)])
note that this doesn't actually use split_text, it would take formatted directly:
print(encrypt(formatted,length))
the problem with using the split_text you then cannot make use of tools like zip since they stop when the first iterator stops (so because the last group only has one character in it you only get the one group from zip(*split))
for i in zip("stuff that is important","a"):
print(i)
#output:
("s","a")
#nothing else, since one of the iterators finished.
In order to use something like that you would have to redefine the way zip works by allowing some of the iterators to finish and continue until all of them are done:
def myzip(*iterators):
iterators = tuple(iter(it) for it in iterators)
while True: #broken when none of iterators still have items in them
group = []
for it in iterators:
try:
group.append(next(it))
except StopIteration:
pass
if group:
yield group
else:
return #none of the iterators still had items in them
then you can use this to process the split up data like this:
encrypted_data = ''.join(''.join(x) for x in myzip(*split))
I'm trying to create a typewriter effect for text being blitted. By typewriter effect, I simply mean that Im trying to avoid the entirety of the text being blitted on screen at once. Instead, im trying to have each letter appear individually, with a slight delay before the next character in the string appears.
The catch is that im not using pygame's font.render. Instead, i've made my own custom fonts, each letter being saved as a separate image file. Now each alphanumeric character has it's own variable to which it's image is attached and each is appended to a list.
e.g:
letter_IMGs = []
a = "a" == pygame.image.load("IMG/letter_a.gif)
letter_IMG.append(a)
Lower, I have something along these lines:
letter_pos_x = 0
text = "Hello"
for i, c in enumerate(text):
screen.blit(letter_IMGs[i], (letter_pos_x,0))
letter_pos_x += 20
scroll_wait #this is a clock.delay variable. It's value was set outside the loop. I'm just calling it here.
Now as you'd guess, the result with that code is that the entire line of text appears simultaneously after the delay. I've been trying to code it as needed from there, but most of what I come up with returns with a "cannot iterate through surface objects" error.
I'm pretty much at a loss on how I should proceed next. Note that, ive been learning a bit of code on my own, on and off, for the past year and that I don't really know what im doing yet. Any and all help will be much appreciated.
Thanks in advance for your time.
Without getting into the pygame specifices too much, you just need to change the iterator so it returns substrings rather than letters:
def iterate_text(text):
for r in range(len(text)):
yield text[:r + 1]
which will return the substring iteratively:
for t in iterate_text('hello'):
print t
# h
# he
# hel
# hell
# hello
use a separate function to draw the string:
def draw_text(x, y, text):
characters = [letter_IMGs[t] for t in text]
cursor = x
for char in characters:
screen.blit(char, cursor, y)
cursor += 20
in your main loop you can decide when to get the next character. You'll basically do something like:
typewriter = iter_text('hello world')
text_to_draw = None
advance_text = False
at a level outside the loop that survive from frame to frame. When you want to draw the next character, you set advance_text to True, in and in the main loop:
if typewriter and advance_text:
text_to_draw = typewriter.next()
advance_text = False # until you set it again
if text_to_draw :
draw_text(0,0, draw_text)
You can start over by resetting the typewriter with new text, and control the timing of the new character appearing by setting advance_text to True before the next frame
Current assignment is building a basic text adventure. I'm having trouble with the following code. The current assignment uses only functions, and that is the way the rules of the assignment state it must be done.
def make_selections(response):
repeat = True
while repeat == True:
selection = raw_input('-> ')
for i, v in enumerate(response):
i +=1 # adds 1 to the index to make list indices correlate to a regular 1,2,3 style list
if selection == i:
print v[1]
else:
print "There's an error man, what are you doing?!?!?"
firstResponse = 'You chose option one.'
secondResponse = 'You chose option two.'
thirdResponse = 'You chose option three.'
responses = [(0, firstResponse), (1, secondResponse),( 0, thirdResponse)]
make_selections(responses)
My intention in that code is to make it so if the user selects a 1, it will return firstResponse, if the user selects 2 it will return secondResponse, etc.
I am basically just bug testing the code to make sure it produces the appropriate response, hence the "Error man..." string, but for some reason it just loops through the error message without printing the appropriate response string. Why is this?
I know that this code is enumerating the list of tuples and I can call them properly, as I can change the code to the following and get the expected output:
for i, v in enumerate(response):
i += 1 # adds 1 to the index to make list indices correlate to a regular 1,2,3 style list
print i, v
Also, two quick asides before anyone asks:
I know there is currently no way to get out of this while loop. I'm just making sure each part of my code works before I move on to the next part. Which brings me to the point of the tuples.
When I get the code working, a 0 will produce the response message and loop again, asking the user to make a different selection, whereas a 1 will produce the appropriate response, break out of the loop, and move on to the next 'room' in the story... this way I can have as many 'rooms' for as long of a story as I want, the player does not have to 'die' each time they make an incorrect selection, and each 'room' can have any arbitrary amount of options and possible responses to choose from and I don't need to keep writing separate loops for each room.
There are a few problems here.
First, there's no good reason to iterate through all the numbers just to see if one of them matches selection; you already know that will be true if 1 <= selection <= len(response), and you can then just do response[selection-1] to get the v. (If you know anything about dicts, you might be able to see an even more convenient way to write this whole thing… but if not, don't worry about it.)
But if you really want to do this exhaustive search, you shouldn't print out There is an error man after any mismatch, because then you're always going to print it at least twice. Instead, you want to only print it if all of them failed to match. You can do this by keeping track of a "matched" flag, or by using a break and an else: clause on your for loop, whichever seems simpler, but you have to do something. See break and continue Statements, and else Clauses on Loops in the tutorial for more details.
But the biggest problem is that raw_input returns a string, and there's no way a string is ever going to be equal to a number. For example, try '1' == 1 in your interactive interpreter, and it'll say False. So, what you need to do is convert the user's input into a number so you can compare it. You can do that like this:
try:
selection = int(selection)
except ValueError:
print "That's not a number!"
continue
Seems like this is a job for dictionaries in python. Not sure if your assignment allows this, but here's my code:
def make_selections(response):
selection = raw_input('-> ')
print response.get(selection, err_msg)
resp_dict = {
'1':'You chose option one.',
'2':'You chose option two.',
'3':'You chose option three.'
}
err_msg = 'Sorry, you must pick one of these choices: %s'%sorted(resp_dict.keys())
make_selections(resp_dict)
The problem is that you are comparing a string to an integer. Selection is raw input, so it comes in as a str. Convert it to an int and it will evaluate as you expect.
You can check the type of a variable by using type(var). For example, print type(selection) after you take the input will return type 'str'.
def make_selections(response):
repeat = True
while repeat == True:
selection = raw_input('-> ')
for i, v in enumerate(response):
i +=1 # adds 1 to the index to make list indices correlate to a regular 1,2,3 style list
if int(selection) == i:
print v[1]
else:
print "There's an error man, what are you doing?!?!?"
I have a script that pulls some data from a network device, strips off some crap and returns a value via a re.search.
the end result is i have two variables that contain a numerical value, say file1 contains one line with '10', file2 contains one line with '20'. i've put these into variables
oldnumber = 10
newnumber = 20
what i need to do is check to see if the numbers are the same value. if the numbers are the same, do nothing. if they aren't the same, then do something else - ie. send a mail to myself (smtplib works for me).
i'm new to python and finding my way, not sure how to code this?
i suppose the simplest way to describe this is if oldnumber = newnumber, then send mail, else do nothing.
If I remember well you're right
just do
if oldnumber!=newnumber;
do what you want
http://www.tutorialspoint.com/python/python_if_else.htm
almost right.
if oldnumber != newnumber:
# do something
# and then proceed..
Or:
if oldnumber == newnumber:
# do this
else:
# do that
# and then proceed..