社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

DarrylG

DarrylG 最近创建的主题
DarrylG 最近回复了
5 年前
回复了 DarrylG 创建的主题 » Python-以合理的格式放置列表

您可以将customerList(作为字符串)直接传递给如下计算价格的函数。

[['potato', 'X', '8'], ['orange', 'X', '7'], ['rice', 'X', '13'], ['bread', 'X', '13']]

计算值的函数:

def calc_purchase_value(customerList_contents, price_list):
    " Compute purchase value "

    # convert customerList_contents to a list of list
    purchase_list = [x.split() for x in customerList_contents.split('\n') if x.strip()]

    # Iterate through the purchase_list looking up items in the price list
    # Each sublist will be of the form [item, 'X', cnt]
    return sum([price_list.get(item, 0) * int(cnt) for item, x, cnt in purchase_list])

使用自定义列表内容(将从文件中读取不同的字符串)

customerList_contents = """
potato X 8
orange X 7
rice X 13
bread X 13
"""

price_list = {"rice": 2.10,
"potato":4.21,
"orange":3.31,
"eggs":1.92,
"cheese":8.10,
"chicken":5.22}

print(calc_purchase_value(purchase_list, price_list))
#>> 84.15

完全解决方案

import glob
import os
import json

def readShopping():
    " Reads each customer shopping list, returning result as a geneerator "
    for file in glob.glob('./shoppinglists/*.txt'):
        with open(file,'r') as customerList:
            contents = customerList.read()
            # return file path and contents
            yield file, contents

def calc_purchase_value(customerList_contents, price_list):
    " Compute purchase value "

    # convert customerList_contents to a list of list
    purchase_list = [x.split() for x in customerList_contents.split('\n') if x.strip()]

    # Iterate through the purchase_list looking up items in the price list
    # Each sublist will be of the form [item, 'X', cnt]
    return sum([price_list.get(item, 0) * int(cnt) for item, x, cnt in purchase_list])

def get_prices():
    " Reads prices from JSON file "
    with open('./shoppinglists/pricelist.json') as json_file:
        return json.load(json_file)

# - Get prices from JSON file
price_list = get_prices()

for file, contents in readShopping():
    # file - path to customer file
    # contents - contents of customer file

    # Extract customer name from file path
    basename = os.path.basename(file)
    customer_name = os.path.splitext(basename)[0]

    # Total price: based upon shopping list and price list
    total_price = calc_purchase_value(contents, price_list)

    # Show results
    print('Customer {} total is: {:.2f}'.format(customer_name, total_price))

在上面,我有两个文本文件在文件夹购物列表“Mary.txt”和“James.txt”(你会说50或更多)。

Mary.txt的内容

orange X 3
rice X 2
potato X 3
eggs X 2

potato X 8
orange X 7
rice X 13
bread X 13

Customer james total is: 84.15
Customer mary total is: 30.60

使用函数搜索搜索(+/-)的二叉树。

预先计算从数组中每个索引到结尾的绝对值之和,允许在搜索的中间节点上终止。

这是因为,如果到目前为止的值之和+从当前索引到数组末尾的值之和<0,那么我们知道剩余数组中没有足够的值来克服当前的负累积值。

def findsums(a, n = -1, sumsofar = 0, signs = [], results = [], cumsum = []):

    """
    finds additions and subtraction of array element which are >= 0
        a - input array\n        
        n - highest index element of array we\'re using on the previous iteration
        sumsofar - sum using element up to index
        signs - signs (+/-) applied to these eleemnt
        results - solutions
        cumsum - cumulative sum of elements from index i to the end of array
    """
    if not cumsum:
        # Base case getting started
        #
        # Cumulative so of a in reverse order
        cumsum = cumsum_calc(a)

        # Use the first number as-is (i.e. no +/- sign)
        signs = [''] # first element is a
        sumsofar = a[0]
        n = 0

    # terminal case
    if n >= len(a)-1:
        if sumsofar >= 0:
            # terminal case (valid solution, so add)
                results.append(signs[:])
        else:
            # invalid solution
            pass # nothing to do 
    elif n == -1 or sumsofar + cumsum[n] >= 0:
        # Viable candidate so far
        # Try +/- alternatives\n        
        # Try + sign

        signs.append(' + ')
        findsums(a, n+1, sumsofar+a[n+1], signs, results, cumsum)
        signs.pop()

        # Try '-' sign
        signs.append(' - ')
        findsums(a, n+1, sumsofar-a[n+1], signs, results, cumsum)
        signs.pop()

    else:
        # Backtrack (sumsofar + cumsum[n] < 0):
        # No valid solution going forward\n        
        # So don\'t go any further with this sequence
        pass

    return results

def cumsum_calc(arr):
    " accum sum from next index forward in the array "
    # Adepted from https://www.geeksforgeeks.org/python-program-to-find-cumulative-sum-of-a-list/\n    
    # maximum sum of elements after i
    b = [abs(x) for x in arr]
    return [sum(b[i+1:]) for i in range(len(b)+1)]

def show_solutions(a, signs):
    " intertwines signs and array to show how they are added "
    # convert a to string, with parentheses around negative values

    converta = list(map(str, a))

    # place sign before each value in array a (converta)
    # function to generate list of sign, value pairs
    create_sign_value_pairs = lambda sign: list(zip(sign, converta))

    # Create sign/value pairs (i.e. [[('+', '(-1)'), ('+', '2')],...]
    sol_with_signs = list(map(create_sign_value_pairs, signs))

    # Convert each solution to a string
    solutions = list(map(lambda sol: ' '.join([''.join(s) for s in sol]), sol_with_signs))

    return "\t" + '\n\t'.join(solutions)

tests = [[2, 3], [-1, 2], [1], [-1], [-1, -2], [1, 2, 3, 4, -5]]

测试=[[2,3],[1,2],[1],[1],[1,-2],[1,2,3,4,-5]]

对于测试中的t: print(“对于数组{},解决方案是:”.format(t)) 打印(显示解决方案(t,s))

输出

For array [2, 3], solutions are:
    2  + 3
For array [-1, 2], solutions are:
    -1  + 2
For array [1], solutions are:
    1
For array [-1], solutions are:

For array [-1, -2], solutions are:
    -1  - -2
For array [1, 2, 3, 4, -5], solutions are:
    1  + 2  + 3  + 4  + -5
    1  + 2  + 3  + 4  - -5
    1  + 2  + 3  - 4  - -5
    1  + 2  - 3  + 4  - -5
    1  + 2  - 3  - 4  - -5
    1  - 2  + 3  + 4  + -5
    1  - 2  + 3  + 4  - -5
    1  - 2  + 3  - 4  - -5
    1  - 2  - 3  + 4  - -5

性能

使用Grzegorz Skibinski(组合法)

当前方法(使用回溯)

72.1 ms±2.34 ms/回路(7次运行的平均值±标准偏差,每个10回路)

使用回溯比测试所有组合快10倍

5 年前
回复了 DarrylG 创建的主题 » 有没有类似于matlab的python语法来选择行和列?[副本]

使用zip将列转换为行,然后选择第三个子列表(行)

lst = [
       [111, 111, 4523.123, 111, 111],
       [111, 111, 4526.15354, 111, 111],
       [111, 111, 4580.112, 111, 111],
       ]

第三栏:

list(zip(*lst))[2] 
5 年前
回复了 DarrylG 创建的主题 » 用Python中的字符串替换包含子字符串的字符串

使用正则表达式

import re

s = """
biography -> biography
biographical -> biography
biopic -> biography
bio-pic -> biography-pic
I watched a biographical movie -> I watched a biography movie
"""
x = re.sub(r'\b(bio\w*)', 'biography', s)
print(x)

输出

biography -> biography
biography -> biography
biography -> biography
biography-pic -> biography-pic
I watched a biography movie -> I watched a biography movie
6 年前
回复了 DarrylG 创建的主题 » Python 3.7中通过逐段计数单词的自定义数据结构
import re
from collections import defaultdict, Counter

def create_dict(text):
" Dictionary contains strings for each paragraph using paragraph ID as key"
  d = defaultdict(lambda: "")
  lines = text.splitlines()
  for line in lines:
    matchObj = re.match( r'<P ID=(\d+)>', line)
    if matchObj:
      dictName = matchObj.group(0)
      continue  #skip line containing paragraph ID
    elif re.match(r'</P>', line):
      continue  #skip line containing paragraph ending token
    d[dictName] += line.lower()
  return d

def document_frequency(d):
" frequency of words in document "
  c = Counter()
  for paragraph in d.values():
    words = re.findall(r'\w+', paragraph)
    c.update(words)
  return c

def paragraph_frequency(d):
"Frequency of words in paragraph "
  c = Counter()
  for sentences in d.values():
    words = re.findall(r'\w+', sentences)
    set_words = set(words)  # Set causes at most one occurrence 
                            # of word in paragraph
    c.update(set_words)
  return c

text = """<P ID=1>
I have always wanted to try like, multiple? Different rasteraunts. Not quite sure which kind, maybe burgers!
</P>

<P ID=2>
Nice! I love burgers. Cheeseburgers, too. Have you ever gone to a diner type restauraunt? I have always wanted to try every diner in the country.
</P>

<P ID=3>
I am not related to the rest of these paragraphs at all.
</P>"""

d = create_dict(text)
doc_freq = document_frequency(d)    # Number of times in document
para_freq = paragraph_frequency(d)  # Number of times in paragraphs
print("document:", doc_freq)
print("paragraph: ", para_freq)

结果

document: Counter({'i': 4, 'to': 4, 'have': 3, 'always': 2, 'wanted': 2, 'try': 2, 'not': 2,'burgers': 2, 'diner': 2, 'the': 2, 'like': 1, 'multiple': 1, 'different': 1, 'rasteraunts':1, 'quite': 1, 'sure': 1, 'which': 1, 'kind': 1, 'maybe': 1, 'nice': 1, 'love': 1, 'cheeseburgers': 1, 'too': 1, 'you': 1, 'ever': 1, 'gone': 1, 'a': 1, 'type': 1, 'restauraunt': 1, 'every': 1, 'in': 1, 'country': 1, 'am': 1, 'related': 1, 'rest': 1, 'of': 1, 'these': 1, 'paragraphs': 1, 'at': 1, 'all': 1})
paragraph:  Counter({'to': 3, 'i': 3, 'try': 2, 'have': 2, 'burgers': 2, 'wanted': 2, 'always': 2, 'not': 2, 'the': 2, 'which': 1, 'multiple': 1, 'quite': 1, 'rasteraunts': 1, 'kind': 1, 'like': 1, 'maybe': 1, 'sure': 1, 'different': 1, 'love': 1, 'too': 1, 'in': 1, 'restauraunt': 1, 'every': 1, 'nice': 1, 'cheeseburgers': 1, 'diner': 1, 'ever': 1, 'a': 1, 'type': 1, 'you': 1, 'country': 1, 'gone': 1, 'at': 1, 'related': 1, 'paragraphs': 1, 'rest': 1, 'of': 1,'am': 1, 'these': 1, 'all': 1})