Lab 5: Python Lists, Trees

Q2: Riffle Shuffle

The familiar riffle shuffle of a deck of cards (or in our case, of a sequence of things) results in a new configuration of cards in which the top card is followed by the middle card, then by the second card, then the card after the middle, and so forth. Assuming the deck (sequence) contains an even number of cards, write a list comprehension that produces the shuffled sequence.

Hint: To write this as a single comprehension, you may find the expression k%2, which evaluates to 0 on even numbers and 1 on odd numbers, to be useful. Consider how you can use the 0 or 1 returned by k%2 to alternatively access the beginning and the middle of the list.

 分析:

我是直接根据样例二,找出规律对应的表达式,然后直接实现

def riffle(deck):
    """Produces a single, perfect riffle shuffle of DECK, consisting of
    DECK[0], DECK[M], DECK[1], DECK[M+1], ... where M is position of the
    second half of the deck.  Assume that len(DECK) is even.
    >>> riffle([3, 4, 5, 6])
    [3, 5, 4, 6]
    >>> riffle(range(20))
    [0, 10, 1, 11, 2, 12, 3, 13, 4, 14, 5, 15, 6, 16, 7, 17, 8, 18, 9, 19]
    """
    "*** YOUR CODE HERE ***"
    #return [] if len(deck)==0 else deck[0:len(deck)//2]+deck[len(deck)-1:len(deck)//2-1:-1] if len(deck)%2==0 else deck[0:len(deck)//2]+deck[len(deck)-1:len(deck)//2-1:-1]
    #return [] if len(deck)==0 else [deck[x] for x in range(0,len(deck)//2)]+[deck[x] for x in range(len(deck)-1,len(deck)//2-1,-1)]
    return [deck[(i%2)*len(deck)//2+i//2]for i in range(len(deck))]

相关推荐

  1. Lab 5: Python Lists, Trees

    2023-12-06 22:02:03       59 阅读
  2. 5G LAN

    2023-12-06 22:02:03       45 阅读
  3. CS144 Lab Checkpoint 5: down the stack (the network interface)

    2023-12-06 22:02:03       30 阅读
  4. XSS-<span style='color:red;'>Lab</span>

    XSS-Lab

    2023-12-06 22:02:03      47 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-06 22:02:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-06 22:02:03       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-06 22:02:03       87 阅读
  4. Python语言-面向对象

    2023-12-06 22:02:03       96 阅读

热门阅读

  1. 浅谈Elasticsearch安全和权限管理

    2023-12-06 22:02:03       47 阅读
  2. Ubuntu22.04 安装nvida-docker2和改路径

    2023-12-06 22:02:03       46 阅读
  3. ElasticSearch之cat indices API

    2023-12-06 22:02:03       54 阅读
  4. 【C++刷题】校招笔试编程题第一辑

    2023-12-06 22:02:03       46 阅读
  5. 洛谷P1269 信号放大器(树形数据)

    2023-12-06 22:02:03       42 阅读
  6. 前端中级开发:突破瓶颈,迈向更高峰

    2023-12-06 22:02:03       52 阅读
  7. Django rest froamwork-HyperlinkedModelSerializer

    2023-12-06 22:02:03       56 阅读
  8. 基于 HarmonyOS 的用户登录界面实现

    2023-12-06 22:02:03       71 阅读
  9. 26、Spring是如何解决Bean的循环依赖?

    2023-12-06 22:02:03       57 阅读