I have an example pandas dataframe, df, below:
{'column_a': {0: 'b', 1: 'b', 2: 'a', 3: 'b', 4: 'd', 5: 'a', 6: 'b', 7: 'b', 8: 'c', 9: 'a', 10: 'a', 11: 'a', 12: 'a', 13: 'c', 14: 'c', 15: 'c', 16: 'b', 17: 'a', 18: 'a', 19: 'b', 20: 'd', 21: 'c', 22: 'a', 23: 'b', 24: 'c', 25: 'c', 26: 'c', 27: 'e', 28: 'e', 29: 'e', 30: 'e', 31: 'c', 32: 'e', 33: 'e', 34: 'd', 35: 'e', 36: 'd', 37: 'e', 38: 'd', 39: 'b', 40: 'd', 41: 'c', 42: 'b', 43: 'd', 44: 'c', 45: 'e', 46: 'd', 47: 'c', 48: 'e', 49: 'b', 50: 'c'}, 'column_b': {0: 'c', 1: 'b', 2: 'b', 3: 'd', 4: 'b', 5: 'a', 6: 'd', 7: 'c', 8: 'c', 9: 'd', 10: 'a', 11: 'a', 12: 'b', 13: 'a', 14: 'c', 15: 'd', 16: 'd', 17: 'c', 18: 'b', 19: 'd', 20: 'a', 21: 'a', 22: 'd', 23: 'b', 24: 'a', 25: 'c', 26: 'e', 27: 'd', 28: 'b', 29: 'c', 30: 'd', 31: 'b', 32: 'e', 33: 'b', 34: 'b', 35: 'c', 36: 'b', 37: 'b', 38: 'd', 39: 'c', 40: 'b', 41: 'a', 42: 'b', 43: 'e', 44: 'e', 45: 'c', 46: 'e', 47: 'c', 48: 'b', 49: 'b', 50: 'c'}, 'column_c': {0: 'b', 1: 'd', 2: 'b', 3: 'b', 4: 'd', 5: 'c', 6: 'b', 7: 'a', 8: 'a', 9: 'a', 10: 'a', 11: 'b', 12: 'd', 13: 'c', 14: 'b', 15: 'a', 16: 'a', 17: 'a', 18: 'b', 19: 'c', 20: 'a', 21: 'a', 22: 'b', 23: 'd', 24: 'd', 25: 'c', 26: 'd', 27: 'c', 28: 'c', 29: 'e', 30: 'd', 31: 'c', 32: 'd', 33: 'c', 34: 'b', 35: 'b', 36: 'd', 37: 'd', 38: 'd', 39: 'b', 40: 'c', 41: 'e', 42: 'e', 43: 'b', 44: 'b', 45: 'd', 46: 'd', 47: 'c', 48: 'e', 49: 'd', 50: 'b'}, 'column_d': {0: 'b', 1: 'c', 2: 'd', 3: 'd', 4: 'b', 5: 'b', 6: 'd', 7: 'd', 8: 'd', 9: 'b', 10: 'd', 11: 'c', 12: 'b', 13: 'a', 14: 'c', 15: 'c', 16: 'd', 17: 'c', 18: 'd', 19: 'a', 20: 'd', 21: 'b', 22: 'd', 23: 'b', 24: 'd', 25: 'e', 26: 'c', 27: 'c', 28: 'c', 29: 'd', 30: 'c', 31: 'e', 32: 'd', 33: 'd', 34: 'd', 35: 'b', 36: 'c', 37: 'e', 38: 'b', 39: 'e', 40: 'b', 41: 'c', 42: 'b', 43: 'e', 44: 'b', 45: 'c', 46: 'd', 47: 'c', 48: 'c', 49: 'b', 50: 'd'}, 'target': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1, 19: 1, 20: 1, 21: 1, 22: 1, 23: 1, 24: 1, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0, 34: 0, 35: 0, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 0, 49: 0, 50: 0}}
What I am trying to accomplish is to select a subsample of this dataframe of an arbitrary length or percentage, but in doing so, I want to maintain (as closely as possible) the frequency distributions of each value for each class.
For example, if I want to simply subsample the dataframe, I can use .sample() method
smaller_df = df.sample(n=100) or smaller_df = df.sample(frac=0.1)
However, it could be the case that the distributions of each value in each column in each class are lost. I need to preserve these value densities while downsampling my dataset size.
I can see these frequency densities with:
for col in df.columns:
print(df.groupby(['target'])[col].value_counts(normalize=True))
That output looks like:
target column_a
0 e 0.384615
c 0.269231
d 0.230769
b 0.115385
1 a 0.360000
b 0.320000
c 0.240000
d 0.080000
I have seen this post on Stack Overflow which seemingly answers that for a single distribution, but not multiple.
Ideally, how can I downsample my dataframe to maintain each columns frequency distribution with less samples? My actual dataset is (8370994, 731)
Related
I'm a Korean. English translation may be wrong.
I am making a program that can output data in Python using a qr reader that is received as a usb input from a Raspberry Pi 4.
The code below raises KeyError:74 . What's the workaround?
ss += hid[int(ord(c))]
Below is the full code.
import sys
hid = {4: 'a', 5: 'b', 6: 'c', 7: 'd', 8: 'e', 9: 'f', 10: 'g', 11: 'h', 12: 'i', 13: 'j', 14: 'k', 15: 'l', 16: 'm',
17: 'n', 18: 'o', 19: 'p', 20: 'q', 21: 'r', 22: 's', 23: 't', 24: 'u', 25: 'v', 26: 'w', 27: 'x', 28: 'y',
29: 'z', 30: '1', 31: '2', 32: '3', 33: '4', 34: '5', 35: '6', 36: '7', 37: '8', 38: '9', 39: '0', 44: ' ',
45: '-', 46: '=', 47: '[', 48: ']', 49: '\\', 51: ';', 52: '\'', 53: '~', 54: ',', 55: '.', 56: '/'}
hid2 = {4: 'A', 5: 'B', 6: 'C', 7: 'D', 8: 'E', 9: 'F', 10: 'G', 11: 'H', 12: 'I', 13: 'J', 14: 'K', 15: 'L', 16: 'M',
17: 'N', 18: 'O', 19: 'P', 20: 'Q', 21: 'R', 22: 'S', 23: 'T', 24: 'U', 25: 'V', 26: 'W', 27: 'X', 28: 'Y',
29: 'Z', 30: '!', 31: '#', 32: '#', 33: '$', 34: '%', 35: '^', 36: '&', 37: '*', 38: '(', 39: ')', 44: ' ',
45: '_', 46: '+', 47: '{', 48: '}', 49: '|', 51: ':', 52: '"', 53: '~', 54: '<', 55: '>', 56: '?'}
fp = open('/dev/hidraw4', 'rb')
ss = ""
shift = False
done = False
while not done:
## Get the character from the HID
buffer = fp.read(8)
for c in buffer:
if ord(c) > 0:
## 40 is carriage return which signifies
## we are done looking for characters
if int(ord(c)) == 40:
done = True
break;
## If we are shifted then we have to
## use the hid2 characters.
if shift:
## If it is a '2' then it is the shift key
if int(ord(c)) == 2 :
shift = True
## if not a 2 then lookup the mapping
else:
ss += hid2[int(ord(c))]
shift = False
## If we are not shifted then use
## the hid characters
else:
## If it is a '2' then it is the shift key
if int(ord(c)) == 2 :
shift = True
## if not a 2 then lookup the mapping
else:
ss += hid[int(ord(c))]
print(ss)
A KeyError is raised when you try to access a key/value in a dict that does not contain that key. You probably want to re-check and update your mapping to contain the correct (ASCII) values as keys. The 74 comes from int(ord("J")).
You can avoid Key errors by changing hid[int(ord(c))] to hid.get(int(ord(c)) which would return None when the key does not exist.
I have dataframe column with strings, similar to:
'TCCTGTAAATCAAAGGCCAAGRG', 'GNGCNCCNGAYATRGCNTTYCC', 'GATTTCTCTYCCTGTTCTTGCA'
and I have a list of letter:
SNPs={}
SNPs["Y"] = ['C', 'T']
SNPs["R"] = ['A', 'G']
SNPs["N"] = ['C', 'G', 'A', 'T']
where every R needs to change to A/G and so on...
ex: TCCTGTAAATCAAAGGCCAAGRG
changes to TCCTGTAAATCAAAGGCCAAGAG and TCCTGTAAATCAAAGGCCAAGGG.
I want all permutation and combinations and the result in other column.
Please help me with the same.
import re, itertools
text = "GNGCNCCNGAYATRGCNTTYCC"
def getList(dict):
return list(dict.keys())
lsources = getList(SNPs)
ldests = []
for source in lsources:
ldests.append(SNPs[source])
#print(ldests)
# Generate the various pairings
for lproduct in itertools.product(*ldests):
#print(lproduct)
for i in text:
output = i
for src, dest in zip(lsources, lproduct):
# Replace each term (you could optimise this using a single re.sub)
output = output.replace("%s" % src, dest)
print(output)
this is my code..but I am not getting desired output
Try this:
>>> import itertools
>>> text = "GNGCNCCNGAYATRGCNTTYCC"
>>> SNPs={ "Y" : ['C', 'T'] , "R" : ['A', 'G'] , "N" : ['C', 'G', 'A', 'T']}
>>> text_tmp = ""
>>> dct = {}
>>> for idx, v in enumerate(text):
... if v in SNPs:
... dct[idx] = SNPs.get(v)
... text_tmp += f'_{idx}_'
... else:
... text_tmp += v
>>> text_tmp
'G_1_GC_4_CC_7_GA_10_AT_13_GC_16_TT_19_CC'
>>> dct
{1: ['C', 'G', 'A', 'T'],
4: ['C', 'G', 'A', 'T'],
7: ['C', 'G', 'A', 'T'],
10: ['C', 'T'],
13: ['A', 'G'],
16: ['C', 'G', 'A', 'T'],
19: ['C', 'T']}
>>> per_val = list(itertools.product(*dct.values()))
>>> per_key_val = list(map(dict,[zip(dct.keys(), p) for p in per_val]))
>>> per_key_val
[{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'A', 16: 'C', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'A', 16: 'C', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'A', 16: 'G', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'A', 16: 'G', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'A', 16: 'A', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'A', 16: 'A', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'A', 16: 'T', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'A', 16: 'T', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'G', 16: 'C', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'G', 16: 'C', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'G', 16: 'G', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'G', 16: 'G', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'G', 16: 'A', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'G', 16: 'A', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'G', 16: 'T', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'G', 16: 'T', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'T', 13: 'A', 16: 'C', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'T', 13: 'A', 16: 'C', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'T', 13: 'A', 16: 'G', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'T', 13: 'A', 16: 'G', 19: 'T'},
...
]
>>> out = []
>>> for pkl in per_key_val:
... tmp = text_tmp
... for k,v in pkl.items():
... tmp = tmp.replace(f'_{k}_', v)
... out.append(tmp)
>>> out
['GCGCCCCCGACATAGCCTTCCC',
'GCGCCCCCGACATAGCCTTTCC',
'GCGCCCCCGACATAGCGTTCCC',
'GCGCCCCCGACATAGCGTTTCC',
'GCGCCCCCGACATAGCATTCCC',
'GCGCCCCCGACATAGCATTTCC',
'GCGCCCCCGACATAGCTTTCCC',
'GCGCCCCCGACATAGCTTTTCC',
'GCGCCCCCGACATGGCCTTCCC',
'GCGCCCCCGACATGGCCTTTCC',
'GCGCCCCCGACATGGCGTTCCC',
'GCGCCCCCGACATGGCGTTTCC',
'GCGCCCCCGACATGGCATTCCC',
'GCGCCCCCGACATGGCATTTCC',
'GCGCCCCCGACATGGCTTTCCC',
'GCGCCCCCGACATGGCTTTTCC',
'GCGCCCCCGATATAGCCTTCCC',
'GCGCCCCCGATATAGCCTTTCC',
'GCGCCCCCGATATAGCGTTCCC',
'GCGCCCCCGATATAGCGTTTCC',
'GCGCCCCCGATATAGCATTCCC',
'GCGCCCCCGATATAGCATTTCC',
'GCGCCCCCGATATAGCTTTCCC',
...
]
Update: (run on dataframe)
def rplc_per(text):
SNPs={ "Y" : ['C', 'T'] , "R" : ['A', 'G'] , "N" : ['C', 'G', 'A', 'T']}
text_tmp = ""
dct = {}
for idx, v in enumerate(text):
if v in SNPs:
dct[idx] = SNPs.get(v)
text_tmp += f'_{idx}_'
else:
text_tmp += v
per_val = list(itertools.product(*dct.values()))
per_key_val = list(map(dict,[zip(dct.keys(), p) for p in per_val]))
out = []
for pkl in per_key_val:
tmp = text_tmp
for k,v in pkl.items():
tmp = tmp.replace(f'_{k}_', v)
out.append(tmp)
return out
df = pd.DataFrame({'String': ['TCCTGTAAATCAAAGGCCAAGRG', 'GNGCNCCNGAYATRGCNTTYCC', 'GATTTCTCTYCCTGTTCTTGCA']})
df['all_per'] = df['String'].apply(rplc_per)
print(df)
Output:
String all_per
0 TCCTGTAAATCAAAGGCCAAGRG [TCCTGTAAATCAAAGGCCAAGAG, TCCTGTAAATCAAAGGCCAA...
1 GNGCNCCNGAYATRGCNTTYCC [GCGCCCCCGACATAGCCTTCCC, GCGCCCCCGACATAGCCTTTC...
2 GATTTCTCTYCCTGTTCTTGCA [GATTTCTCTCCCTGTTCTTGCA, GATTTCTCTTCCTGTTCTTGCA]
I have set up a raspberry Pi with a USB barcode scanner for a little project. It works with my generated barcodes, it prints the output of the scanned code in the terminal. I really want to save this input to a txt file that doesn't overwrite itself. I have tried changing all the functions and i just cant get it to work. I'm just a novice in Python and i have been stuck on this for a long time now and i have looked all over the internet. If you can just point me to the specific place in code i need to change in order to print the output out i would be very appreciative.
Source: Instructables
!/usr/bin/python
import sys
import requests
import json
api_key = "" #https://upcdatabase.org/
def barcode_reader():
hid = {4: 'a', 5: 'b', 6: 'c', 7: 'd', 8: 'e', 9: 'f', 10: 'g', 11: 'h', 12: 'i', 13: 'j', 14: 'k', 15: 'l', 16: 'm',
17: 'n', 18: 'o', 19: 'p', 20: 'q', 21: 'r', 22: 's', 23: 't', 24: 'u', 25: 'v', 26: 'w', 27: 'x', 28: 'y',
29: 'z', 30: '1', 31: '2', 32: '3', 33: '4', 34: '5', 35: '6', 36: '7', 37: '8', 38: '9', 39: '0', 44: ' ',
45: '-', 46: '=', 47: '[', 48: ']', 49: '\\', 51: ';', 52: '\'', 53: '~', 54: ',', 55: '.', 56: '/'}
hid2 = {4: 'A', 5: 'B', 6: 'C', 7: 'D', 8: 'E', 9: 'F', 10: 'G', 11: 'H', 12: 'I', 13: 'J', 14: 'K', 15: 'L', 16: 'M',
17: 'N', 18: 'O', 19: 'P', 20: 'Q', 21: 'R', 22: 'S', 23: 'T', 24: 'U', 25: 'V', 26: 'W', 27: 'X', 28: 'Y',
29: 'Z', 30: '!', 31: '#', 32: '#', 33: '$', 34: '%', 35: '^', 36: '&', 37: '*', 38: '(', 39: ')', 44: ' ',
45: '_', 46: '+', 47: '{', 48: '}', 49: '|', 51: ':', 52: '"', 53: '~', 54: '<', 55: '>', 56: '?'}
fp = open('/dev/hidraw0', 'rb')
ss = ""
shift = False
done = False
while not done:
## Get the character from the HID
buffer = fp.read(8)
for c in buffer:
if ord(c) > 0:
## 40 is carriage return which signifies
## we are done looking for characters
if int(ord(c)) == 40:
done = True
break;
## If we are shifted then we have to
## use the hid2 characters.
if shift:
## If it is a '2' then it is the shift key
if int(ord(c)) == 2:
shift = True
## if not a 2 then lookup the mapping
else:
ss += hid2[int(ord(c))]
shift = False
## If we are not shifted then use
## the hid characters
else:
## If it is a '2' then it is the shift key
if int(ord(c)) == 2:
shift = True
## if not a 2 then lookup the mapping
else:
ss += hid[int(ord(c))]
return ss
def UPC_lookup(api_key,upc):
'''V3 API'''
url = "https://api.upcdatabase.org/product/%s/%s" % (upc, api_key)
headers = {
'cache-control': "no-cache",
}
response = requests.request("GET", url, headers=headers)
print("-----" * 5)
print(upc)
print(json.dumps(response.json(), indent=2))
print("-----" * 5 + "\n")
if __name__ == '__main__':
try:
while True:
UPC_lookup(api_key,barcode_reader())
except KeyboardInterrupt:
pass
If it is already printing to the console it means it's coming from this part of the code:
print("-----" * 5)
print(upc)
print(json.dumps(response.json(), indent=2))
print("-----" * 5 + "\n")
In order to save it to a file you can use the following:
with open('FILENAME.txt', 'a', encoding='utf-8') as file:
file.write('CONTENT THAT YOU WANT TO WRITE!\n')
Or in your particular case:
with open('FILENAME.txt', 'a', encoding='utf-8') as file:
file.write("-----" * 5)
file.write(upc)
file.write(json.dumps(response.json(), indent=2))
file.write("-----" * 5 + "\n")
I have the classic ucb admission dataset as a pandas DataFrame with multiIndex:
value
Dept Gender Admit
A Male Admitted 512
Rejected 313
Female Admitted 89
Rejected 19
etc. for other departments ('A' through 'F')
and I want to create a table of the ratio of students accepted to rejected, grouped by Dept and Gender
My current approaches have been
ucbA.groupby(level=['Dept', 'Gender']).apply(lambda x: x.xs('Admitted', level=2).iloc[0] / x.xs('Rejected', level=2).iloc[0]).unstack().value
which is horrible
and
admitted = ucbA.unstack('Admit')
DataFrame({'Proportion Accepted': admitted.value.Admitted / admitted.value.Rejected}).unstack(1)
which ok I guess, but I feel it should be possible as a one-liner without unstacking.
Is there a really neat way of doing something like this? I'm imagining a one-liner staying within the context of the multi-index.
Edit: The full frame:
DataFrame({'Admit': {0: 'Admitted', 1: 'Rejected', 2: 'Admitted', 3: 'Rejected', 4: 'Admitted', 5: 'Rejected', 6: 'Admitted', 7: 'Rejected', 8: 'Admitted', 9: 'Rejected', 10: 'Admitted', 11: 'Rejected', 12: 'Admitted', 13: 'Rejected', 14: 'Admitted', 15: 'Rejected', 16: 'Admitted', 17: 'Rejected', 18: 'Admitted', 19: 'Rejected', 20: 'Admitted', 21: 'Rejected', 22: 'Admitted', 23: 'Rejected'}, 'Dept': {0: 'A', 1: 'A', 2: 'A', 3: 'A', 4: 'B', 5: 'B', 6: 'B', 7: 'B', 8: 'C', 9: 'C', 10: 'C', 11: 'C', 12: 'D', 13: 'D', 14: 'D', 15: 'D', 16: 'E', 17: 'E', 18: 'E', 19: 'E', 20: 'F', 21: 'F', 22: 'F', 23: 'F'}, 'Gender': {0: 'Male', 1: 'Male', 2: 'Female', 3: 'Female', 4: 'Male', 5: 'Male', 6: 'Female', 7: 'Female', 8: 'Male', 9: 'Male', 10: 'Female', 11: 'Female', 12: 'Male', 13: 'Male', 14: 'Female', 15: 'Female', 16: 'Male', 17: 'Male', 18: 'Female', 19: 'Female', 20: 'Male', 21: 'Male', 22: 'Female', 23: 'Female'}, 'value': {0: 512, 1: 313, 2: 89, 3: 19, 4: 353, 5: 207, 6: 17, 7: 8, 8: 120, 9: 205, 10: 202, 11: 391, 12: 138, 13: 279, 14: 131, 15: 244, 16: 53, 17: 138, 18: 94, 19: 299, 20: 22, 21: 351, 22: 24, 23: 317}}).set_index(['Dept', 'Gender', 'Admit']).astype(float).astype(int)
Alternatively if you have rpy:
import pandas.rpy.common as com
ucbA = com.load_data('UCBAdmissions').set_index(['Dept', 'Gender', 'Admit']).astype(float).astype(int)
Here you go:
df = pd.DataFrame({'Dept':['A','A','A','A'],
'Gender':['Male', 'Male', 'Female', 'Female'],
'Admit':['Admitted', 'Rejected', 'Admitted', 'Rejected'],
'value':[512,313,89,19]})
df = df.set_index(['Dept', 'Gender', 'Admit'])
# Proportions accepted and rejected:
df / df.groupby(level=['Dept','Gender']).transform(sum)
# value
#Dept Gender Admit
#A Female Admitted 0.824074
# Rejected 0.175926
# Male Admitted 0.620606
# Rejected 0.379394
# If you really want admitted as fraction of rejected:
df2 = df.swaplevel(1,2).swaplevel(0,1)
df2.ix['Admitted'] / df2.ix['Rejected']
# value
#Dept Gender
#A Male 1.635783
# Female 4.684211
Here's a way
In [55]: grouper = ['Dept','Gender']
In [56]: x = df.reset_index()
In [57]: (x[x.Admit=='Admitted'].groupby(grouper).sum() /
x[x.Admit=='Rejected'].groupby(grouper).sum()
).unstack()
Out[57]:
value
Gender Female Male
Dept
A 4.684211 1.635783
B 2.125000 1.705314
C 0.516624 0.585366
D 0.536885 0.494624
E 0.314381 0.384058
F 0.075710 0.062678
[6 rows x 2 columns]
I am working on ways to get me thinking in python. I have a simple idea that will take a number and give the corresponding "value" from a dictionary.
So basically I would like to have a number or numbers given, and then turn those numbers into a word.
The overall all view is to have a dictionary with keys ranging for 1 to 26 with values going from a to z. So 1 would equal "a" and 26 would equal "z".
I have a variable d = 1, and need to get the output of 'a'. Then increase size of this function for a list like (1,2,3,4) which output would be a, b, c, d.
Here is what I have so far.
d = 1
def code_scram(x):
c = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'}
scram = ""
for i in d:
if i in c:
scram += c[i]
return scram
print code_scram(d)
However, its not working out as planned.
Your for loop should iterate through x, not d.
def code_scram(x):
c = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'}
scram = ""
for i in x:
if i in c:
scram += c[i]
return scram
print code_scram([1,2,3,4])
Result:
abcd
The function only works for lists, so passing in the integer d won't work. Pass in a list instead.
d = [1]
print code_scram(d)
If you want the function to work for lists and lone integers, you can perform a type check, and convert as necessary.
def code_scram(x):
if isinstance(x, int):
x = [x]
c = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'}
scram = ""
for i in x:
if i in c:
scram += c[i]
return scram
d = 1
print code_scram(d)
Result:
a