text
stringlengths
5
121k
import pandas as pd import numpy as np import matplotlib.pyplot as plt dataset = pd.read_csv('Mall_Customers.csv') dataset.head() X = dataset.iloc[:,[3,4]].values from sklearn.cluster import KMeans wcss = [] for i in range(1,11): Kmeans = KMeans(n_clusters = i,init = 'k-means++',max_iter = 300,n_init = 10,ra...
'''Given the following list of strings: names = ['alice', 'bertrand', 'charlene'] produce the following lists: (1) a list of all upper case names; (2) a list of capitalized (first letter upper case);''' names = ['alice', 'bertrand', 'charlene'] upNames =[x.upper() for x in names] print(upNames) cNames = [x.title() f...
class Person(): def __init__(self,name,age): self.name=name self.age=age def out(self): print("Name:" +self.name + " Age:" +self.age) class child(Person): pass kid=child("Sumi","9") kid.out()
import sys import urllib2 url=raw_input("Enter Website:") url.rstrip() header=urllib2.urlopen(url).info() print(str(header))
'''The pop method on a list returns the "rightmost" item from a list and removes that item from the list:''' a = ['11','aaa','15','26',] b = a.pop() print(b) print(a)
def linear_function(m, b, x): y = m*x + b return y def calculate_error(m,b,point): x, y = point y_1 = linear_function(m,b,x) distance = abs(y-y_1) return distance ...
""" You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed. Return the number of consistent strings in the array words. Example 1: Input: allowed = "ab", words = ["ad","bd","aaab","baa","ba...
""" Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. Return the array in the form [x1,y1,x2,y2,...,xn,yn]. Example 1: Input: nums = [2,5,1,3,4,7], n = 3 Output: [2,3,5,4,1,7] Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]. Example 2:...
def encrypt(key, plaintext): key = key.replace(" ", "") plaintext = plaintext.replace(" ", "") alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] table = {} rows = (len(plaintext)//len(key))+...
import re def whole_field(x): x_trimmed = x.strip() if len(x_trimmed): return x_trimmed else: return None def first_word(x): x_trimmed = x.strip() if len(x_trimmed): return x_trimmed.split()[0] else: return None def first_two_words(x): x_trimmed = x.stri...
def rectangle(len,wid): print('There area is',len*wid) print('The perimenter is',len*2 + wid*2) rectangle(3,4)
from ggame import * from random import randint red = Color(0xFF0000,1) green = Color(0x00FF00,1) blue = Color(0x0000FF,1) black = Color(0x000000,1) blackOutline = LineStyle(1,black) def bubble(event): randnum = randint(1,4) if randnum == 1: circle = CircleAsset(randint(20,100), blackOutline, red)...
class Functions: @staticmethod def binary(a, b) -> list: """ Check whether values in respect to their positions match per two arrays. Parameters ---------- a : list or an array (numpy) First list/array holding variable. b : list or an array (...
import queue import threading class ThreadManager(object) : """Creates and manages threads and queues for bidirectional communications with the worker.""" def __init__(self, worker, collector=None, num_threads=4, killsig=None) : self.worker = worker self.collector = collector ...
def addString(lis, str): newList = [] for item in lis: newList.append(str+"{}".format(item)) return newList print(addString([1,2,3,4], 'emp'))
def checkDuplicate(dict, key): if key in dict: print("Oh! the there is duplicate key") else: print("No duplicate :) ") checkDuplicate({1: 10, 2: 20, 3: 30, 4: 40, 7: 50, 6: 60},5)
hi = lambda tup: sorted(tup) print(hi((2,3,1,4,5)))
string = "Hello Friends" upper = string.upper() lower = string.lower() print(string) print(upper) print(lower)
myd = {1: 10, 2: 20, 3: 30, 4: 40, 7: 50, 6: 60} for key, value in myd.items(): print(key,value)
def firsLas(string): return string[-1:]+string[1:-1]+string[0:1] pr = firsLas("Sumi") print(pr)
lis = [10, 20, 30, 40, 50, 60, 70] tup = tuple(lis) print(tup)
dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} dic1.update(dic2) dic1.update(dic3) print(dic1)
import turtle def day_of_birth(): """ this function first checks if the input is a master number (11,22,33) and returns it. if not a master number, it adds the integers of the day of birth and returns them. :param: None :return: sum of integers of the day of birth or master number (11, 22 ...
import heapq class Heap(object): """ Wraps heapq to provide a heap. The sorting is done by provided cost and then insertion order; the values are never compared. """ def __init__(self): self.heap = [] self.order = 0 def push(self, cost, value): x = (cost, self.order, v...
def nth_power(exponent): def pow_of(base): return pow(base,exponent) return pow_of square = nth_power(2) print(square(2)) print(square(3)) print(square(4)) print(square(5)) cube = nth_power(3) print(cube(2)) print(cube(3))
string = "this is a some words and it is my test" def highest_value(string): string = string.replace(" ", "").lower() dict = {} for item in range(len(string)): dict[string[item]] = dict.get(string[item], 0) + 1 x = sorted(dict, key=(lambda key: dict[key]), reverse=True) return x[0] print...
import unittest class Node(object): def __init__(self, val): self.value = val self.next = None class SList(object): def __init__(self): self.head = None def add_to_front(self, val): new_node = Node(val) current_head = self.head new_node.next = current_hea...
""" #1 movie = ["ウォーキング・デッド","アントラージュ", "ザ・ソプラノズ","ヴァンパイア・ダイアリーズ"] for show in movie: print(show) #2 for i in range(25,51): print(i) #3 movie = ["ウォーキング・デッド","アントラージュ", "ザ・ソプラノズ","ヴァンパイア・ダイアリーズ"] for i,show in enumerate(movie): print(i,":",show) #4 right = (7,10,1...
print("-------------------- ********** --------------------") print("User1 veillez saisir un nombre que user2 doit essaier de le trouver :") nbr_user1 = int(input()) print("User2 devine le nombre que user1 a saisie:") nbr_user2 = int(input()) score = 100 while(nbr_user1 != nbr_user2): if(nbr_user1 > nbr_user2): ...
from Student_Monsters_class import * class Spooky_Workshops(): def __init__(self, subject, staff, location, student_list): self.scary_subject = subject self.staff = staff self.list_students = student_list self.location = location def add_students(self, student): student...
while True: print("MY TO DO APP") print("==============") print("1. Add Task") print("2. View All Tasks") print("0. To Exit") option=int(input("Choose Option:")) if option==1: n1=input("Enter Task Name:") print("Task added") elif option==2: n1=input(...
fruits = ['apple', 'apricot', 'banana', 'chickoo', 'fig', 'guava', 'mango', 'orange'] while fruits: fruit = fruits.pop() if fruit == 'chickoo': print(fruit, "! Yuck... I will skip this one") continue print("I love", fruit) print("I am done!")
class doubleLinkNode: def __init__(self,key,val): self.val = val self.key = key self.prev = None self.next = None class LRUCache: def __init__(self, capacity: int): self.cache = {} self.head = doubleLinkNode(-1,-1) self.tail = doubleLinkNode(-1,-1) ...
class Solution: def minMutation(self, start: str, end: str, bank: List[str]) -> int: bank = set(bank) if end not in bank: return -1 front = {start} back = {end} step = 0 while front: next_front = set() for seq in front: ...
class Solution: def coinSelect(self,coins,path,amount,res): if amount==0: res['num'] = min(res['num'],len(path)) for c in coins: if amount - c >=0: self.coinSelect(coins,path+[c],amount-c,res) def coinChange(self, coins: List[int], amount: int) -> int: ...
while True: mainSentence = input("Enter your sentence here: ").lower() letters = "" isCapital = 0 for letter in mainSentence: if letter == " ": letters += " " elif isCapital == 0: compare = """1234567890-=[]\;',./`""" compare2 = """!@#$%^&*()_+{}|:"<>?~""" count = ...
import unittest from app.models import Article class TestArticle(unittest.TestCase): """ Test class to test the behaviour of the movie class """ self.new_article = Article("Bob","Random Title", "Short","random.com","random.jpg","12/12/12","None") def test_instance(self): """ Tests if ins...
import csv class CSVTest: """ Class that can be used to read, append and write csv files. """ @staticmethod def open_file(name, like): """ Method for opening a csv file """ return open(name, like) @staticmethod def get_dialect(file): """ Me...
""" Created on Wed Sep 23 08:29:52 2020 @author: karel """ feet,inch = eval(input("Enter your height (in feet, followed by inch separated by a comma):", )) print("Feet:", feet) print("Inches:", inch) float(feet) inch=inch/12 feet+=inch board = feet*30.48*88/100 print("Suggested board length:", board)
""" Created on Thu Jul 27 16:22:26 2017 @author: danielhaggerty """ answer = "Kafah tells lies" question = input("Does Kafah prefer Dan or crappy Persian TV: ") if 'Dan': print(answer) else: print(answer)
current_number = 1 while current_number <= 5: print(current_number) current_number += 1
def is_Rotation_my_method(A,B): len_A = len(A) result = {} for i in range(len_A): if A[i] not in result: result[A[i]] = 1 else: result[A[i]] += 1 if B[i] not in result: result [B[i]] = 1 else: result [B[i]] += 1 ...
def calculateLength(n): length = 0; while (n != 0): length = length + 1; n = n // 10; return length; def sumOfDigits(num): rem = sum = 0; len = calculateLength(num); while (num > 0): rem = num % 10; sum = sum + (rem ** len); num = num /...
print("Program running.....") x= int(input("type a number in the box ")) def conversion (unit): mililiters = unit * 29.57353 return mililiters print(conversion(x))
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression advertising = pd.DataFrame(pd.read_csv("Data/simple_lr_application/advertising.csv")) X = advertising['TV'].values y...
''' There are two ways to assign values to properties of a class. Assign values when defining the class. Assign values in the main code. ''' class Employee: def __init__(self, ID=None, salary=None, department=None): self.ID = ID self.salary = salary self.department = department ...
def sumofDigits(n): assert n >= 0 and int(n) == n, 'n must be positive and a whole number' if n == 0: return 0 else: return int(n%10) + sumofDigits(int(n//10)) print(sumofDigits(1111111111111111111))
import re text_to_search = ''' azertyuiop azertyuio azertyuHZZHZHA abc ''' sentence = 'Start a sentence and then bring it to an end' pattern = re.compile(r'https?://(www\.)?(\w+)(\.w+)') matches = pattern.finditer(text_to_search) subbed_urls = pattern.sub(r'\2\3',urls) with open('data.txt', 'r', e...
def solution(s): stack = list() for v in s: if stack and stack[-1] == v: stack.pop() else: stack.append(v) return not(stack)
import sys sys.stdin = open("input22.txt", "rt") n, target = map(int, input().split()) a = list(map(int, input().split())) a.sort() start = 0 end = n-1 while start <= end: mid = (start + end) // 2 if a[mid] == target: print(mid+1) break elif a[mid] > target: end = mid - 1 else:...
""" Created on Sun Dec 9 21:08:49 2018 @author: MMOHTASHIM """ import pandas as pd import matplotlib.pyplot as plt import quandl from statistics import mean import numpy as np from IPython import get_ipython api_key="fwwt3dyY_pF8LyZqpNsa" def get_data_company(company_name): df=quandl.get("EURONEXT/"+str(company_...
""" Created on Thu Jan 3 14:15:33 2019 @author: MMOHTASHIM """ from statistics import mean import numpy as np import matplotlib.pyplot as plt from matplotlib import style style.use("fivethirtyeight") xs=np.array([1,2,3,4,5,6],dtype=np.float64) ys=np.array([5,4,6,5,6,7],dtype=np.float64) def best_fit_slope_and_int...
import curses as crs """ Gets the character value (as an int) of a cell in the board; As blocks take up two curses-coordinate spaces, a cell is defined as such, and its identifying symbol will be in the righthand space; In theory, the cell will either be empty (". "), have an old block (two ACS_BLOCK chars), or have a...
print('lab5\nSofiia Hrynevych \nІПЗ-11 \nVariant 3') def binomial_coefficient(n, k): if n < k: return (print('It`s impossible to calculate a factorial value of negative number!')) if k == 0 or k == n: return 1 else: return binomial_coefficient(n - 1, k - 1) + binomial_coefficient(n - 1, k) while True: ...
import math print('Lab 2 \nSofiia Hrynevych \nIПЗ-11 \nTASK 1') def s(): print('\n') s() while True: a = float(input('Основа рівнобедренного трикутника = ')) b = float(input('Бічна сторона трикутника = ')) if (a > 0 and b > 0) and ((2 * b) > a): break s() print('It`s an impossible triangle! \nTry again!'...
import math print('Lab 2 \nSofiia Hrynevych \nIПЗ-11 \nVariant 3\n \nTASK 1') def s(): print('\n') s() r = float(input('R = ')) length = (2*math.pi)*r area = math.pi*(r**2) s() print('Length of the circle: {0:5.3f} \nArea of the circle: {1:5.3f}'.format(length,area)) s() print('TASK2') s() d2 = float(input('D =')...
x = 2 y = 5 if y > 8: y = y * 2 else: x = x * 2 print (x + y) lista = [] for i in range(9): if i != 3: for j in range (6): print (f'oi') lista.append(j) print (len(lista)) lista = [] listafinal = [] for n in range (1068,3628,2): lista.append(n)...
from Pet import Pet class Ninja: def __init__(self, first_name, last_name, treats, pet_food, pet): self.first_name=first_name self.last_name= last_name self.treats=treats self.pet_food=pet_food self.pet=pet def walk(self): self.pet.play() retu...
import math def FindHim(): for x in range(10): for y in range(10): if x != y: result = x * 1100 + y * 11 test = math.sqrt(result) if test.is_integer(): return result print (FindHim())
class MenuItem(object): def __init__(self, nameparam, typeparam, priceparam, descripparam): self.name = nameparam self.type = typeparam self.price = priceparam self.description = descripparam def getName(self): return self.name def getType(self): return...
def isEven(x): if x % 2 == 0: return True return False def isUpper(x): return x.isupper() def square(x): return x**2 def grade(x): if x >= 95: return "5.5" elif x >= 80: return "5" elif x >= 70: return "4" elif x >= 65: return "3" elif x >...
honapok= ["Január", "Február", "Március", "Április", "Május", "Június", "Július", "Augusztus", "Szeptember", "Október", "November", "December"] napok=[31,29,31,30,31,30,31,31,30,31,30,31] h=input("Hónap: ") n=input("Nap: ") def szamHiba(): try: int(n) return True except ValueError: ...
from math import floor from .tone import Tone class Square(Tone): """ This class continually produces a 50% duty cycle square wave centered in the cycle (meaning it starts at halfway through the low cycle and then shifts to high for 50% of the cycle and then back down to 0 at 75%. """ def __iter__(sel...
def flatten(inp): """ Recursive flatten function """ out=[] for i in inp: if type(i)==list: [out.append(j) for j in flatten(i)] else: out.append(i) return out; inp= [[1,'a',['cat'],2],[[[3]],'dog'],4,5] print("Output of Part...
import numpy as np import math import random from matplotlib import pyplot as plt from IPython.display import clear_output x = np.linspace(0, 100, 2000) y = (1/7)*np.sqrt(2500+np.power(x,2))+(1/2)*np.sqrt(2500+np.power((100-x),2)) def get_rand_num(min_val, max_val): range = max_val - min_val choice = random.u...
from typing import List class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: if not intervals: return 0 intervals.sort(key=lambda x: (x[1], x[0])) before = intervals[0] res = 0 for i in range(1, len(intervals)): if inte...
from sys import argv class InvaderRecognizer: def __init__(self, accuracy: float): self.accuracy = accuracy @staticmethod def read_file(filename: str) -> list: try: with open(filename, 'r') as file: return [list(line.strip()) for line in file] except F...
class TinyUrl: def __init__(self): self.long_short = {} self.short_long = {} self.char_dict = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" self.tot = 0 def longToShort(self, url): if url not in self.long_short: tiny = ""...
class Employee: noOfLeaves = 8 var = 8 def __init__(self,name,role,salary): self.name = name self.role = role self.salary = salary def printDetailsofEmp(self): return f'Hey your name is {self.name} and your role is {self.role} and your salary is {self.salary}...
from parts import part class CarRepair: def __init__(self): self.part = input("What part do you need?: ") self.part = self.part.capitalize() self.cost = part.get(self.part) self.labor = 1.75 def parts_cost(self): if self.part in part: print(f"The {se...
personal_info={"Name": "Hammad Ahmed","Contact No.": "0304-********", "Email":"abc@gmail.com"} print (personal_info) personal_info["age"]=int(input("Enter your age:")) print (personal_info)
"""rot13v1 = Convert command-line input to ROT13 format""" import sys import string CHAR_MAP = dict(list(zip(string.ascii_lowercase, string.ascii_lowercase[13:36]+string.ascii_lowercase[0:13]))) def rot13_letter(letter): do_upper = False if letter.isupper(): do_upper = True letter = lett...
""" Python3: Extract text from pdf file and copy into txt file """ import PyPDF2 pdf_pages = [] pdf_text = [] pages = [int(i) for i in input('Enter page numbers to split text for: ').split(',')] in_pdf = open(r'path/to/input.pdf', 'rb') pdf_reader = PyPDF2.PdfFileReader(in_pdf) for page in pages: pdf_pages...
""" SimpleCalc: Four-Function Calculator """ def Add(x,y): print('Sum = ',x+y) def Sub(x,y): print('Difference = ',x-y) def Mul(x,y): print('Product ',x*y) def Div(x,y): print('Quotient = ',x/y) legalTup = (1,2,3,4) flag = 0 restart = 1 print('This Is A Simple Calculator') while restart: print('=...
class Resistor(object): def __init__(self, ohms): self.ohms = ohms self.voltage = 0 self.current = 0 r1 = Resistor(50e3) r1.ohms = 10e3 r1.ohms += 5e3 class VoltageResistance(Resistor): def __init__(self, ohms): super().__init__(ohms) self._voltage = 0 @proper...
from decimal import Decimal, ROUND_UP rate = Decimal('1.45') seconds = Decimal('222') cost = rate * seconds / Decimal('60') print(cost) rounded = cost.quantize(Decimal('0.01'), rounding=ROUND_UP) print(rounded) rate = Decimal('0.05') seconds = Decimal('5') cost = rate * seconds / Decimal('60') print(cost) rounded...
import pandas as pd import menu.adminmenu as adminmenu import sql mycursor=sql.mycursor mydb=sql.mydb def cancel_flight(): df=pd.read_sql("SELECT CODE ,AIRLINE, F AS FROM_ , T AS TO_ ,DOF FROM FLIGHT",mydb) print(df) code = int(input("ENTER THE CODE OF FLIGHT YOU WANT TO DELETE : ")) code_lis...
import sys def does_file_exists(path): try: f = open(path, "r") f.close() return True except Exception as e: print(e) def read_from_file(path): f = open(path, "r") text = f.read() f.close() return text def get_dictionary(text): lines = text.splitlines()...
def fact(num): if num > 1: return num * fact(num - 1) else: return num print('enter number') a=int(input()) if(a==0): print('Not Possible') else: print(fact(a))
def check(str): a = 0 strv = 'aeiou' vowels = set(strv) for i in vowels: if i in set(str.lower()): a= a +1 if a==5: print('Accept') else: print('Not Accept') check(input())
import sys previous = None sum = 0 average = 0 count = 0 for line in sys.stdin: key, value = line.split( '\t' ) if key != previous: if previous is not None: average = sum / count print (previous + '\t' + str(average)) previous = key sum = 0 count = 0 ...
num=int(input("Enter Number to check prime or not:")) m=0 i=0 flag=0 m=int(num/2) for i in range(2,m+1): if(num%i==0) : print("Number is not prime") flag=1 break if(flag==0) : print("Number is prime") num=int(input("Enter Number to get Factotial:")) i...
""" CodeBreaker class """ from constants import * class CodeBreaker: def __init__(self): """ initializes an instance """ pass def makeGuess(self, guessCount): """ returns a validated guess """ guessesLeft = MAX_NUMBER_OF_GUESSES - guessCount print('\nNumber of guess...
def getWords(): lineNumber = 1 for line in tester.readlines(): startChar = 1 endChar = 1 tempToken = "" for char in line: endChar += 1 ...
def bar_stack_grapher(values,bar_labels,colors,barwidth=1,legend_values=None,x_label=None,y_label=None,title=None,x_lim=None,y_lim=None,plt_show=True): ''' input: values in a array that follow the format that each bar is one row\n bar_labels label what the bars and determine the number of bars\n colors ...
"""Checking an attribute's existence""" class ExampleClass: def __init__(self, val): if val % 2 != 0: self.a = 1 else: self.b = 1 example_object = ExampleClass(2) print(example_object.a) try: print(example_object.b) except AttributeError: pass class ExampleClass:...
""" Created on Wed Nov 25 17:30:27 2020 @author: dshlyapnikov """ import random class Card: def __init__(self, suit, val): """Create card of suit suit [str] and value val [int] 1-13 1 - Ace, 2 - 2, 3 - 3,..., 11 - Jack, 12 - Queen, 13 - King suit can be "clubs", "diamonds", "heart...
for index in range(10): if index == 5: print("Hello") break print(index) for index in range(10): if index == 5: continue print("Hello") print(index)
country_to_capital = {'United Kingdom': 'London', 'France': 'Paris', 'India': 'New Delhi', 'Sri Lanka': 'Colombo'} captital_to_country = {capital: country for country, capital in country_to_capital.items()} print(captital_to_country) words = ['hi', 'hello', 'welcome', 'hey'] d = {x[0]: x for x in words} print(d)
t = ('Norway', 4.953, 4) print(t[1]) print(len(t)) for item in t: print(item) print(t + (747, 'Bench')) print(t) print(t * 3) a = ((120, 567), (747, 950), (474, 748), (747,738)) print(a[3]) print(a[3][1]) h = (849) print(h, type(h)) h = (858,) print(h, type(h)) e = () ...
print(range(5)) for i in range(5): print(i) range(5, 10) print(list(range(5, 10))) print(list(range(0, 10, 2))) t = [6, 44, 532, 2232, 534536, 36443643] for i in enumerate(t): print(i) for i, v in enumerate(t): print("i={} v={}".format(i,v))
import __init__ as SphereDist def show_version(): print("SphereDist version 0.8.3 by katahiromz") def show_help(): print( "SphereDist --- Equal distance distribution of vertexes on a sphere or a hemisphere.\n" + "Usage: SphereDist [options] [output.tsv]\n" + "Options:\n" + ...
""" This module will be used for creating image """ from PIL import Image from randcolor import randomColor def imageCreator(): a = randomColor() b = randomColor() c = randomColor() d = randomColor() e = randomColor() img = Image.open("image/SZE3.png") pixels = img.load() for i in ...
''' created on 06 April 2019 @author: Gergely ''' import math def distance(point_1=(0, 0), point_2=(0, 0)): """Returns the distance between two points""" return math.sqrt((point_1[0] - point_2[0]) ** 2 + (point_1[1] - point_2[1]) ** 2)
"chandomin rooze separi shode az saal" d = int(input('rooz: ')) m = int(input('mah: ')) y = int(input('sal: ')) days=[31,28,31,30,31,30,31,31,31,30,31,30] days_passed = 0 if y%400 == 0 or (y%4 == 0 and y%100 != 0): days[1] = 29 for months in days[:m-1]: days_passed += months days_passed += d prin...
""" Created on Wed Jan 22 07:35:11 2020 @author: morte """ class A: __b=None def __init__(self, unObjetoB): self.__b=unObjetoB def __del__(self): print('Chau objeto A') class B: __a=None def __init__(self): self.__a=A(self) def __del__(self): p...
import argparse, os, sys import numpy as np from part1 import find_invalid_number, load_data def find_encryption_weakness(input_filename, preamble_size): fail_number = find_invalid_number(input_filename, preamble_size) if fail_number is not None: data = load_data(input_filename) for i in range(len(data)...
import FileContentParser import TextProcessorAndTokenizer from collections import Counter def get_word_count(filename): text = FileContentParser.parse(filename) keywords = TextProcessorAndTokenizer.get_keywords(text) return Counter(keywords)
def remove_item(list_item,to_remove): new=[] for i in list_item: if to_remove not in list_item: return "This item is not in list" elif i != to_remove: new.append(i) return new print(remove_item([1,2,34,7,5],7))
def findfirstSetbit(num): pos = 1 for i in range(32): if not (num & (1 << i)): pos += 1 else: break if pos > 32: return 0 else: return pos kases = int(input()) for kase in range(kases): num = int(input()) print(findfirstSetbit(n...