Opperations inside a list with different elements - list

The teacher assistant assigned me this problem but I could not understand if this op is possible:
Create a list with int, str and float: my_list = [2, 3, 0.5, "cams"]
print only the odd numbers in this list
I am not sure if I can operate conditions in a list with different elements. Please help!

Python:
my_list = [2, 3, 0.5, "cams"]
for i in my_list:
if type(i) is not str and i%2 == 1:
print(i)
JS:
my_list = [2, 3, 0.5, "cams"]
for(let i=0;i<my_list.length;i++){
if(typeof(my_list[i]) != "string" && i%2 == 1){
console.log(my_list[i])
}
}
Output:
3

Related

Python list append different lists in the same scope for the same variable

Okay. I write an algorithm for show me all the permutations of a list of integers. But during the algorithm I got a problem to append a permuted list to my result list.
The code is the heap's algorithm. I got my finished permutation when size == 1. So a can append the permutated list V to my final list res. Here's the code:
The function for permutate the list
def permutations(V, size):
global res
if size == 1:
print(V)
res.append(V)
for i in range(0, size):
permutations(V, size-1)
if size % 2 == 1:
V[size-1], V[0] = V[0], V[size-1]
else:
V[i], V[size-1] = V[size-1], V[i]
A = [1,2,3]
res = []
permutation(A, len(A))
print(res)
And this is the output:
[1, 2, 3]
[2, 1, 3]
[3, 1, 2]
[1, 3, 2]
[2, 3, 1]
[3, 2, 1]
res: [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
The printed permutations of V are all correct. But the list V append to my global res are not change. They are being append right after the print and the list append is different.
If you change the lines like this:
res.append(V)
|
|
v
D = [V[i] for i in range(len(V))]
res.append(D)
The results is correct on the final. Anyone can explain how can a printed list can be different from a appended list using the same variable.
Replace res.append(V) with res.append(list(V)) simply fixes your issue.
All V you appended to the res are references to the same object. This can be observed by printing the id of each element in the list:
for i in res:
print(id(i))

Python2 : Create a list of dictionaries from two list of values

I have two input lists as following:
x_values = [1,2,3]
y_values = [1,2,3]
Is there a quick way to create a list of dictionaries from these two lists, like following:
points = [{x=1, y=1},{x=2, y=2},{x=3, y=3}]
Thanks in advance.
If I understood the question this should help:
>>> x_values = [1, 2, 3]
>>> y_values = [1, 2, 3]
>>> points = [{"x":i, "y":j} for i, j in zip(x_values, y_values)]
>>> points
[{'y': 1, 'x': 1}, {'y': 2, 'x': 2}, {'y': 3, 'x': 3}]
There could be a more Pythonic way to do this, but one straight forward approach could be:
x_values = [1,2,3]
y_values = [1,2,3]
points = []
i = 0
while i < len(x_values):
new_dict = {}
new_dict['y'] = y_values[i]
new_dict['x'] = x_values[i]
points.append(new_dict)
i += 1
This may at least get you going.

BNR book-Swift Ch 22, gold challenge-A solution in Swift 3.0

This is a Swift 3.0 version of a previously presented Swift 2.0 solution.
import Cocoa
func findAll<T: Equatable, C: Collection>(items: C, itemToFind: T) -> [C.Index]? where C.Iterator.Element == T {
guard items.contains(itemToFind) else {
return nil
}
var result = Array<C.Index>()
var index = items.startIndex
for item in items {
if item == itemToFind {
result.append(index)
}
index = items.index(after: index) // index = index.successor()
}
return result
}
print("\nList the Indicies within 'items' of where 'itemToFind' was found")
let Indexes = findAll([items: [5, 3, 7, 3, 9], itemToFind: 3) // result expected: [1, 3]
let Indexes = findAll([items: ["c", "a", "b", "c", "a"], itemToFind: "b") // result expected: [1, 4]
let stringChars = ["Hello, playground!".characters]
let stringIndexes = findAll(items: stringChars, itemToFind: Character("l")) // result expected: [2, 3, 8]
The compiler doesn't help me, the only errors reported complain about "expected ',' separator missing in the 4 statements after the only print statement.
Can anyone point out where I've either written the routine incorrectly or miss-understood how to input the parameters in the call to the 'findAll' function?
let Indexes = findAll([items: [5, 3, 7, 3, 9], itemToFind: 3)
^ 🤷
This line has a stray square bracket at the location I've marked. Remove it.
let Indexes = findAll([items: ["c", "a", "b", "c", "a"], itemToFind: "b")
Same problem, same place. Also, I'm not sure why you expect this to return [1, 4] -- if you'd passed itemToFind: "c" I'd agree, but "b" only appears once, at position [2].
(Also, you'll need to name the variable something other than Indexes -- that name is already in use from the previous line.)
let stringChars = ["Hello, playground!".characters]
Wouldn't you know it, this line doesn't need either of its square brackets! characters is already a CharacterView (which behaves enough like an array for findAll() to work); it doesn't need to be wrapped into another level of array.
This works in Swift 3.0
import Cocoa
func findAll<T: Equatable, C: Collection>(items: C, itemToFind: T) -> [C.Index]? where C.Iterator.Element == T {
guard items.contains(itemToFind) else {
return nil
}
var result = Array<C.Index>()
var index = items.startIndex
for item in items {
if item == itemToFind {
result.append(index)
}
index = items.index(after: index) // index = index.successor()
}
return result
// Another approach:
// return items.indices.filter { items[$0] == itemToFind }
}
print("\nList the Indicies within 'items' of where 'itemToFind' was found")
let Indexes1 = findAll(items: [5, 3, 7, 3, 9], itemToFind: 3) // result: [1, 3]
print(Indexes1!)
let Indexes2 = findAll(items: ["c", "a", "b", "c", "a"], itemToFind: "c") // result: [0, 3]
print(Indexes2!)
func offsetValue(input: String.CharacterView, position: String.CharacterView.Index) -> Int {
let offset = input.distance(from: input.startIndex, to: position)
return offset
}
var i = 0
let stringChars = "Hello, playground!".characters
let stringIndexes = findAll(items: stringChars, itemToFind: Character("l")) // result: [2, 3, 8]
print("[", terminator: "")
for stringIndex in stringIndexes! {
let stringIndexInt = offsetValue(input:stringChars, position: stringIndex)
print("\(stringIndexInt)", terminator: "")
i += 1
if i < (stringIndexes?.count)! {
print(", ", terminator: "")
}
}
print("]")

why the list is value is 'None' when same variable is assigned to it? Please check the code given

l = [5,4,3,2,1]
l = l.sort()
print(l) << this prints "None" << why is this happening
l = [5,4,3,2,1]
k = l.sort()
print(k) << this prints "None"
print(l) << This prints [1, 2, 3, 4, 5]
May I know what's the exact behaviour?
Its because of that sort method, sort the list in-place and when you assign it to any variable it would be None.
If you want to assign the result of your sort you can use sorted instead of sort.
>>> l = [5, 4, 3, 2, 1]
>>> l = sorted(l)
>>> l
[1, 2, 3, 4, 5]

Is there a Groovy equivalent to Ruby's #map?

I realize there is support for #each
Book.findAll().each(){ book->
println ">>> ${book}"
}
and there's even support for #inject
def sentence = m.inject('Message: ') { s, k, v ->
s += "${k == 'likes' ? 'loves' : k} $v "
}
Is there support for #map for Groovy out of the box (without any special libraries like Functional Java)?
def list = [1,2,3,4].map{ num->
num + 1
}
assert list == [2,3,4,5]
You want collect.
groovy:000> [1,2,3,4].collect { num -> num + 1 }
===> [2, 3, 4, 5]
I hope that helps.
You can use collect, as in
[1, 2, 3, 4].collect { it + 1 }
For the case where you're calling a method directly on each object in the collection there's a shorter syntax using the spread-dot operator:
[1, 2, 3, 4]*.plus 1
(using a method Groovy adds to java.lang.Integer to implement the + operator)
This operator works even if the list contains nulls:
groovy:000> [1, 2, 3, null, 4]*.plus 1
===> [2, 3, 4, null, 5]
where with collect you'd have to check:
[1, 2, 3, null, 4].collect { it?.plus 1 }