# Coding Bat: Python. List-1

All solutions were successfully tested on 16 April 2013.

first_last6:

```def first_last6(nums):
return nums == 6 or nums[-1] == 6
```

same_first_last:

```def same_first_last(nums):
return len(nums) >= 1 and nums == nums[-1]
```

make_pi:

```def make_pi():
return [3, 1, 4]
```

common_end:

```def common_end(a, b):
return a == b or a[-1] == b[-1]
```

sum3:

```def sum3(nums):
#return nums + nums + nums
return sum(nums)
```

Either way works. The version I’ve commented out is less elegant, though.

rotate_left3:

```def rotate_left3(nums):
return [nums, nums, nums]
```

reverse3:

```def reverse3(nums):
#return [nums, nums, nums]
return nums[::-1]
```

Again, the second version is more elegant or, as some phrase it, more “pythonic”.

max_end3:

```def max_end3(nums):
m = max(nums, nums)
return [m, m, m]
```

For matters of comparison, here is the solution from the website:

```def max_end3(nums):
big = max(nums, nums)
nums = big
nums = big
nums = big
return nums
```

It is less expressive and, frankly, a bit painful to look at. A much nicer way to assign “big” to three variables at once would be one of the two following ways:

```def max_end3(nums):
big = max(nums, nums)
#nums, nums, nums = big, big, big
nums, nums, nums = (big, ) * 3
return nums
```

sum2:

```def sum2(nums):
if len(nums) == 0:
return 0
if len(nums) == 1:
return nums
return nums + nums
```

middle_way:

```def middle_way(a, b):
return [a, b]
```

make_ends:

```def make_ends(nums):
return [nums, nums[-1]]
```

has23:

```def has23(nums):
return 2 in nums or 3 in nums
```

Do you remember what this looked like in Java?

## 9 thoughts on “Coding Bat: Python. List-1”

1. Hong Jeon

pythony solution to sum2:

def sum2(nums):
return sum(nums[:2])

takes care of all cases, no?

2. rosa

this guide is missing has23

1. Gregor Ulm Post author

You’re mistaken.

1. rosa

no you have has22 for list2 but not has23 for list1

1. Gregor Ulm Post author

It’s at the very end of this post.

3. Pszemo

sum2 cleaner solution:
def sum2(nums):
if len(nums) > 2:
return sum(nums[:2])
return sum(nums)

4. Gud

I know my code is a silly one – but why is it wrong for has23([4, 5]) (gives True???)
def has23(nums):
if nums or nums== 2 or 3:
return True
else:
return False

1. Gregor Ulm Post author

Look up how ‘or’ works. What is “bool(2 or 3)” in Python?

5. Abdul

make_pi(nums):
if nums == 3 and nums == 1 and nums == 4:
return True
else:
return False
make_pi([3,1,4])

This site uses Akismet to reduce spam. Learn how your comment data is processed.