In my hangman program, I am experiencing some difficulties in trying to organize the user's correctly guessed inputs (when they guess a letter correctly). For example, if the word was "frog", and the user guessed in the order "r", "o", "f", "g", the program should sort it (eventually) into "frog". When I do the .sort() function, it arranges it in alphabetical order (e.g. "fgor" for "frog"). Before using the .sort() method, I had no means of arranging it.
Here is a small piece of my code (pretending the word is "frog" which it isn't in my program):
word = "frog"
guess = input("Put in a letter") # with an iteration of a while loop
def hangman():
nothing = []
points = 0
while num_of_lives >= 1:
guess = input("Put in a letter: ")
for i in word1:
if guess in i:
print(guess, "is one of the letters")
points += 1
nothing += i
nothing2 = []
for y in nothing[:]:
nothing2[0:] += y[0:]
nothing2.sort()
print(nothing2)
You can define a custom sort method using this technique:
https://www.geeksforgeeks.org/python-list-sort/
# Python program to demonstrate sorting by user's
# choice
# function to return the second element of the
# two elements passed as the parameter
def sortSecond(val):
return val[1]
# list1 to demonstrate the use of sorting
# using using second key
list1 = [(1, 2), (3, 3), (1, 1)]
# sorts the array in ascending according to
# second element
list1.sort(key = sortSecond)
print(list1)
You just need to create a function that returns the letter's position in the original word. This can be used to yield the key for comparison. For that I would look at pythons' list.index
I am absolutely new in lua and just want to modify an existing script.
There is a function that writes values in a list. I would like to sort them by name:
function display_moments()
local counter = 1
if(moments[media_name]~=nill) then
moments_list = main_layout:add_list(1,4,4,1) -- empty moments_list widget to prevent duplicate entries
for i,j in pairs(moments[media_name]) do
moments_list:add_value(i,counter)
counter = counter + 1
end
end
end
Do I have the chance to get my list sorted in any way?
From Lua table.sort (ref manual) if your list is as follows
local _list = {1,4,4,1}
print(unpack(_list)) -- 1, 4, 4, 1
table.sort(_list)
print(unpack(_list)) -- 1, 1, 4, 4
you can add following line after the loop, given that your list is an array
table.sort(moments_list)
How do I make a number argument a variable?
For example:
Snippet 1:
a=1
a_7 = a+6
alphabet = "ABCDEFGHIJKLMNOPQRSTUVQXYZ"
letter_7 = alphabet.slice[a_7..a_7]
Snippet 2:
alphabet = "ABCDEFGHIJKLMNOPQRSTUVQXYZ"
letter_7 = alphabet.slice[7..7]
I would like to make snippet 1 have the same outcome as snippet 2, with a variable as the arguments within slice action. Is there a way to do this?
So your issue come from the fact that you are using the slice method without any arguments. You can not use [] with the slice method. To make this work, you need to change [] to ()
letter_7 = alphabet.slice(7..7)
This will actually return H as the result, because arrays index start at 0, so to get the 7th letter, you will need to slice at index 6.
letter_7 = alphabet.slice(6..6) #=> 'G'
Or, you can just use the [] method on the string itself.
letter_7 = alphabet[6] #=> 'G'
Of course, you can replace the index values with variables, as long as the variables are set to integers.
a = 6
letter_7 = alphabet[a] #=> 'G'
I have two arrays. One Mapper and one with my ID's.
My Array with the external ID's:
genres_array = [12,28,16]
The Mapper Array (Internal-ID, External-ID)
mapper = [
[1,12],
[2,18],
[3,19],
[4,28],
[5,16],
[6,90],
]
As Result i would like to have now a new array, with only the internal values of the genres_array (the genres_array had the external values first). In this case the result would be [1,4,5]
I tried a lot of ways but i really have no idea how to solve this simple problem in a clean way. Im pretty sure it will be something like
genres_array.map { |genre_id| get_internal_id_from_mapper }
PS: It could also happen that a ID won't be found in the mapper. In that i case i just want to remove it from the array. Any idea?
You're looking for rassoc:
genres_array.map { |genre_id| mapper.rassoc(genre_id)[0] }
Which results in
[1, 4, 5]
EDIT: Just read the PS - try something like this:
genres_array.map { |genre_id|
subarr = mapper.rassoc genre_id
subarr[0] if subarr
}.compact
Then for an input of
genres_array = [12,28,100,16]
You would still get the output
[1, 4, 5]
Another way that won't throw an exception if the external id is not found:
genres_array = [12,28,16]
mapper = [
[1,12],
[2,18],
[3,19],
[4,28],
[5,16],
[6,90],
]
internal_ids = genres_array.map do |genre_id|
element = mapper.detect { |m| m[1] == genre_id }
element ? element[0] : nil
end.compact
Another solution involving a hash:
Hash[mapper].invert.values_at(*genres_array)
Asking for values that does not exist will return nil, if you do not want the nil just add .compact at the end.
I have a key => value table I'd like to sort in Lua. The keys are all integers, but aren't consecutive (and have meaning). Lua's only sort function appears to be table.sort, which treats tables as simple arrays, discarding the original keys and their association with particular items. Instead, I'd essentially like to be able to use PHP's asort() function.
What I have:
items = {
[1004] = "foo",
[1234] = "bar",
[3188] = "baz",
[7007] = "quux",
}
What I want after the sort operation:
items = {
[1234] = "bar",
[3188] = "baz",
[1004] = "foo",
[7007] = "quux",
}
Any ideas?
Edit: Based on answers, I'm going to assume that it's simply an odd quirk of the particular embedded Lua interpreter I'm working with, but in all of my tests, pairs() always returns table items in the order in which they were added to the table. (i.e. the two above declarations would iterate differently).
Unfortunately, because that isn't normal behavior, it looks like I can't get what I need; Lua doesn't have the necessary tools built-in (of course) and the embedded environment is too limited for me to work around it.
Still, thanks for your help, all!
You seem to misunderstand something. What you have here is a associative array. Associative arrays have no explicit order on them, e.g. it's only the internal representation (usually sorted) that orders them.
In short -- in Lua, both of the arrays you posted are the same.
What you would want instead, is such a representation:
items = {
{1004, "foo"},
{1234, "bar"},
{3188, "baz"},
{7007, "quux"},
}
While you can't get them by index now (they are indexed 1, 2, 3, 4, but you can create another index array), you can sort them using table.sort.
A sorting function would be then:
function compare(a,b)
return a[1] < b[1]
end
table.sort(items, compare)
As Komel said, you're dealing with associative arrays, which have no guaranteed ordering.
If you want key ordering based on its associated value while also preserving associative array functionality, you can do something like this:
function getKeysSortedByValue(tbl, sortFunction)
local keys = {}
for key in pairs(tbl) do
table.insert(keys, key)
end
table.sort(keys, function(a, b)
return sortFunction(tbl[a], tbl[b])
end)
return keys
end
items = {
[1004] = "foo",
[1234] = "bar",
[3188] = "baz",
[7007] = "quux",
}
local sortedKeys = getKeysSortedByValue(items, function(a, b) return a < b end)
sortedKeys is {1234,3188,1004,7007}, and you can access your data like so:
for _, key in ipairs(sortedKeys) do
print(key, items[key])
end
result:
1234 bar
3188 baz
1004 foo
7007 quux
hmm, missed the part about not being able to control the iteration. there
But in lua there is usually always a way.
http://lua-users.org/wiki/OrderedAssociativeTable
Thats a start. Now you would need to replace the pairs() that the library uses. That could be a simples as pairs=my_pairs. You could then use the solution in the link above
PHP arrays are different from Lua tables.
A PHP array may have an ordered list of key-value pairs.
A Lua table always contains an unordered set of key-value pairs.
A Lua table acts as an array when a programmer chooses to use integers 1, 2, 3, ... as keys. The language syntax and standard library functions, like table.sort offer special support for tables with consecutive-integer keys.
So, if you want to emulate a PHP array, you'll have to represent it using list of key-value pairs, which is really a table of tables, but it's more helpful to think of it as a list of key-value pairs. Pass a custom "less-than" function to table.sort and you'll be all set.
N.B. Lua allows you to mix consecutive-integer keys with any other kinds of keys in the same table—and the representation is efficient. I use this feature sometimes, usually to tag an array with a few pieces of metadata.
Coming to this a few months later, with the same query. The recommended answer seemed to pinpoint the gap between what was required and how this looks in LUA, but it didn't get me what I was after exactly :- which was a Hash sorted by Key.
The first three functions on this page DID however : http://lua-users.org/wiki/SortedIteration
I did a brief bit of Lua coding a couple of years ago but I'm no longer fluent in it.
When faced with a similar problem, I copied my array to another array with keys and values reversed, then used sort on the new array.
I wasn't aware of a possibility to sort the array using the method Kornel Kisielewicz recommends.
The proposed compare function works but only if the values in the first column are unique.
Here is a bit enhanced compare function to ensure, if the values of a actual column equals, it takes values from next column to evaluate...
With {1234, "baam"} < {1234, "bar"} to be true the items the array containing "baam" will be inserted before the array containing the "bar".
local items = {
{1004, "foo"},
{1234, "bar"},
{1234, "baam"},
{3188, "baz"},
{7007, "quux"},
}
local function compare(a, b)
for inx = 1, #a do
-- print("A " .. inx .. " " .. a[inx])
-- print("B " .. inx .. " " .. b[inx])
if a[inx] == b[inx] and a[inx + 1] < b[inx + 1] then
return true
elseif a[inx] ~= b[inx] and a[inx] < b[inx] == true then
return true
else
return false
end
end
return false
end
table.sort(items,compare)