Recurring Character Counter - python-3.6

Good day:
would like to ask a simple question regarding my code on Python 3.6
I want to count all the characters that repeats itself
here is the sample of the code that i worked on:
name01 = input("1st Name: ")
ch_name01 = []
bl_char = False
i = 0
for ch in name01:
i = 0
for ich in ch_name01:
bl_char = False
if ich[i][0] == ch:
bl_char = True
#ch_name01[i][1] = ch_name01[i][1] + 1
#print(str(ch_name01[i][0]) + " - " + str(ch_name01[i][1]))
if not bl_char:
i = i + 1
if bl_char == False:
ch_name01.append([ch, 1])
print(ch_name01)
#print(ch_name01)
for example input "aabbccddef"
would like to return a = 2, b = 2, c = 2, d = 2
but it will return error message
"TypeError: 'int' object is not subscriptable"
on if ich[i][0] == ch:

Using a dictionary will make your life so much easier here.
name01 = input("1st Name: ")
ch_name01 = {} # New dictionary
for ch in name01: # For every char in the input string
if ch in ch_name01: # If that char already has an entry in the dictionary
ch_name01[ch] += 1 # increment that char's entry's integer value
else: # the char hasn't been added to the dictionary yet
ch_name01[ch] = 1 # add a new dictionary entry with an integer value of 1
print(ch_name01)
Supplying input of aabbccddef produces:
{'a': 2, 'b': 2, 'c': 2, 'd': 2, 'e': 1, 'f': 1}
Edit:
I added code comments to explain what each line is doing

Related

Lua timer script producing all-numeric value instead of proper time

My timer script writes this into the file when it saves the value.
Example Time in file: 1638185640
Example of time displayed in game:
name = "Timer"
description = "Just a normal Timer."
positionX = 0
positionY = 0
sizeX = 24
sizeY = 10
scale = 1
START_STOP_KEY = 0x55 --or 'U'
RESET_KEY = 0x4A --or 'J'
--
--[[
Timer Module Script by SebyGHG original script by Onix64(Stopwatch)
if you wish to change the key you can take the key code from here
https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
]] -------------script-code-------------
state = 1
stopTime = 0
startTime = 0
f = io.input("timesave.txt")
result = f :read()
f :close()
stopTime = result
state = 2
function keyboard(key, isDown)
if (isDown == true) then
if (key == RESET_KEY) then
state = 0
elseif (key == START_STOP_KEY) then
if (state == 0) then
state = 1
startTime = os.time()
elseif (state == 1) then
state = 2
io.output("timesave.txt")
timesave= (io.open("timesave.txt","w"))
io.write(stopTime)
io.close(timesave)
stopTime = os.time() -stopTime
elseif (state == 2) then
state = 1
startTime =startTime + os.time() - stopTime
end
end
end
end
TimerText = "00:00"
TextColor = {r = 30, g = 255, b = 30, a = 255}
function doubleDigit(number)
if (number < 10) then
return "0" .. math.floor(number)
else
return math.floor(number)
end
end
function timeText(time)
local result = ""
local days = 0
while (time > 86399) do
days = days + 1
time = time - 86400
end
local hours = 0
while (time > 3599) do
hours = hours + 1
time = time - 3600
end
local minutes = 0
while (time > 59) do
minutes = minutes + 1
time = time - 60
end
if (days == 0) then
if (hours == 0) then
return doubleDigit(minutes) .. ":" .. doubleDigit(time)
else
return math.floor(hours) .. " : " .. doubleDigit(minutes) .. ":" .. doubleDigit(time)
end
else
return math.floor(days) ..
" : " .. doubleDigit(hours) .. " : " .. doubleDigit(minutes) .. ":" .. doubleDigit(time)
end
end
function update()
if (state == 0) then
TextColor = {r = 255, g = 0, b = 0, a = 255}
TimerText = "00:00"
elseif (state == 1) then
TimerText = timeText(os.time() - startTime)
TextColor = {r = 0, g = 255, b = 255, a = 255}
elseif (state == 2) then
TimerText = timeText(stopTime - startTime)
TextColor = {r = 255, g = 255, b = 0, a = 255}
end
end
function render()
local font = gui.font()
local tw = font.width(TimerText)
gfx.color(0, 0, 0, 0)
gfx.rect(0, 0, tw + 4, 10)
gfx.color(TextColor.r, TextColor.g, TextColor.b, TextColor.a)
gfx.text(2, 1, TimerText)
end
It looks like you are saving the Unix Timestamp to your file, you can try and make it human readable using an online time converter (https://time.is/Unix_time_converter)
Besides this, take some time to read the os.time() implementation details on this lua page: https://www.lua.org/pil/22.1.html
The time function, when called without arguments, returns the current date and time, coded as a number. (In most systems, that number is the number of seconds since some epoch.)
If you want the time in between certain action, save the initial timestamp and diff it at the end of the action. This is natively supported in lua using os.difftime(). (http://www.lua.org/manual/5.3/manual.html#pdf-os.difftime)

Creating advance lua array table from list view and call the array elements

Say I have a CE Lua form and some variables:
form.Show()
list = form.CEListView1
tab_player = {}
p_name = 'Joe'
p_gen = 'Male'
table.insert(tab_player,{player_name = p_name, player_gen = p_gen})
-- and then add some elements from List View to same record index
for idx = list.ItemIndex + 1, list.Items.Count-1 do
mtrl_name = list.Items[idx].Caption
mtrl_qty = list.Items[idx].SubItems[0]
mtrl_unit = list.Items[idx].SubItems[1]
mtrl_price = list.Items[idx].SubItems[2]
mtrl_tprice = list.Items[idx].SubItems[3]
table.insert(tab_player, {v_itemname = mtrl_name, v_itemqty = mtrl_qty,
v_itemunit = mtrl_unit, v_itemprice = mtrl_price, v_itemttlprice = mtrl_tprice})
end
-- check
for index, data in ipairs(tab_player) do
print(index)
for key, value in pairs(data) do
print('\t', key, value)
end
end
Result, it's created 9 tab_player record indexes (depending how many items on list view).
What I want is like this structure for one record index:
tab_player =
{
player_name = p_name,
player_gen = p_gen,
{
v_itemname = mtrl_name,
v_itemqty = mtrl_qty,
v_itemunit = mtrl_unit,
v_itemprice = mtrl_price,
v_itemttlprice = mtrl_tprice},
{
v_itemname = mtrl_name,
v_itemqty = mtrl_qty,
v_itemunit = mtrl_unit,
v_itemprice = mtrl_price,
v_itemttlprice = mtrl_tprice},
{
v_itemname = mtrl_name,
v_itemqty = mtrl_qty,
v_itemunit = mtrl_unit,
v_itemprice = mtrl_price,
v_itemttlprice = mtrl_tprice}
-- and so on
}
How CE Lua script to get the structure as I want?
If done, then how CE Lua script call the data from tab_player to fill player name editbox, player gen editbox and fill the items to CE List View?
EDIT:
What I want to be produce an array table with structure below:
list = UDF1.CEListView1
tab_player = {}
player_name = 'Joe'
player_gen = 'Male'
-- this is list view items contain:
--- row 1, column 1 to 5
mtrl_name = list.Items[1].Caption -- Milk
mtrl_qty = list.Items[1].SubItems[0] -- 300
mtrl_unit = list.Items[1].SubItems[1] -- ml
mtrl_price = list.Items[1].SubItems[2] -- 3975
mtrl_tprice = list.Items[1].SubItems[3] -- 3975
--- row 2, column 1 to 5
mtrl_name = list.Items[2].Caption -- Sugar
mtrl_qty = list.Items[2].SubItems[0] -- 1
mtrl_unit = list.Items[2].SubItems[1] -- Kg
mtrl_price = list.Items[2].SubItems[2] -- 18000
mtrl_tprice = list.Items[2].SubItems[3] -- 18000
--- row 3, column 1 to 5 and so om
the tab_player should be:
tab_player = {
-- index 0 or record 1
{player_name = 'Joe', player_gen = 'Male',
-- row 1, column 1 to 5
{
item_name = 'Milk',
item_qty = 300,
item_unit = 'ml',
item_price = 3975,
item_tprice = 3975
},
-- row 2, column 1 to 5
{
item_name = 'Sugar',
item_qty = 2,
item_unit = 'Kg',
item_price = 9000
item_tprice = 18000
},
-- row 3, column 1 to 5
{
item_name = 'bla bla bla',
item_qty = 1,
item_unit = 'bla',
item_price = 1000000
item_tprice = 1000000
}
-- and so on
}
How to create, print multidimensional and call back the item from the array table as above?.

Julia: Console Input Validation

How do you guys handle console input validation? In C++, case/switch is my goto...
I was trying a recursive function but was getting locked in lower levels. Plus that might be overdoing it. I did manage a while loop with an "exclusive or" but, that is not really scalable.
function prob6()
println("Pick a number; any number:")
x = readline(stdin)
y = parse(Int64, x)
z = 0
println("Select 1 or 2")
p1 = readline(stdin)
p2 = parse(Int64, p1)
select = p2
while xor((p2 == 1), (p2 == 2)) == false
println("Select 1 or 2")
p1 = readline(stdin)
p2 = parse(Int64, p1)
select = p2
end
if select == 1
for i in 1:y
print("$i ")
z = z + i
end
else
z = 1
for i in 1:y
print("$i ")
z = z * i
end
end
println(z)
end
Any alternatives?
There are many ways. I usually create a validation loop to check the type of the input item, and will use tryparse instead of parse, since it will not throw an error if input is malformed:
function queryprompt(query, typ)
while true
print(query, ": ")
choice = uppercase(strip(readline(stdin)))
if (ret = tryparse(typ, choice)) != nothing
return ret
end
println()
end
end
n = queryprompt("Integer please", Int64)
println(n)
x = queryprompt("Float please", Float64)
println(x)

Fail Safe Fail Fast Example

ConcurrentHashMap<String, Integer> hm = new ConcurrentHashMap<>();
hm.put("1", 1);
hm.put("2", 2);
hm.put("3", 3);
Iterator<String> itr = hm.keySet().iterator();
while(itr.hasNext()){
String key = itr.next();
System.out.println(key + " : " + hm.get(key));
hm.put("4", 4);
}
System.out.println(hm);
ConcurrentHashMap<String, Integer> hm1 = new ConcurrentHashMap<>();
hm1.put("One", 1);
hm1.put("Two", 2);
hm1.put("Three", 3);
Iterator<String> itr1 = hm1.keySet().iterator();
while(itr1.hasNext()){
String key = itr1.next();
System.out.println(key + " : " + hm1.get(key));
hm1.put("Four", 4);
}
System.out.println(hm1);
Output:
1 : 1
2 : 2
3 : 3
4 : 4
{1=1, 2=2, 3=3, 4=4}
One : 1
Two : 2
Three : 3
{One=1, Four=4, Two=2, Three=3}
Why so?
The interator() call has this documentation:
https://docs.oracle.com/javase/8/docs/api/java/util/Set.html#iterator--
"The elements are returned in no particular order"
hm.put("4", 4)
Adds it to the end of the list (by chance?)
hm1.put("Four", 4)
Adds it between One and Four. However the next() operator is evidently already past this point in the Iterator, so the next call to next() is already at Two=2.
Answer:
Changing an unordered list as you're iterating over the same list is not a good idea.

How to find the first differentials between elements in a list of list?

I have a list of list as follow:
data = [
[0.051, 0.05],
[],
[],
[],
[],
[],
[0.03],
[0.048],
[],
[0.037, 0.036, 0.034, 0.032],
[0.033, 0.032, 0.03]
]
I am trying to find the first difference between the elements in each sub-list but couldn't quite figure out how to do so with python. Here's what i wrote:
x = {}
index = 0
for item in data:
if len(item) < 2:
x[index] = "NA"
index += 1
else:
try:
x[index] = item[0] - item[1]
index += 1
except IndexError:
x[index] = "NA"
index += 1
y = {}
index = 0
for item in data:
if len(item) < 2:
y[index] = "NA"
index += 1
else:
try:
y[index] = item[1] - item[2]
index += 1
except IndexError:
y[index] = "NA"
index += 1
z = {}
index = 0
for item in data:
if len(item) < 2:
z[index] = "NA"
index += 1
else:
try:
z[index] = item[2] - item[3]
index += 1
except IndexError:
z[index] = "NA"
index += 1
However, I would much prefer a more dynamic version that could extend based on the number of elements in each sub-list. Mathematically, there will be n - 1 first differential x for n elements.
data = [
[0.051, 0.05],
[],
[],
[],
[],
[],
[0.03],
[0.048],
[],
[0.037, 0.036, 0.034, 0.032],
[0.033, 0.032, 0.03]
]
x = {}
for i in range(0,len(data)):
tmp = []
#print "\ndata[i]= ", data[i]
try:
z = 0
for s in range(0,len(data[i])):
try:
z = str(data[i][s] - data[i][s+1]) #WITHOUT THIS STR() HERE VALUES GOT ROUNDED - so instead of getting 0.001 it was 0.000999999999994 or sth like that.
#print "difference = ", z
tmp.append(z)
#print "tmp = ", tmp
except:
pass
#print "inside error"
except:
pass
#print "error"#, i
x[i+1] = tmp
print x
Here is my working code. I hope it's what you meant.
----> v THIS IS FIXED v <----
I have only one problem with it - for example:
difference = 0.001
tmp = [0.000999999999999994]
difference (z variable) is appended to tmp, and tmp looks like "rounded" instead of full 0.001, I don't really know how to format it properly :(.
I will try work on it now and I will edit my post if I manage to do it somehow.
#### FIX EDIT: #####
I fixed it by changing the difference value to str instead of leaving it as float.

Resources