How do I count all the characters in a string without dictionary/set/lists? - character

Write and develop a function getPartsInCode which has one string parameter: productCode. The function returns a string in this format:
if product code is AABBBGH, then the function returns 2A 3B 1G 1H.
I can't seem to find any that's similar to the output I want to get. The closest was
word = input("Enter a word: ")
Alphabet=['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']
for i in range(0,26):
if word.count(Alphabet[i]) > 0:
print(word.count(Alphabet[i]))

What I would do is create a dictionary that corresponds each letter to a specific integer value.
def get_parts_in_code(code): # Creating a function that takes one parameter: code
# Creating a dictionary called 'alphabet' that stores every letter and its corresponding value
alphabet = {
'A': 0,
'B': 0,
'C': 0,
'D': 0,
'E': 0,
'F': 0,
'G': 0,
'H': 0,
'I': 0,
'J': 0,
'K': 0,
'L': 0,
'M': 0,
'N': 0,
'O': 0,
'P': 0,
'Q': 0,
'R': 0,
'S': 0,
'T': 0,
'U': 0,
'V': 0,
'W': 0,
'X': 0,
'Y': 0,
'Z': 0,
'OTHER': 0, # An 'other' category for spaces, underscores, etc (anything that isn't in the english alphabet)
}
code = code.upper() # Making everything upercase
code = list(code) # Converting our code into a list
code.sort() # Sorting it alphebetically
for letter in code: # For every letter in our list (code)
try:
alphabet[letter] += 1 # It should try to increase the corresponding value by one
except:
alphabet['OTHER'] += 1 # If that failed, then it means that the charecter is not in our dictionary, so we instead increase the 'OTHER' value
for letter in alphabet: # For every letter in our dictionary (alphabet)
if alphabet[letter] > 0: # Instead of printing all the zeroes, let's only print the values greater than 0
print(letter, alphabet[letter]) # Print the letter and the corresponding values
get_parts_in_code("hello world") #Executing the function
In this code, we go through each item in the code and increase the dictionary value by one. In the end, we go through each value in our dictionary 'alphabet', and if the value is greater than zero, we print it. Read the comments for a line-by-line description of the code.

Related

Repeat stream when done

hello I am using a stream on my app to get some data. at the end of data the stream stop, what i want is to start again every time stream is done
final stream = Stream.periodic(kDuration, (count) => count)
.take(kLocations.length);
stream.listen((value) => newLocationUpdate(value)
I was searching for hours and didnt find a good solution
Calling .take(kLocations.length) will cause the stream to close once that number of elements have been emitted. For example:
final stream = Stream.periodic(kDuration, (count) => count).take(3);
stream.listen(print); // prints 0, 1, 2, then stops
If instead, you want this to repeat (i.e. emit 0, 1, 2, 0, 1, 2, etc), you can use the modulus operator (%):
final stream = Stream.periodic(kDuration, (count) => count % 3);
stream.listen(print); // prints 0, 1, 2, 0, 1, 2, 0, 1, 2, ...

about or-tools OnlyEnforceIf,AddBoolAnd question

I have a Bool array, I want some ones to appear in certain places like this:
[1,1,1,1,0,0,0,0,0,0] or [0,0,0,0,0,0,1,1,1,1],here I want four ones appear in array's head,or tail,just two places,how can I do this?
model = cp_model.CpModel()
solver = cp_model.CpSolver()
shifts = {}
ones={}
sequence = []
for i in range(10):
shifts[(i)] = model.NewIntVar(0, 10, "shifts(%i)" % i)
ones[(i)] = model.NewBoolVar( '%i' % i)
for i in range(10):
model.Add(shifts[(i)] ==8).OnlyEnforceIf(ones[(i)])
model.Add(shifts[(i)] == 0).OnlyEnforceIf(ones[(i)].Not())
#I want the four 8s in the array to only appear in two positions at the head or tail of the array, and not in other positions.
model.AddBoolAnd([ones[(0)],ones[(1)],ones[(2)],ones[(3)]])# appear in head
#model.AddBoolAnd([ones[(6)],ones[(7)],ones[(8)],ones[(9)]]) #appear in tauk ,error!
model.Add(sum(ones[(i)] for i in range(10)) == 4)
status = solver.Solve(model)
print("status:",status)
res=[]
for i in range(10):
res.append(solver.Value(shifts[(i)]))
print(res)
bold
italic
quote
Try AddAllowedAsignments:
model = cp_model.CpModel()
ones = [model.NewBoolVar("") for _ in range(10)]
model.AddAllowedAssignments(
ones, [[1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1]]
)
Edit: #Laurent's suggestion
model = cp_model.CpModel()
ones = [model.NewBoolVar("") for _ in range(10)]
head = model.NewBoolVar("head")
# HEAD
model.AddImplication(head, ones[0])
model.AddImplication(head, ones[1])
model.AddImplication(head, ones[2])
model.AddImplication(head, ones[3])
model.AddImplication(head, ones[4].Not())
model.AddImplication(head, ones[5].Not())
...
# TAIL
model.AddImplication(head.Not(), ones[0].Not())
model.AddImplication(head.Not(), ones[1].Not())
....
model.AddImplication(head.Not(), ones[6])
model.AddImplication(head.Not(), ones[7])
model.AddImplication(head.Not(), ones[8])
model.AddImplication(head.Not(), ones[9])

Distribute elements evenly (adding ints values to array of int values)

Say I have an array of Ints and all elements equal zero. It'd look something like this:
let arr: [Int] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
There are 11 elements in this array in total. I want three of the elements in this array to be the number one. I want these one values to be distributed evenly throughout the array so that it looks something like this:
[0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0]
I want to be able to add however many one's and distribute them evenly (or as close to evenly as possible) no matter how many total elements there are. How could I do this?
Note: For anyone wondering why I need this, I have a collection of strings that when joined together make up a large body of text. Think of the zeroes as the pieces of text and think of the ones as advertisements I am adding in between the text. I wanted to distribute these ads as evenly as possible. I figured this would be a simple way of expressing what I needed.
Maybe you can try this.
var arr: [Int] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
let distribution = arr.count / 3 // 3 is the number of 1s
for (index, value) in arr.enumerated() {
arr[index] = (index + 1) % distribution == 0 ? 1 : value
}
print(arr) // [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0]
Assuming that the value distribution > 1

Using textscan in Matlab to handle data not properly formatted data

I'm using textscan to import data. I can get to it successfully import properly formatted data. I can't get it to properly handle data that isn't properly formatted. Below is the format of the data.
JeB2021Da 12-13 and stuff, 1, 1, 0, 1, 0, 1, 1, 1, 3, 1, 99, 0, 0, 0,
JoB2021Ha 12-13 and stuff, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 99, 2, 1, 0,
JoP2021Co 12-13 and stuff, not enough samples
MaA2021Be 12-13 and stuff, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 99, 1, 0, 0,
MaA2021Ma 12-13 and stuff, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 99, 1, 0, 0,
How would I handle the data that is, not enough samples? Because currently the data structures don't line up. The data structures that are being produced are 17 x 1 and 16 x 14. I'd like to import the string as it is in the data. So not enough samples would be imported. Below is the code that I'm using.
fid = fopen('./file.txt','r');
fmt = ['%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d'];
d = textscan(fid, fmt, 'CollectOutput', 1,'Delimiter',',','headerLines', 1, 'EmptyValue', 0);
I'm trying to handle it with the EmptyValue flag but it's not working. Any help is greatly appreciated.
I am not sure what exactly you mean by I'd like to import the string as it is in the data, or more exactly where you would like to have that string stored.
But about just reading your data as a whole you can use the 'TreatAsEmpty' argument:
d = textscan(fid, fmt, 'CollectOutput', 1,'Delimiter',',','headerLines', 1,'TreatAsEmpty','not enough samples');
Then you can modify the input further by looking for the rows in the imported data array that solely consist of zeros.

Why doesn't this coffee-script print out?

So when the index is 0, I want to print it out:
a = [ 1, 2, 3 ]
for i of a
if i == 0
console.log a[i]
But there is no output.
i == 0 is never true...
i returns the index as a string, if you parse them as an integer, it would work
a = [ 1, 2, 3 ]
for i of a
if parseInt(i) == 0
console.log a[i]
It's because i will only be 1, 2 or 3, as you loop over the items in a, not the index numbers.
This works the way you described above:
a = [ 1, 2, 3 ]
for i in [0..a.length]
if i == 0
console.log a[i]
You shouldn't use of to loop over an array, you should use in. From the fine manual:
Comprehensions can also be used to iterate over the keys and values in an object. Use of to signal comprehension over the properties of an object instead of the values in an array.
yearsOld = max: 10, ida: 9, tim: 11
ages = for child, age of yearsOld
"#{child} is #{age}"
So you're trying to iterate over the properties of an array object, not its indexes.
You should use one of these for your loop:
for e, i in a
if(i == 0)
console.log(a[i])
for e, i in a
console.log(e) if(i == 0)
console.log(e) for e, i in a when i == 0
#...
Or, since you have an array and a numeric index, why not just skip the loop and get right to the point:
console.log(a[0])