全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 python论坛
1352 5
2015-08-27
有python比较熟练的朋友帮忙看下这两道题吗?万分感激。。

Do both of these problems using at least one loop each and not using any special pre-existing functions that give you the answer with just one line of code.

1. Make a function to count the number of times a specified number is repeated in a list/array.  That means that if we have a number list

  numberList=[5, 12, 0, 7, 2, 5, 10, 9, 12, 5];

and we use the function call

  numRepeats(numberList, 5)

we get the output: 3  --- meaning 5 occurs three times in numberList.

2. Make a function that takes in a multi-dimensional array/list and returns the "diagonal" --- a list of the elements at the 1st row-and-1st column, 2nd row-and-2nd column, 3rd row-and-3rd column, etc. That means if we have a multi-dimensional array:

  multiArray = [[3, -4, 12, 5], [5, 2, 11, -5], [2, 2, 0, 5], [-5, -3, 2, 2]];

and we use the function call

  diagonal(multiArray)

we get the output [3, 2, 0, 2] .
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2015-8-28 16:29:41
def numRepeats(List,Element):
    return(len([x for x in List if x==Element]))

def diagonal(multiArray):
    return([multiArray[i][i] for i in range(len(multiArray))])
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2015-8-28 16:36:27
def numRepeat(numlist,num):
    return numlist.count(num)
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2015-8-28 16:38:29
def numberRepeat(numlist,num)
   return numlist.count(num)
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2015-8-28 18:50:49
第一题如楼上所言, 不难
第二题也不难 用numpy的包也很方便
import numpy as np

def diagonal(multiArray)
      matrix_data = np.array(multiArray)
     return np.diag(matrix_data)
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2015-8-31 11:51:31
def repeatCount(seq, num):
    store = []
    for i in range(len(seq)):
        if seq[i] == num:
            store.append(seq[i])
    return len(store)

def diagonal(arr):
    store = []
    for i in range(len(arr)):
        store.append(arr[i][i])
    return store


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群