I want to create a list of items from a range using the map command. I have the following code that's supposed to take the range between two numbers (firstnum and secondnum) and a lambda statement that says to increment between the two numbers and create myList of the results (between the two ends of the range). However my syntax is wrong, not sure why...
["myList"] = map(lambda x, y: x + 1, range(firstnum..secondnum))
This would be valid syntax:
>>> list(map(lambda x: x + 1, range(2, 12)))
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
But you can get the same result much simpler:
>>> list(range(3, 13))
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Or more general:
>>> firstnum = 2
>>> secondnum = 12
>>> (list(map(lambda x: x + 1, range(firstnum, secondnum))) ==
list(range(firstnum + 1, secondnum + 1)))
True
Related
The question I am given is
We are given an array.
In one operation we can replace any element of the array with any two elements that sum to that element.
For example: array = {4, 11, 7}. In one operation you can replace array[1] with 5 and 6 which sums to 11. So the array becomes array = {4, 5, 6, 7}
Return the minimum number of steps in which the whole array can be sorted in non-decreasing order. Along with array in sorted order.
For example: array = {3,9,3}
I think the answer will be 9 will be converted to 3,3,3
But I cannot think of a general formula of doing it.
My thoughts on the solution are
Suppose we want to convert number 6 and 9
We use if and else
IF
we see that we divide a number by 2 and take ceiling but it is greater than the number on it's right side(last example in the question) then we keep subtracting that number(3) until we get integer 0.
That is 9 = 3(number on right of 9 in array in last example) - 3 - 3
ELSE
simply do ceiling(num / 2) to get first number and then num - ceil(num / 2) to ger second. 7 will be 4 and 3.
Please can someone think of a general formula for doing it?
Edy's way (as I interpret it) in Python:
def solve(xs):
limit = 10**100
out = []
for x in reversed(xs):
parts = (x - 1) // limit + 1
limit, extra = divmod(x, parts)
out += extra * [limit+1] + (parts - extra) * [limit]
print(len(out) - len(xs), out[::-1])
solve([4, 11, 7])
solve([3, 9, 3])
solve([9, 4, 15, 15, 28, 23, 13])
Output showing steps and result array for the three test cases (Try it online!):
1 [4, 5, 6, 7]
2 [3, 3, 3, 3, 3]
8 [3, 3, 3, 4, 5, 5, 5, 7, 8, 9, 9, 10, 11, 12, 13]
An output illustrating the progress:
[4, 11, 7] = (input)
[4, 11, [7]]
[4, [5, 6], [7]]
[[4], [5, 6], [7]]
[3, 9, 3] = (input)
[3, 9, [3]]
[3, [3, 3, 3], [3]]
[[3], [3, 3, 3], [3]]
[9, 4, 15, 15, 28, 23, 13] = (input)
[9, 4, 15, 15, 28, 23, [13]]
[9, 4, 15, 15, 28, [11, 12], [13]]
[9, 4, 15, 15, [9, 9, 10], [11, 12], [13]]
[9, 4, 15, [7, 8], [9, 9, 10], [11, 12], [13]]
[9, 4, [5, 5, 5], [7, 8], [9, 9, 10], [11, 12], [13]]
[9, [4], [5, 5, 5], [7, 8], [9, 9, 10], [11, 12], [13]]
[[3, 3, 3], [4], [5, 5, 5], [7, 8], [9, 9, 10], [11, 12], [13]]
Code for that (Try it online!):
def solve(xs):
print(xs, '= (input)')
limit = 10**100
for i, x in enumerate(reversed(xs)):
parts = (x - 1) // limit + 1
limit, extra = divmod(x, parts)
xs[~i] = (parts - extra) * [limit] + extra * [limit+1]
print(xs)
print()
You would want to scan from the right to the left. For convenient explanation, let's mark the right-most element x_0, and the left-most x_{n-1} (n can increase as you split a number into two).
If x_{i} > x_{i-1}, you would want to divide x_{i} into ((x_{i} - 1) / x_{i-1}) + 1 parts, where / is integer division, as evenly as possible.
So for example:
If x_{i} = 15, x_{i-1] = 5, divide x_{i} into (15-1)/5 + 1 = 3 parts: (5, 5, 5).
If x_{i} = 19, x_{i-1] = 5, divide x_{i} into (19-1)/5 + 1 = 4 parts: (4, 5, 5, 5).
(To divide a number equally into a non-decreasing sequence would require a bit of calculation, which shouldn't be too difficult.)
Once you know the sequence, it would be straightforward to repeatedly split a number into 2 to produce that sequence.
I found iterable functions, but I am not sure how I can use.
For example, skip, take, map, forEach, fold and join
Could you give me examples how to use?
Yes, let's check the following sample code.
List<int> values = [1, 2, 3, 4, 5, 6, 7, 8, 9];
print(values.skip(5).toList());
//[6, 7, 8, 9]
print(values.skip(5).take(3).toList());
//[6, 7, 8]
values.skip(5).take(3).map((e) => e.toString()).forEach((element) {print(element);});
//6 7 8
String str = values.fold("initialValue",
(previousValue, element) => previousValue + ", " + element.toString());
print(str);
//initialValue, 1, 2, 3, 4, 5, 6, 7, 8, 9
str = values.join(", ");
print(str);
//1, 2, 3, 4, 5, 6, 7, 8, 9
skip(1) skips the first value, 1, in the values list literal.
take(3) gets the next 3 values 2, 3, and 4 in the values list literal.
map() Returns a new lazy [Iterable] with elements that are created by calling f on each element of this Iterable in iteration order.
fork() Reduces a collection to a single value by iteratively combining each element of the collection with an existing value
join() Converts each element to a [String] and concatenates the strings.
Hi Avdienko and welcome to Stack Overflow. I will give you an example for a .forEach iterable function performed on a List.
List<int> listOfIntegers = [1, 2, 3, 4, 5];
listOfIntegers.forEach((element) {
print(element.toString() + " ");
});
This code will result in printing "1 2 3 4 5 " to the console.
I am looking for a fast implementation of the following code; using, for instance, map() or next():
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
total_so_far = 0
for i in l:
total_so_far += i
if total_so_far > 14:
break
print(i)
The code prints the index of item in list where sum of start of list to the index is greater greater than 14.
Note: I need to continuously update the link in another loop. Therefore, a solution in numpy would probably be too slow, because it cannot update a list in-place.
You can also make use of itertools.accumulate() together with enumerate() and next():
In [1]: from itertools import takewhile
In [2]: l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [3]: next(index for index, value in enumerate(accumulate(l)) if value > 14)
Out[3]: 5
possible_list = []
bigger_list = []
new_list= [0, 25, 2, 1, 14, 1, 14, 1, 4, 6, 6, 7, 0, 10, 11]
for i in range(0,len(new_list)):
# if the next index is not greater than the length of the list
if (i + 1) < (len(new_list)):
#if the current value is less than the next value
if new_list[i] <= new_list[i+1]:
# add the current value to this sublist
possible_list.append(new_list[i])
# if the current value is greater than the next, close the list and append it to the lager list
bigger_list.append(possible_list)
print bigger_list
How do I find the longest consistent increment in the list called new_list?
I expect the result to be
[[0,2], [2], [1,14], [1,14], [1,4,6,6,7], [0,10,11]]
I can find the remaining solution from there myself.
One problem (but not the only one) with your code is that you are always adding the elements to the same possible_list, thus the lists in bigger_list are in fact all the same list!
Instead, I suggest using [-1] to access the last element of the list of subsequences (i.e. the one to append to) and [-1][-1] to access the last element of that subsequence (for comparing the current element to).
new_list= [0, 25, 2, 1, 14, 1, 14, 1, 4, 6, 6, 7, 0, 10, 11]
subseq = [[]]
for e in new_list:
if not subseq[-1] or subseq[-1][-1] <= e:
subseq[-1].append(e)
else:
subseq.append([e])
This way, subseq ends up the way you want it, and you can use max to get the longest one.
>>> subseq
[[0, 25], [2], [1, 14], [1, 14], [1, 4, 6, 6, 7], [0, 10, 11]]
>>> max(subseq, key=len)
[1, 4, 6, 6, 7]
I am making this multiplication program in python 2.7.5 for my sister, and I don't know how to count the correct answers. Here is the code:
import easygui
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
answer = easygui.enterbox("What is " + str(i) + ' times 8?')
if int(answer) == i * 8:
easygui.msgbox("That is correct!")
else:
easygui.msgbox("Wrong!")
Why not just add a variable to keep count for you?
import easygui
correct_answers = 0 # start with none correct
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
answer = easygui.enterbox("What is " + str(i) + ' times 8?')
if int(answer) == i * 8:
easygui.msgbox("That is correct!")
correct_answers += 1 # increment
else:
easygui.msgbox("Wrong!")
You could improve your program by making the base number a variable, too, and using Python's str.format() rather than addition:
base = 8
...
answer = easygui.enterbox("What is {0} times {1}?".format(i, base))
if int(answer) == i * base:
...