Tuple:Data Processing and Visulisation with Python (Python Exercise 16)

Data Processing and Visulisation with Python

The N t h N^{th} Nth element in tuple

Write a Python function to return the N t h N^{th} Nth element of a given tuple. If N N N is out of the range of the tuple index, then return None. ( N N N is the index of the element hence 0 based.)

def eleInTuple(m,n):
    if n > len(m)-1 :
        return None
    else :
        return m[n]
eleInTuple((1,2,3,4,5,6,7), 4)

eleInTuple((1,2,3,4,5,6,7), 7)

在这里插入图片描述

Remove the N t h N^{th} Nth element in tuple

Write a Python function to remove the N t h N^{th} Nth element of a given tuple. ( N N N is the index of the element hence 0 based.)

Hint: Remember a tuple is immutable.

def removeEleInTuple(t,n):
    a = list(t)
    if n < len(a):
        y = tuple(a[:n]+a[n+1:])
        return y
    else:
        return t
removeEleInTuple((1,2,3,4,5,6,7), 4)

removeEleInTuple((1,2,3,4,5,6,7), 7)

在这里插入图片描述

Find the index of an item in a tuple

Write a Python function indexTuple(tup, itm) to find the first index of itm in a tuple tup.

Hint: Try tuple.index().

def indexTuple(t,c):
    if c in t:
        n = t.index(c)
        return n
    else:
        return None
indexTuple((1,2,3,4,5,3,2,1), 2)

indexTuple((1,2,3,4,5,3,2,1), 6)

t = tuple('abcdeabcdabc')
indexTuple(t, 'c')

t = tuple('abcdeabcdabc')
indexTuple(t, 'h')

在这里插入图片描述

Remove an item from tuple

Write a Python function removeTupleItem(tup, itm) to remove all the elements of itm in tuple tup.

Hint: Remember a tuple is immutable.

method 1

def removeTupleItem(t,c):
    if c in t:
        a = list(t)
        while c in a:
            a.remove(c)
        nt = tuple(a)
        return nt
    else:
        return t

method 2

def removeTupleItem(tup,itm):
    a = []
    for i in tup:
        if i != itm:
            a.append(i)
    b = tuple(a)
    return b

method 3

# Q4
def removeTupleItem(tup,itm):
    counts = tup.count(itm)
    
    for _ in range(counts):
        if itm in tup:
            ind = tup.index(itm)
            tup = removeEleInTuple(tup, ind)
    return tup
removeTupleItem((1,2,3,4,5,6,5,4,3,2,1,2,3,4,5,6), 3)

removeTupleItem((1,2,3,4,5,6,5,4,3,2,1,2,3,4,5,6), 7)

t = tuple('abcdeabcdabc')
removeTupleItem(t, 'c')

t = tuple('abcdeabcdabc')
removeTupleItem(t, 'h')

在这里插入图片描述

Sort dictionary keys

Write a Python function sortKey(dic, n) to take a dictionary of word frequency dic, sort the words in alphabet order and return the first n words with their corresponding frequencies in a list of tuples.

method 1

def sortKey(d,n):
    a = []
    for k,v in d.items():
        t = (k,v)
        a.append(t)
    a = sorted(a)
    return a[:n]

method 2

#Q5
def sortKey(dic, n):
    l1=sorted(list(dic.items()))
    return l1[:3]

method 3

def sortKey(dic,n):
    return sorted(dic.items())[:n]
sortKey({3:5,4:2,1:1,2:0}, 3)

def ranDict(keyLen, itemNum):
    import random
    d = {}
    for _ in range(itemNum):
        k = ''
        for _ in range(keyLen):
            c = chr(65+random.randrange(26))
            k += c
        d[k] = random.randrange(1000)
    return d

d = ranDict(2, 10)
print('Before sorting, the original dictionary: \n', d)
print('After sorting, the first 5 items are: \n', sortKey(d, 5))

d = ranDict(3, 20)
print('Before sorting, the original dictionary: \n', d)
print('After sorting, the first 8 items are: \n', sortKey(d, 8))

在这里插入图片描述

Sort dictionary values

Write a Python function sortValue(dic, n) to take a dictionary of word frequency dic, sort the frequencies in decending order and return the first n frequencies with their corresponding words in a list of tuples.

method 1

def sortValue(d,n):
    a = []
    for k,v in d.items():
        t = (v,k)
        a.append(t)
    a = sorted(a,reverse=True)
    return a[:n]

method 2

# 6
def sortValue(dic, n):
    temp = list()
    for k,v in dic.items():
        temp.append((v,k))
    return sorted(temp,reverse = True)[:n]
sortValue({3:5,4:2,1:1,2:0}, 3)

d = ranDict(2, 10)
print('Before sorting, the original dictionary: \n', d)
print('After sorting values in decending order, the first 5 items are: \n', sortValue(d, 5))

d = ranDict(3, 20)
print('Before sorting, the original dictionary: \n', d)
print('After sorting values in decending order, the first 8 items are: \n', sortValue(d, 8))

在这里插入图片描述

Two sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.

Example 1:

  • Input: nums = [2,7,11,15], target = 9
  • Output: (0,1)
  • Output: Because nums[0] + nums[1] == 9, we return (0,1).

Example 2:

  • Input: nums = [3,2,4], target = 6
  • Output: (1,2)

Example 3:

  • Input: nums = [3,3], target = 6
  • Output: (0,1)

Constraints:

  • 2 2 2 <= nums.length <= 1 0 5 10^5 105
  • - 1 0 9 10^9 109 <= nums[i] <= 1 0 9 10^9 109
  • - 1 0 9 10^9 109 <= target <= 1 0 9 10^9 109
  • Only one valid answer exists
  • Your function twoSum(nums, target) is expected to solve each problem in less than 2 seconds

sample

def twoSum(nums, target):
    """
    :type nums: list of integers
    :type target: int
    :rtype: 2-tuple of integers
    """
    #-----------------Code Section-----------------

    
    
    #--------------End of Code Section-------------

method 1

def twoSum(nums, target):   
    for i in range(len(nums)):
        for j in range(len(nums)):
            if j != i:
                if nums[i]+nums[j] == target:
                    out = (i,j)
    return out    

method 2

def twoSum(nums, target): 
    d = {}
    for i in range(len(nums)):
        if target - nums[i] in d :
            return i,d[target - nums[i]]
        d[nums[i]] = i 
twoSum([2,7,11,15], 9)

twoSum([3,2,4], 6)

import os
import pickle
import time

count = 1
while count<=3:
    print('Case', count,':')
    with open(f'testNums_{count}.pkl','rb') as f:
        nums = pickle.load(f)
    nums = nums.tolist()
    print('\tTotal number of nums:', len(nums))
    with open(f'testTargets_{count}.pkl', 'rb') as t:
        targets = pickle.load(t)
    print('\tTotal number of targets:', len(targets))
    print('\n\tCorrect\tAccepted\tTime used')
    for target in targets:
        startTime = time.time()                
        r = twoSum(nums, target)
        useTime = time.time() -  startTime
        isCorrect = nums[r[0]]+nums[r[1]]==target
        isAccepted = isCorrect and useTime<2
        print('\t', isCorrect, '\t ', isAccepted, '\t ', useTime)
    count += 1
    print('\n')

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值