How do I get arrays to couple multiple numbers? - python

I'm making a game with a saving system in Python, but it doesn't work as intended.
thingcount = saveArray[0]
The code above is supposed to set thingcount to 5454, as shown in the saveArray:
[5454, 0, 1]
But it only sets thingcount to 5. Does anyone know how to do this?

As some of the comments have noted, if saveArray truly equals [5454, 0, 1], then the command print(thingcount) will yield your desired output of [5454]
If thingcount[0] yields an output of 5, then at some point in your code, saveArray is being set to 5454 only - Maybe as a string, but not the full list of [5454, 0, 1]
Below are two code snippets for a comparison example:
Desired Output
saveArray = [5454, 0, 1]
thingcount = saveArray[0]
print (thingcount)
Console output:
5454
Code that will yield the output you're seeing
saveArray = '5454'
thingcount = saveArray[0]
print (thingcount)
Console output:
5
In any case, I would check what saveArray is being set to - At some point in your code, its being set to a different value, not your full target list of [5454,0,1]
On getting the first element from a list in Python - Below is a link to another thread that discusses getting the first element of a list, if that is helpful:
Returning the first element python

Related

Formatted string in list

What is its solution or another way?
I wrote a strings list as shown before this I wanted to format it and include options then I wanted to print (by taking input from user) its index but on the terminal error was thrown that 0 or 1 index is not present in list.
options = ["a) 31\n b) 32\n c) 33\n d)34", "a) Energy\n b) Motion\n c) Motion and Energy\n d)Nothing"]
questions = [f"Our brain is consists of ..... bones:\n{options.index(1)}",
f"Physics is the study of .......\n{options.index(2)}"]
q_1 = input(questions[0])
options.index(1) searches 1 in the list and returns its index. This is not what you seem to want.
You seem to want to get the first element of options, which is done with options[0] instead.
It is 0 instead of 1, because Python lists are indexed starting from 0, not 1.
You are doing this correctly when you index into questions.
I have corrected your code with options[1] insted of options.index(1)
options = ["a) 31\n b) 32\n c) 33\n d)34", "a) Energy\n b) Motion\n c) Motion and Energy\n d)Nothing"]
questions = [f"Our brain is consists of ..... bones:\n{options[0]}", f"Physics is the study of .......\n{options[1]}"]
q_1 = input(questions[0])
The index method searches if the value you provided is in the list ie it options.index(0) checks if an element with value 0 is present and returns its index
To get the element at index 0 use list[0]

I'm trying to make a simple script that says two different two phrase lines(Python)

So, I'm just starting to program Python and I wanted to make a very simple script that will say something like "Gabe- Hello, my name is Gabe (Just an example of a sentence" + "Jerry- Hello Gabe, I'm Jerry" OR "Gabe- Goodbye, Jerry" + "Jerry- Goodbye, Gabe". Here's pretty much what I wrote.
answers1 = [
"James-Hello, my name is James!"
]
answers2 = [
"Jerry-Hello James, my name is Jerry!"
]
answers3 = [
"Gabe-Goodbye, Samuel."
]
answers4 = [
"Samuel-Goodbye, Gabe"
]
Jack1 = (answers1 + answers2)
Jack2 = (answers3 + answers4)
Jacks = ([Jack1,Jack2])
import random
for x in range(2):
a = random.randint(0,2)
print (random.sample([Jacks, a]))
I'm quite sure it's a very simple fix, but as I have just started Python (Like, literally 2-3 days ago) I don't quite know what the problem would be. Here's my error message
Traceback (most recent call last):
File "C:/Users/Owner/Documents/Test Python 3.py", line 19, in <module>
print (random.sample([Jacks, a]))
TypeError: sample() missing 1 required positional argument: 'k'
If anyone could help me with this, I would very much appreciate it! Other than that, I shall be searching on ways that may be relevant to fixing this.
The problem is that sample requires a parameter k that indicates how many random samples you want to take. However in this case it looks like you do not need sample, since you already have the random integer. Note that that integer should be in the range [0,1], because the list Jack has only two elements.
a = random.randint(0,1)
print (Jacks[a])
or the same behavior with sample, see here for an explanation.
print (random.sample(Jacks,1))
Hope this helps!
random.sample([Jacks, a])
This sample method should looks like
random.sample(Jacks, a)
However, I am concerted you also have no idea how lists are working. Can you explain why do you using lists of strings and then adding values in them? I am losing you here.
If you going to pick a pair or strings, use method described by Florian (requesting data by index value.)
k parameter tell random.sample function that how many sample you need, you should write:
print (random.sample([Jacks, a], 3))
which means you need 3 sample from your list. the output will be something like:
[1, jacks, 0]

Slow code in "inner joins" lists in python

I have seen several posts about lists in python here, but I don't find a correct answer to my question; because it is about optimize a code.
I have a python code to compare two lists. It has to find the same code, and modifying the value of the second positions. It finally works perfectly, but it takes a lot of time. In SQL this query take 2 minuts, no more...., however, here, I spend 15 minutes.... so I don't understand if it is problem of memory or bad code written.
I have two lists.
The first one [code, points]. The second [code, license]
If the first value(code) in the first list, match with the first value of the second list(code); it has to update the second value of the first list (points) if the license is equal to 'THIS', for example:
itemswithscore = [5675, 0], [6676, 0], [9898, 0], [4545, 0]
itemswithlicense = [9999, 'ATR'], [9191, 'OPOP'], [9898, 'THIS'], [2222, 'PLPL']
for sublist1 in itemswithscore:
for sublist2 in itemswithlicense:
if sublist1[0] == sublist2[0]: #this is the "inner join" :)
if sublist2[1] == 'THIS': #It has to be license 'THIS'
sublist1[1] += 50 #I add 50 to the score value
Finally, I have this list updated in the code 9868:
itemswithscore = [5675, 0], [6676, 0], [9898, 50], [4545, 0]
It is true that the two lists have 80.000 values everyone.. :(
Thanks in advance!!!
I'll suggest to transform/keep your data structure into/as dicts. In that way, you won't need to iterate over both lists with nested for loops - an O(n2) or O(n x m) operation - searching for where the lists' code numbers align before updating the score value.
You'll simply update the value of the score where the key at the corresponding dict matches the search string:
dct_score = dict(itemswithscore)
dct_license = dict(itemswithlicense)
for k in dct_score:
if dct_license.get(k) == 'THIS': # use dict.get in case key does not exist
dct_score[k] += 50
It would be very efficient if you can use pandas.
So You can make two dataframes and merge them on a single column
Something like this
itemswithscore = [5675, 0], [6676, 0], [9898, 0], [4545, 0]
itemswithlicense = [9999, 'ATR'], [9191, 'OPOP'], [9898, 'THIS'], [2222, 'PLPL']
df1 = pd.DataFrame(list(itemswithscore), columns =['code', 'points'])
df2 = pd.DataFrame(list(itemswithlicence), columns=['code', 'license'])
df3 = pd.merge(df1, df2 , on='code', how='inner')
df3 = df3.drop('points', axis=1)
Hope this helps, accept if correct
Cheers!
I'm pretty sure the slowness is mostly due to the looping itself, which is not very fast in Python. You can speed up the code somewhat by caching variables, like so:
for sublist1 in itemswithscore:
a = sublist1[0] # Save to variable to avoid repeated list-lookup
for sublist2 in itemswithlicense:
if a == sublist2[0]:
if sublist2[1] == 'THIS':
sublist1[1] += 50
Also, if you happen to know that 'THIS' does not occur in itemswithlicense more than once, you should insert a break after you update sublist1[1].
Let me know how much of a different this make.

KeyError with Python dictionary

I've been practicing on a ><> (Fish) interpreter and am stuck on an error I'm getting. The problematic code seems to be here:
import sys
from random import randint
file = sys.argv[1]
code = open(file)
program = code.read()
print(str(program))
stdin = sys.argv[2]
prgmlist = program.splitlines()
length = len(prgmlist)
prgm = {}
for x in range(0,length-1):
prgm[x+1] = list(prgmlist[x])
The goal here was to take the code and put it into a sort of grid, so that each command could be taken and computed separately. By grid, I mean a map to a list:
{line1:["code","code","code"]
line2:["code","code","code"]
line3:...}
and so on.
However, when I try to retrieve a command using cmd = prgm[y][x] it gives me KeyError: 0.
Any help is appreciated.
Here's a traceback:
Traceback (most recent call last):
File "/Users/abest/Documents/Python/><>_Interpreter.py", line 270, in <module>
cmd = prgm[cmdy][cmdx]
KeyError: 0
And a pastebin of the entire code.
The input is the hello world program from the wiki page:
!v"hello, world"r!
>l?!;o
Few issues -
You are not considering the last line , since your range is - for x in range(0,length-1): - and the stop argument of range is exlusive, so it does not go to length-1 . You actually do not need to get the length of use range, you can simply use for i, x in enumerate(prgmlist): . enumerate() in each iteration returns the index as well as the current element.
for i, x in enumerate(prgmlist, 1):
prgm[i] = list(x)
Secondly, from your actual code seems like you are defining cmdx initially as 0 , but in your for loop (as given above) , you are only starting the index in the dictionary from 1 . So you should define that starting at 1. Example -
stacks, str1, str2, cmdx, cmdy, face, register, cmd = {"now":[]}, 0, 0, 1, 0, "E", 0, None
And you should start cmdy from 0 . Seems like you had both of them reversed.
You'll want to use something like
cmd = prgm[x][y]
the first part prgm[x] will access the list that's the value for the x key in the dictionary then [y] will pull the yth element from the list.

reporting the best alignment with pairwise2

I have a fastq file of reads, say "reads.fastq". I want to align the sequnces to a string saved as a fasta file ref.faa. I am using the following code for this
reads_array = []
for x in Bio.SeqIO.parse("reads.fastq","fastq"):
reads_array.append(x)
for x in Bio.SeqIO.parse("ref.faa","fasta"):
refseq = x
result = open("alignments_G10_final","w")
aligned_reads = []
for x in reads_array:
alignments =pairwise2.align.globalms(str(refseq.seq).upper(),str(x.seq),2,-1,-5,-0.05)
for a in alignments:
result.write(format_alignment(*a))
aligned_reads.append(x)
But I want to report only the best alignment for each read. How can I choose this alignment from the scores in a[2]. I want to choose the alignment(s) with the highest value of a[2]
You could sort the alignments according to a[2]:
for x in reads_array:
alignments = pairwise2.align.globalms(
str(refseq.seq).upper(), str(x.seq), 2, -1, -5, -0.05)
sorted_alignments = sorted(alignments, key=operator.itemgetter(2))
result.write(format_alignment(*sorted_alignments[0]))
aligned_reads.append(x)
I know this is an old question, but for anyone still looking for the correct answer, add one_alignment_only=True argument to your align method:
alignments =pairwise2.align.globalms(str(refseq.seq).upper(),
str(x.seq),
2,-1,-5,-0.05,
one_alignment_only=True)
I had to do some digging around in the documentation to find it, but this gives back the optimal score.

Categories

Resources