I have this list which contain only Ws and Ss:
ls = ['W', 'S', 'S', 'S', 'W', 'W', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'W', 'W', 'W', 'W', 'W', 'W', 'S']
What I want to do is to extract the longest nonbreaking "S" in that list?
and return the index of that Ss, returning:
['S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S']
and
[6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
How can I achieve that?
Use itertools.groupby with enumerate and max:
>>> from operator import itemgetter
>>> from itertools import groupby
>>> val = max((list(g) for k, g in
groupby(enumerate(ls), itemgetter(1)) if k == 'S'), key=len)
>>> indices, items = zip(*val)
>>> indices
(6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
>>> items
('S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S')
Same solution as Ashwini Chaudhary's minus the elegance,
from itertools import groupby
index, result, m_index = 0, [], 0
# Group based on the elements of the list
for item, grp in groupby(ls):
# Get the grouped items as a list
grp = list(grp)
# Filter out `M`s and check if this is the biggest run of `S`s ever seen
if item == "S" and len(grp) > len(result):
result, m_index = grp, index
# Increment the index to keep track of the list covered
index += len(grp)
print(result, list(range(m_index, m_index + len(result))))
>>> import re
>>> max((x.group(), x.span()) for x in re.finditer("S+", "".join(ls)))
('SSSSSSSSSSS', (6, 17))
>>> range(6, 17)
[6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
package com.algo.sort;
public class LargestCont{
static int g[]={1,1,1,1,2,2,3,4,5,5,5,5,5,5,5,5,5,5,5,2,2,2,2,3,3,3,3,3,3,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,3,3,3,3,3,3,3,3,3,0,0,0,0,0,0,0,0,0};
public static void main(String f[]){
manage(g);
}
public static void manage(int[] j){
int max=1; int val=-1; int count=0; int ans=0;
for(int i=0;i<j.length;i++){
if(j[i]!=val){
if(max>count){
ans=val;
count=max;
System.out.println(ans+"...."+count);
}
val=j[i]; max=1;}else{
max++;
}
}
System.out.println(ans);
}
}
ls = ['W', 'S', 'S', 'S', 'W', 'W', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'W', 'W', 'W', 'W', 'W', 'W', 'S']
for x,y in enumerate(ls):
print (x,str(y).split("W"))
I found this one.
Related
I stole Charles Duffy's code on line 9.
here is my code now:
from itertools import combinations
def rSubset(arr, r):
return set(list(combinations(arr, r)))
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
r = 10
for item in combinations(arr, r): print(item)
When I run this in my terminal (python passwordgenerator.py) I get a few seconds of a list and then my terminal freezes :(
Any thoughts?
Also would there be any way to chop this up into little pieces where I could generate a few lines, then write to a txt file, then generate a few more lines, then write to a file?
Edit:
Maybe I could use a loop and a break and a continue? I'm a bit of a python noob right now btw.
How to write a code to identify indexes where a shift happens and fetch corresponding value from another array in python?
array1 = (0,0,0,1,1,1,1,1,2,2,2,2,3,3,3,2,2,2,3,3,3,3,3,1,1,1)
array2 = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z')
The final output should be two arrays, one should contain elements fetched from array2 and the other should contain index numbers of the shifts.
Desired Output:
Indexes: [3, 8, 12, 15, 18, 23]
Final: ['d', 'i', 'm', 'p', 's', 'x']
Here is a solution
array1= [0,0,0,1,1,1,1,1,2,2,2,2,3,3,3,2,2,2,3,3,3,3,3,1,1,1]
array2= ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
cur=array1[0]
indxes=[]
final=[]
for i in range(1,len(array1)):
if array1[i]!=cur:
cur=array1[i]
indxes.append(i)
final.append(array2[i])
print(indxes)
print(final)
Here is a possible solution:
indexes = [i for i in range(1, len(array1)) if array1[i-1] != array1[i]]
final = [array2[i] for i in indexes]
"""
ID: kunalgu1
LANG: PYTHON3
TASK: ride
"""
fin = open ('ride.in', 'r')
fout = open ('ride.out', 'w')
lines = fin.readlines()
cometString = lines[0]
cometValue = 1
groupString = lines[1]
groupValue = 1
def orderS (val):
arrL = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
arrN = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
indexVal = arrL.index(val.lower())
return arrN[indexVal]
for x in cometString:
print(orderS(x))
cometValue *= orderS(x)
print(cometValue)
Here is the main error: it won't print
cometValue = cometValue % 47
print(cometValue)
fout.close()
The loop gets an error because the lines returned by readlines() include the newline terminator. When it calls orderS() for that character, arrL.index() fails because there's no newline in arrL.
You can remove the newline with the rstrip() method:
cometString = lines[0].rstrip()
You could also have orderS() return a default value when the character can't be found:
def orderS (val):
arrL = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
arrN = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
try:
indexVal = arrL.index(val.lower())
return arrN[indexVal]
except ValueError:
return 27
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']#alphabet
bag_o_letters = []#letters to chose from
letter_count = [9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1]#random indexes to chose from
for x in range(26):#loops through the random index of letter_count
for i in range(letter_count[x]):#chooses the index
bag_o_letters.append(letters[x])#appends the index of the letter to bag_o_letters
rack = []#list for the person to see
for a in range(7):#makes the list 7 letters long
rack.append(bag_o_letters.pop(random.randint(0,len(letters)-1)))#appends the letter to rack(supposedly...)
print(rack)
In this code that you just read it should choose random letters and put 7 of those letters in a rack that the person can see. It shows a error that I've looked over many times, but I just can't see what is wrong.
I put comments on the side to understand the code.
It shows this error:
rack.append(bag_of_letters.pop(random.randint(0,len(letters)-1)))
IndexError: pop index out of range
Can someone please help?
After this code, I am going to make a input statement for the user to make a word from those letters.
The first time through the loop, you append one value to bag_of_letters, and then you try to pop an index of random.randint(0,len(letters)-1). It doesn't have that many elements to pop from yet. Instead of this approach, you can make a list of the required length and sample from it:
letters = ['a', ...]#alphabet
letter_count = [9, ...]#random indexes to chose from
bag_of_letters = [l*c for l,c in zip(letters, letter_count)]
...
rack = random.sample(bag_o_letters, 7)
You're selecting the index to pop for bag_of_letters from the length of letters which is obviously larger.
You should instead do:
rack.append(bag_of_letters.pop(random.randint(0, len(bag_of_letters)-1)))
# ^^^^^^^^^^^^^^
However, there are likely to be more problems with your code. I'll suggest you use random.sample in one line of code or random.shuffle on a copy of the list, and then slice up till index 7. Both will give you 7 randomly selected letters:
import random
print(random.sample(letters, 7))
# ['m', 'u', 'l', 'z', 'r', 'd', 'x']
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
letters_copy = letters[:]
random.shuffle(letters_copy)
print(letters_copy[:7])
# ['c', 'e', 'x', 'b', 'w', 'f', 'v']
The IndexError is expected:
pop(...)
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
You need to subtract 1 from the bounds of the call to random() after each pop(). Right now you are doing this:
l = [1,2,3]
random_idx = 2
l.pop(random_idx)
>>> l == [1,3]
random_idx = 3
l.pop(random_idx)
>>>> IndexError: pop index out of range
So instead, pop() based on len(bag_o_letter) rather than len(letter).
Why not do something like this:
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
letter_count = [9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1]#random indexes to chose from
from random import shuffle
all_letters = list(''.join([l*c for l,c in zip(letters, letter_count)]))
shuffle(all_letters)
for i in range(int(len(all_letters)/7)):
print all_letters[i*7:(i+1)*7]
So I assume this is for something like scrabble? Your issue is that you're choosing a random index from your list of letters, not bag_o_letters. Maybe try this:
rack = []
for i in range(7):
index = random.randint(0, len(bag_o_letter) - 1)
rack.append(bag_o_letters.pop(index))
I have a list:
word_list = ['dog', 'downvote', 'gestapo']
I would like this:
['d', 'o', 'g', 'w', 'n', 'v', 't', 'e', 's', 'a', 'p']
This is my code;
[list(word_list[j]) for j in range(len(word_list))]
This code returns this:
[['d', 'o', 'g'], ['d', 'o', 'w', 'n', 'v', 'o', 't', 'e'], ['g', 'e', 's', 't', 'a', 'p', 'o']]
Instead I tried this:
[(word_list[j])[k] for j in range(len(word_list)) for k in len(word_list[j])]
This returns an error: 'int' object is not iterable
I would like to rectify and update my final attempt so that I get the desired output.
If you want to preserve the original order of characters (as in the words from word_list):
def f(seq):
seen = set()
for x in (x for word in word_list for x in word):
if x not in seen:
seen.add(x)
yield x
list(f(word_list)) # ['d', 'o', 'g', 'w', 'n', 'v', 't', 'e', 's', 'a', 'p']
If you don't, just construct the set using set comprehension:
{x for word in word_list for x in word} # {'e', 'd', 'n', 'a', 't', 'w', 'o', 'g', 'v', 's', 'p'}
Although I think you are all technically correct.
The right way to do it in python would probably be:
from itertools import chain
set(chain(*word_list))
k=[]
for j in [list(i) for i in word_list]:
k += j
print list(set(k))
>>>>['d', 'o', 'g', 'w', 'n', 'v', 't', 'e', 's', 'a', 'p']
You could use reduce with operator.add, and a set.
>>> import operator
>>> words = ['dog', 'downvote', 'gestapo']
>>> set(reduce(operator.add, words))
set(['a', 'e', 'd', 'g', 'o', 'n', 'p', 's', 't', 'w', 'v'])
If you want it to be a list:
>>> list(set(reduce(operator.add, words)))
['a', 'e', 'd', 'g', 'o', 'n', 'p', 's', 't', 'w', 'v']
Note: it's not alphabetical order.
If the order is important, a simple way is to use(abuse?) an OrderedDict
>>> word_list = ['dog', 'downvote', 'gestapo']
>>> from collections import OrderedDict
>>> from itertools import chain
>>> OrderedDict.fromkeys(chain.from_iterable(word_list)).keys()
['d', 'o', 'g', 'w', 'n', 'v', 't', 'e', 's', 'a', 'p']