Skip to content

Instantly share code, notes, and snippets.

@mizushou
Created September 20, 2019 07:22
Show Gist options
  • Save mizushou/9e9e3f9a4b39354eea7c6eb6cc8956f6 to your computer and use it in GitHub Desktop.
Save mizushou/9e9e3f9a4b39354eea7c6eb6cc8956f6 to your computer and use it in GitHub Desktop.
Python list関連
"""
CICCC WMAD LAB2
Basic python list problems -- no loops.
出展は'Coding Bat'
"""
# まず、ほとんどがワンライナーで書ける
# loopを使わずに、logicで書くことでTrue,Falseをわざわざ書く必要がない、ってことに気づかないと冗長な書き方になる
def first_last6(nums):
"""
Given a list of ints, return True if 6 appears as either the first or last element in the list.
The list will be length 1 or more.
"""
# ここも実はlistの最後の要素はnums[-1]だけで書ける
return nums[0] == 6 or nums[len(nums)-1] == 6
def same_first_last(nums):
"""
Given a list of ints, return True if the list is length 1 or more, and the first element
and the last element are equal.
"""
return len(nums) >= 1 and (nums[0] == nums[len(nums)-1])
def common_end(a, b):
"""
Given 2 lists of ints, a and b, return True if they have the same first element or they have the same last element.
Both lists will be length 1 or more.
"""
return a[0] == b[0] or a[len(a)-1] == b[len(b)-1]
def sum3(nums):
"""
Given a list of ints length 3, return the sum of all the elements.
"""
# listの要素の合計はsum関数で取れる。loopで書く必要はない
return sum(nums)
def rotate_left3(nums):
"""
Given a list of ints length 3, return a list with the elements "rotated left" so {1, 2, 3} yields {2, 3, 1}.
"""
return [nums[1], nums[2], nums[0]]
def reverse3(nums):
"""
Given a list of ints length 3, return a new list with the elements in reverse order,
so {1, 2, 3} becomes {3, 2, 1}.
"""
# sliceは:がないとただの要素取得になってしまうので:を忘れずに
return nums[::-1]
def max_ends3(nums):
"""
Given a list of ints length 3, figure out which is larger, the first or last element in the list,
and set all the other elements to be that value. Return the changed list.
"""
# ここもわざわざifとかで条件分岐で最大値を取得する必要はない。max関数で書けばワンライナーで書ける。
m = max(nums[0], nums[2])
# 今回はlistの長さが決まっているので、要素さえわかれば単純にその要素でlistを作るだけ
return [m, m, m]
def make_ends(nums):
"""
Given a list of ints, return a new list length 2 containing the first and last elements from the original list.
The original list will be length 1 or more.
"""
return [nums[0], nums[len(nums)-1]]
def has23(nums):
"""
Given an int list length 2, return True if it contains a 2 or a 3.
"""
# Pythonのinはfor-inだけでなく要素の有無判定のinもある
return 2 in nums or 3 in nums
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment