Creating my own string functions [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
def tlower(str1):
list = list(str1)
final = ''
for char in range(0,len(str1)):
if list[char] in UPPERCASE:
for ascii in range(0,len(UPPERCASE)):
if list[char] == UPPERCASE[ascii]:
list[char] = LOWERCASE[ascii]
final += list[char]
return final
NOTE - UPPERCASE and LOWERCASE are strings of all upper/lowercase letters
NOTE - can NOT use any string functions built into python (Replace, etc..)
I have this function to turn any string into all lower case, (Yes i know there is a built in function..) But compared to my other string functions I have created, this is fairly long, any better approach I should take to do doing this?

UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
def to_lower(s, trans=dict(zip(UPPERCASE, LOWERCASE))):
return ''.join(trans.get(ch,ch) for ch in s)
print to_lower('This Is a TEST') # => 'this is a test'
Edit:
zip() takes two lists and returns pairs of values, ie
zip('ABC', 'abc') # => [('A','a'), ('B','b'), ('C','c')]
dict() makes a dictionary - in this case,
{'A':'a', 'B':'b', 'C':'c'}
trans.get(x, y) is a more compact way of saying as trans[x] if x in trans else y. In this case, "if you have a lowercase version of this letter, return it, otherwise give back the original letter".
and if you don't like .join, how about reduce?
from operator import add
def to_lower(s, trans=dict(zip(UPPERCASE, LOWERCASE))):
return reduce(add, (trans.get(ch,ch) for ch in s), '')

For completeness:
def to_lower(string):
ords = (ord(c) for c in string)
return ''.join(chr(o + 32 * (65 <= o <= 90)) for o in ords)

Related

I want to create a function where for every word of the alphabet [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
I want to create a function where for every word of the alphabet the user uses for an input, the console returns the following:
a = 0
b = 00
c - 000
And sow on...
Example: Sow if the user put the input of "abc", the console will print out: 000000
In my code, i can't seem to add the letters, hers the code:
def codifier():
userImp = input(str("write a word: "))
if userImp == "a":
print("0")
else:
userImp == "b"
print("00")
print(userImp)
codifier()
MY question is how would you write the code?
Make a dictionary mapping characters to the symbol you want.
>>> m = {'a':'0','b':'00', 'c':'000'}
Then use it along with a user's input
>>> r = input('??')
??ab
>>> ''.join(m[c] for c in r)
'000'
>>> r = input('??')
??ac
>>> ''.join(m[c] for c in r)
'0000'
>>> r = input('??')
??abc
>>> ''.join(m[c] for c in r)
'000000'
>>>
Here is a simple program that does what you are asking for:
def codifier():
userImp = input(str("write a word: "))
for char in userImp:
print(end="0" * (ord(char) - ord('a') + 1))
codifier()

Get n Characters from String specified in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Let s = "%2ABCDE" - get first 2 characters from string
then output should be "AB".
Need to get characters from string specified by numeral in string.
E.g. s1="%12ABCDERTYUIOPLKHGF" - get first 12 characters from string.
I tried to get digit using re.findall('\d+', string ), but this creates problem if my string would be "%2ABCD1".
Please suggest
s = "%2ABCDE"
number = ""
offset = 0
for i in range(len(s)):
if s[i] == "%":
continue
elif s[i].isdigit():
number += s[i]
else:
offset = i
break
print(s[offset:int(number) + offset])
Output: AB
A simpler way of doing this would be to do the following:
txt = "%2ABCDE"
number_list = [s for s in txt if s.isdigit()]
number_concate = int("".join(number_list))
txt_filtered = txt[len(number_list)+1:]
print(txt_filtered[:number_concate])
Outputs AB for string "%2ABCDE"
Outputs ABCDERTYUIOP for string "%12ABCDERTYUIOPLKHGF"
You are taking your string, doing a list comprehension of the string if the digit exists, then joining the list and changing this to an integer to allow for you to filter your string accordingly. Then you strip the string to only the characters and you have your answer printed out.
import re
s = '%2ABCDERTYUIOPLKHGF'
numeral_instruction = re.search(r'%\d+',s).group(0)
start = len(numeral_instruction)
stop = start + int(numeral_instruction[1:])
s[start:stop]
outputs
AB
You can get the position of the first non-digit character in the string (skipping the %) and use that as the basis to get the length and form a substring:
s1="%12ABCDERTYUIOPLKHGF"
i = next(i for i,c in enumerate(s1[1:],1) if not c.isdigit())
result = s1[i:i+int(s1[1:i])]
print(result)
ABCDERTYUIOP
If the first number in the string is not always at index 1, you can skip a variable number of characters using the same technique:
s1="*:%12ABCDERTYUIOPLKHGF"
start = next(i for i,c in enumerate(s1) if c.isdigit())
end = next(i for i,c in enumerate(s1[start:],start) if not c.isdigit())
result = s1[end:end+int(s1[start:end])]
print(result)
ABCDERTYUIOP
If you want to use the re module, you only need the first occurrence of a number, so use re.search() instead of re.findall():
import re
m = re.search(r"\d+",s1)
result = s1[m.end():m.end()+int(m.group())]
print(result)
ABCDERTYUIOP

How can I generate all possible words with a specified set of characters? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I play to HackNet game and i have to guess a word to bypass a firewall.
The key makes 6 characters long and contains the letters K,K,K,U,A,N.
What is the simplest way to generate all possible combinations either in bash or in python ? (bonus point for bash)
Here is a backtracking-based solution in Python:
db = {"K" : 3, "U" : 1, "A" : 1, "N" : 1}
N = 6
def possibilities(v):
l = []
for k in db.keys():
if v.count(k) < db[k]:
l.append(k)
return l
def generateImpl(a):
if len(a) < N:
lst = []
for c in possibilities(a):
lst += generateImpl(a+[c])
return lst
else:
return [''.join(a)]
def generate():
return generateImpl([])
Just run generate() to obtain a list of possible words.
You have 6 letters and need to find a combination of 6 letters. If you are not using the same character in ['K','K','K','U','A','N'] again and again, then there is only 1 permutation.
If you can use the same character again and again, you can use the following code to generate all possible combinations.
import itertools
y = itertools.combinations_with_replacement(['K','U','A','N'],6)
for i in list(y):
print(i)

Python numeric values for letters in string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am having trouble solving the following question,
Q: Given a string find out the total sum of all the numbers.
Values are as A-1, B-10, C-100, D-1000, E-10000.
Ex. DDBC. Answer is 1000+1000+10+100 = 2110.
There are lots of ways to go about this.
Here's one idea:
Make a lookup that maps letters to the their values. Something like:
import string
lookup = {s: 10**i for i,s in enumerate(string.ascii_uppercase)}
Lookup will be a dictionary like:
{
'A': 1,
'B': 10,
'C': 100,
'D': 1000,
'E': 10000,
'F': 100000,
...
}
With that you can use a comprehension and take the sum:
>> s = "DDBC"
>> sum(lookup[l] for l in s)
2110
This, of course, assumes your string is all uppercase, like the example you posted.
just deduce the power of 10 by the position of the letter:
s = "DDBC"
result = sum(10**(ord(c)-ord('A')) for c in s)
result: 2110
You can filter out lowercase letters & other chars easily, but that complexifies a little bit:
result = sum(10**(ord(c.upper())-ord('A')) for c in s if c.isalpha())
Try searching the string, and every instance of that letter occurring causes you to add to total.
For instance:
total = 0
input_string = input()
for i in len(input_string):
if input_string[i] == "A":
total += 1
and then you can repeat that for the other instances of the other characters.
Hope I helped!

Perfect hash function (i.e. no collisions) with same length [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I'm looking for a simple hash function that yields no collisions.
I have an alphanumeric sequence (say 16 letter long) and I want each one of them to map to unique hashed value. Ideally, the hashed value is the same length as the original sequence (16 letter long).
Is there a simple python hash function that achieves this?
Use something like
u"".join([unichr(ord(spl[0])*100 + ord(spl[1])-30) for spl in [instr[i: i + 2] for i in range(0, 16, 2)]])
which is a really crummy shift:
1234567890123456 becomes ጸᐂᓌᖖᙖጸᐂᓌ
aAzZ09jdmekfADEF becomes ☇⿤ዛ⦮⫛⨔ᦊᬜ
IamBADatREQUIREM becomes ᳇⪸ᦊ☺ ΊᲸᬣ
zzaa009990123456 becomes 〄☧ዒᙟᙖጸᐂᓌ
which is reversed via:
"".join([chr(ord(num) / 100) + chr(ord(num) % 100 + 30) for num in unistring])
u"〄☧ዒᙟᙖጸᐂᓌ" becomes zzaa009990123456
and thus the circle of life is complete.
If the hash function can return any immutable object, return the strings directly. No need to map them into anything.
def hash(s):
return s
If it needs to return ints, then it's simple. Python integers can be arbitrarily large, so all you have to do is convert the string an int with the same bytes.
def hash(s):
return int.from_bytes(string.encode(), byteorder='big')
hash functions return a string of fixed length relative to the hash function not the input string, what you want is a cipher
https://crypto.stackexchange.com/questions/8765/is-there-a-hash-function-which-has-no-collisions
ASCII value of a character in Python
from random import shuffle
def create_cipher():
key = []
# ASCII value of numerals
for i in range(48,58):
key.append(i)
# ASCII value of lowercase
for i in range(65,91):
key.append(i)
# ASCII value of uppercase
for i in range(97,123):
key.append(i)
print key
cipher = list(key)
shuffle(cipher)
print cipher
cipher_dict = {}
for i in range(len(key)):
cipher_dict[key[i]] = cipher[i]
return cipher_dict
def cipher(string,code_dict):
coded_list = []
list_string = list(string)
list_string = [ord(i) for i in list_string]
for i in list_string:
coded_list.append(code_dict[i])
coded_list = [chr(i) for i in coded_list]
return ''.join(coded_list)
msg = 'HelloWorld2017'
encode_dict = create_cipher()
decode_dict = {y:x for x,y in encode_dict.iteritems()}
encoded_cipher = cipher(msg,encode_dict)
decoded_cipher = cipher(encoded_cipher,decode_dict)
print msg
print encoded_cipher
print decoded_cipher
>>>
HelloWorld2017
pryyLILoyx9fgm
HelloWorld2017
of course you'd want to validate your inputs... for alphanumeric you can use:
isalnum()

Categories