|
12 | 12 |
|
13 | 13 | **Main Author's Solution: Python 2** |
14 | 14 | ``` |
15 | | -tp=(1,2,3,4,5,6,7,8,9,10) |
16 | | -tp1=tp[:5] |
17 | | -tp2=tp[5:] |
| 15 | +tp = (1,2,3,4,5,6,7,8,9,10) |
| 16 | +tp1 = tp[:5] |
| 17 | +tp2 = tp[5:] |
18 | 18 | print tp1 |
19 | 19 | print tp2 |
20 | 20 | ``` |
@@ -44,3 +44,41 @@ print(lst1) |
44 | 44 | print(lst2) |
45 | 45 | ``` |
46 | 46 | ------------------ |
| 47 | + |
| 48 | +# Question 39 |
| 49 | +### Level 1 |
| 50 | + |
| 51 | +**Question:** |
| 52 | + |
| 53 | +***Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10).*** |
| 54 | + |
| 55 | +---------------------- |
| 56 | +### Hints: Use "for" to iterate the tuple. Use tuple() to generate a tuple from a list. |
| 57 | + |
| 58 | +------------------- |
| 59 | +**My Solution: Python 3** |
| 60 | +``` |
| 61 | +tp = (1,2,3,4,5,6,7,8,9,10) |
| 62 | +li = list() |
| 63 | +for i in tp: |
| 64 | +if tp[i]%2 == 0: |
| 65 | +li.append(tp[i]) |
| 66 | +
|
| 67 | +tp2 = tuple(li) |
| 68 | +print tp2 |
| 69 | +``` |
| 70 | +---------------- |
| 71 | +**My Solution: Python 3** |
| 72 | +``` |
| 73 | +tpl = (1,2,3,4,5,6,7,8,9,10) |
| 74 | +tpl1 = tuple(i for i in tpl if i%2 == 0) |
| 75 | +print(tpl1) |
| 76 | +``` |
| 77 | +**OR** |
| 78 | +``` |
| 79 | +tpl = (1,2,3,4,5,6,7,8,9,10) |
| 80 | +tpl1 = tuple(filter(lambda x : x%2==0,tpl)) # Lambda function returns True if found even element. |
| 81 | + # Filter removes data for which function returns False |
| 82 | +print(tpl1) |
| 83 | +``` |
| 84 | +---------------- |
0 commit comments