Variable within a number - python-2.7

This code ask for a message and a value to the user and then it modifies it with the given value. The problem is that I want the ASCII codes to not go over 126 or under 33, I tried to do so in the highlighted part of the code but when the value of the ASCII code gets over 126 the code returns me nothing for some reason.
loop = True
def start():
final_word = []
word_to_crypt = str(raw_input("Type a word: "))
crypt_value = int(raw_input("Choose a number to cript yout message with: "))
ascii_code = 0
n = 0
m = len(word_to_crypt)
m = int(m - 1)
while n <= m:
ascii_code = ord(word_to_crypt[n])
ascii_code += crypt_value
############# highlight #############
if 33 > ascii_code > 126:
ascii_code = (ascii_code%94)+33
############# highlight #############
final_word.append(chr(ascii_code))
n += 1
print 'Your crypted word is: ' + ''.join(final_word)
while loop:
start()
Sorry if it's not formatted well or for any mistakes in my explanation but I'm on my phone and I'm not native
Solved thank you very much this site and this community is helping me a lot!

There is no number that is greater than 126 and less than 33 at the same time. It should be:
if 33 < ascii_code < 126:
Edit:
If you want the reversed case, you will have to do it separately:
if ascii_code < 33 or ascii_code > 126:
Or you can just use the in operator and a list:
if ascii_code not in [33,126]:

Related

Find starting and ending index of each unique charcters in a string in python

I have a string with characters repeated. My Job is to find starting Index and ending index of each unique characters in that string. Below is my code.
import re
x = "aaabbbbcc"
xs = set(x)
for item in xs:
mo = re.search(item,x)
flag = item
m = mo.start()
n = mo.end()
print(flag,m,n)
Output :
a 0 1
b 3 4
c 7 8
Here the end index of the characters are not correct. I understand why it's happening but how can I pass the character to be matched dynamically to the regex search function. For instance if I hardcode the character in the search function it provides the desired output
x = 'aabbbbccc'
xs = set(x)
mo = re.search("[b]+",x)
flag = item
m = mo.start()
n = mo.end()
print(flag,m,n)
output:
b 2 5
The above function is providing correct result but here I can't pass the characters to be matched dynamically.
It will be really a help if someone can let me know how to achieve this any hint will also do. Thanks in advance
String literal formatting to the rescue:
import re
x = "aaabbbbcc"
xs = set(x)
for item in xs:
# for patterns better use raw strings - and format the letter into it
mo = re.search(fr"{item}+",x) # fr and rf work both :) its a raw formatted literal
flag = item
m = mo.start()
n = mo.end()
print(flag,m,n) # fix upper limit by n-1
Output:
a 0 3 # you do see that the upper limit is off by 1?
b 3 7 # see above for fix
c 7 9
Your pattern does not need the [] around the letter - you are matching just one anyhow.
Without regex1:
x = "aaabbbbcc"
last_ch = x[0]
start_idx = 0
# process the remainder
for idx,ch in enumerate(x[1:],1):
if last_ch == ch:
continue
else:
print(last_ch,start_idx, idx-1)
last_ch = ch
start_idx = idx
print(ch,start_idx,idx)
output:
a 0 2 # not off by 1
b 3 6
c 7 8
1RegEx: And now you have 2 problems...
Looking at the output, I'm guessing that another option would be,
import re
x = "aaabbbbcc"
xs = re.findall(r"((.)\2*)", x)
start = 0
output = ''
for item in xs:
end = start + len(item[0])
output += (f"{item[1]} {start} {end}\n")
start = end
print(output)
Output
a 0 3
b 3 7
c 7 9
I think it'll be in the Order of N, you can likely benchmark it though, if you like.
import re, time
timer_on = time.time()
for i in range(10000000):
x = "aabbbbccc"
xs = re.findall(r"((.)\2*)", x)
start = 0
output = ''
for item in xs:
end = start + len(item[0])
output += (f"{item[1]} {start} {end}\n")
start = end
timer_off = time.time()
timer_total = timer_off - timer_on
print(timer_total)

percentage bins based on predefined buckets

I have a series of numbers and I would like to know % of numbers falling in every bucket of a dataframe.
df['cuts'] have 10, 20 and 50 as values. Specifically, I would like to what % of series are in [0-10], (10-20] and (20-50] bin and this should be appended to the df dataframe.
I wrote the following code. I definitely feel that it could be improvised. Any help is appreciated.
bin_cuts = [-1] + list(df['cuts'].values)
out = pd.cut(series, bins = bin_cuts)
df_pct_bins = pd.value_counts(out, normalize= True).reset_index()
df_pct_bins = pd.concat([df_pct_bins['index'].str.split(', ', expand = True), df_pct_bins['cuts']], axis = 1)
df_pct_bins[1] = df_pct_bins[1].str[:-1].astype(str)
df['cuts'] = df['cuts'].astype(str)
df_pct_bins = pd.merge(df, df_pct_bins, left_on= 'cuts', right_on= 1)
Consider the sample data df and s
df = pd.DataFrame(dict(cuts=[10, 20, 50]))
s = pd.Series(np.random.randint(50, size=1000))
Option 1
np.searchsorted
c = df.cuts.values
df.assign(
pct=df.cuts.map(
pd.value_counts(
c[np.searchsorted(c, s)],
normalize=True
)))
cuts pct
0 10 0.216
1 20 0.206
2 50 0.578
Option 2
pd.cut
c = df.cuts.values
df.assign(
pct=df.cuts.map(
pd.cut(
s,
np.append(-np.inf, c),
labels=c
).value_counts(normalize=True)
))
cuts pct
0 10 0.216
1 20 0.206
2 50 0.578

I before E program not working

Just wrote a python program to determine how useful the mnemonic "I before E except after C" is.
With the input:
'I before e except when conducting an efficient heist on eight foreign neighbors. I believe my friend has left the receipt for the diet books hidden in the ceiling'
It would display:
Number of times the rule helped: 5
Number of times the rule was broken: 5
Changed a few things and thought I changed them back but the code is now broken, any advice will be helpful
while True:
line = input("Line: ")
count = 0
h = 0
nh = 0
words = line.split()
for x in range(0, len(words)):
word = words[count]
if "ie" in word:
if "cie" in word:
nh += 1
else:
h +=1
if "ei" in word:
if "cei" in word:
h += 1
else:
nh += 1
else:
h += 0
count += 1
print("Number of times the rule helped:",h)
print("Number of times the rule was broken:",nh)
print()
Good god I'm an idiot. I've probably spent a total of 3 hours or so trying to fix this thing.
for x in range(0, len(words)):
word = words[count]
if "ie" in word:
if "cie" in word:
nh += 1
else:
h +=1
if "ei" in word:
if "cei" in word:
h += 1
else:
nh += 1
count += 1
Can anyone spot the difference between this and the corresponding part of the old code? That 'count+=1' at the end is just indented an additional time. All those hours wasted... sorry if I wasted anyone else's time here :|
You'd be well-served to better articulate your test cases. I don't exactly understand what you're trying to do.
It seems like all you need is to see how many times 'cie' or 'cei' occurred in the text.
In which case:
for i in range(0, len(line)):
print("scanning {0}".format(line[i:i+3]))
if line[i:i+3].lower() == "cie":
nh += 1
if line[i:i+3].lower() == "cei":
h += 1

Loop problems Even Count

I have a beginner question. Loops are extremely hard for me to understand, so it's come to me asking for help.
I am trying to create a function to count the amount of even numbers in a user input list, with a negative at the end to show the end of the list. I know I need to use a while loop, but I am having trouble figuring out how to walk through the indexes of the input list. This is what I have so far, can anyone give me a hand?
def find_even_count(numlist):
count = 0
numlist.split()
while numlist > 0:
if numlist % 2 == 0:
count += 1
return count
numlist = raw_input("Please enter a list of numbers, with a negative at the end: ")
print find_even_count(numlist)
I used the split to separate out the indexes of the list, but I know I am doing something wrong. Can anyone point out what I am doing wrong, or point me to a good step by step explanation of what to do here?
Thank you guys so much, I know you probably have something more on your skill level to do, but appreciate the help!
You were pretty close, just a couple of corrections:
def find_even_count(numlist):
count = 0
lst = numlist.split()
for num in lst:
if int(num) % 2 == 0:
count += 1
return count
numlist = raw_input("Please enter a list of numbers, with a negative at the end: ")
print find_even_count(numlist)
I have used a for loop rather than a while loop, stored the outcome of numlist.split() to a variable (lst) and then just iterated over this.
You have a couple of problems:
You split numlist, but don't assign the resulting list to anything.
You then try to operate on numlist, which is still the string of all numbers.
You never try to convert anything to a number.
Instead, try:
def find_even_count(numlist):
count = 0
for numstr in numlist.split(): # iterate over the list
num = int(numstr) # convert each item to an integer
if num < 0:
break # stop when we hit a negative
elif num % 2 == 0:
count += 1 # increment count for even numbers
return count # return the total
Or, doing the whole thing in one line:
def find_even_count(numlist):
return sum(num % 2 for num in map(int, numlist.split()) if num > 0)
(Note: the one-liner will fail in cases where the user tries to trick you by putting more numbers after the "final" negative number, e.g. with numlist = "1 2 -1 3 4")
If you must use a while loop (which isn't really the best tool for the job), it would look like:
def find_even_count(numlist):
index = count = 0
numlist = list(map(int, numlist.split()))
while numlist[index] > 0:
if numlist[index] % 2 == 0:
count += 1
index += 1
return count

Assinging 1 character from 1 list to another python

Hi i am making a decryption machine for my school project but i cant get it to work can you guys help me out?
Thanks already.
the error is: line 17, IndexError: list index out of range
The length of zin = 86 just so you know
this is what is in the file i need to decrypt: KEIGO N JIDOUBANEUOFIDNEIESUN IRAEI ESTIGIVNKMUEEER RDONAEOIW ENEZAEE NAML VN NILLRA
with open('something.txt', 'r') as fhandle:
key = 3
#reading the file
zin = list(fhandle.readline())
#setting up solution to which we will output
solution = list(" ")*86
solution[0] = zin[0]
#while loop in which we use the key to decrypt the message
i = 1
while i < len(zin):
solution[i] = zin[key] #this is where i get the error
i += 1
key += key
if i > 86:
break
print(solution)
Since you are accessing zin[key], you need to verify length of zin is at least key+1.