[Solved] Count occurences of all items of a list in a tuple

[ad_1] Being NumPy tagged, here’s a NumPy solution – In [846]: import numpy as np In [847]: t = (1,5,2,3,4,5,6,7,3,2,2,4,3) In [848]: a = [1,2,3] In [849]: np.in1d(t,a).sum() Out[849]: 7 # Alternatively with np.count_nonzero for summing booleans In [850]: np.count_nonzero(np.in1d(t,a)) Out[850]: 7 Another NumPy one with np.bincount for the specific case of positive numbered elements … Read more

[Solved] Scraping Project Euler site with scrapy [closed]

[ad_1] I think I have found a simplest yet fitting solution (at least for my purpose), in respect to existent code written to scrape projecteuler: # -*- coding: utf-8 -*- import scrapy from eulerscraper.items import Problem from scrapy.loader import ItemLoader class EulerSpider(scrapy.Spider): name = “euler’ allowed_domains = [‘projecteuler.net’] start_urls = [“https://projecteuler.net/archives”] def parse(self, response): numpag … Read more

[Solved] how to write regular expression makes sure that there is no digits after

[ad_1] [*] Use a negative lookahead assertion: r’\b[a-z][*]{2}1(?!\d)’ The (?!…) part is the lookahead; it states that it cannot match at any location where a digit (\d) follows. Regex101 demo; note how only the second line is matched (blue). Python demo: >>> import re >>> pattern = re.compile(r’\b[a-z][*]{2}1(?!\d)’) >>> pattern.search(‘x**1’) <_sre.SRE_Match object at 0x10869f1d0> >>> … Read more

[Solved] How to flatten a nested dictionary? [duplicate]

[ad_1] You want to traverse the dictionary, building the current key and accumulating the flat dictionary. For example: def flatten(current, key, result): if isinstance(current, dict): for k in current: new_key = “{0}.{1}”.format(key, k) if len(key) > 0 else k flatten(current[k], new_key, result) else: result[key] = current return result result = flatten(my_dict, ”, {}) Using it: … Read more

[Solved] How to import a variable from another function and another class?

[ad_1] You probably want them to be stored in an instance variable (self….). And you probably want your start to be an __init__ method. Your corrected class could look like: class HostMethod: def start(self): self.my_API = requests.get(“http://ip-api.com/json/{0}”.format(socket.gethostbyname(sys.argv[2]))) self.load_json = json.loads(self.my_API.content) Then, you could do: class Run: def Method(self, choice): print “{0}Zip :\t{1}{2}\n”.decode(‘utf-8’).format(Basic_Green, White, choice.load_json[‘zip’]) a … Read more

[Solved] How to filter out only the number part (800000010627, 800000010040 and so on) from a list?

[ad_1] The easiest way: just cut the needed part from your bytes: only_numbers = [item[18:] for item in initial_list] This expression will create a new list named only_numbers with numbers extracted from original list items. Note that this method simply omits the first 17 symbols, so, if prefix part of your initial data will change … Read more

[Solved] Python xml help? Finish my program?

[ad_1] You create a root element using ET.Element(), adding the children you want to it. Then, you give that as the root to an ET.ElementTree, and call .write() on that, setting xml_declaration to True. import xml.etree.cElementTree as ET def record_time(root, time, speed, acc): attribs = {“t”: str(time), “speed”: str(speed), “acc”: str(acc)} ET.SubElement(root, “record”, attribs) root … Read more

[Solved] Unable to capture records name , price and rating and image in Requests Python [closed]

[ad_1] You have to scrape the adidas site and use regex: import requests import re endpoint = “https://www.adidas.com.au/continental-80-shoes/G27707.html” headers = { ‘User-Agent’: ‘Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36’ } response = requests.get(endpoint, headers = headers) data = response.text pricereg = r”(?<=\”price\”:)(.*)(?=,\”)” namereg = r”(?<=\”name\”:)(.*)(?=,\”co)” ratingreg= r”(?<=\”ratingValue\”:)(.*)(?=,\”reviewCou)” price = re.search(pricereg, data, re.MULTILINE).group() … Read more

[Solved] Addition function in Python is not working as expected

[ad_1] You don’t need the functions nor the sum or multiply variables, just put the operation in str.format(), and you were missing the last position. # def addition(num1,num2): # return num1+num2 # def multiplication(num1,num2): # return num1*num2 print(“1.addition”) print(“2.multiplication”) choice = int(input(“Enter Choice 1/2”)) num1 = float(input(“Enter First Number:”)) num2 = float(input(“Enter Second Number:”)) # … Read more

[Solved] python while loop iteration [closed]

[ad_1] Your while loop is never executing, because while absolute_avg > calculated_std: … is never satisfied. In fact absolute_avg == calculated_std. There seems to be no reason you cannot instantiate absolute_avg and calculated_std to be values such that they will succeed on the first pass of the while loop. Say: calculated_std = 0.0 absolute_avg = … Read more

[Solved] Python Write to Record to New Text File [closed]

[ad_1] Is there a way that I can append a unique character or number to the file name to coerce a new file? Yes, of course there is. Just iterate through the rows and build a different file name for each iteration. For example, import csv import pyodbc connStr = ( r”Driver={SQL Server};” r”Server=(local)\SQLEXPRESS;” r”Database=myDb;” … Read more