text
stringlengths
5
121k
x = [1, 2, 3] y = list(x) print(x, y) if x is y: print("equal value and identity") elif x == y: print("equal value but unqual identity") else: print("unequal")
while True: try: if int(input("Please enter an integer. \n")) % 2 == 0: print("even") break else: print("odd") break except: continue
""" 整数反转 """ class Solution: """ @param number: A 3-digit number. @return: Reversed number. """ def reverseInteger(self, number): g = number % 10 s = int(number / 10 % 10) b = int(number / 100) return int(str(g) + str(s) + str(b)) if __name__ == '__main__'...
print ("Please enter the following: ") adjective = input("adjective: ") animal = input("animal: ") verb1 = input("verb: ") exclamation = input("exclamation: ") verb2 = input("verb : ") verb3 = input("verb: ") print () print ("Your story is: ") print () print (f"The other day, I was really in trouble. It all s...
ccc = dict() ccc['csev'] = 1 ccc['cwen'] = 1 print(ccc) ccc['cwen'] = ccc['cwen'] + 1 print(ccc)
x=42 if x > 1: print('More than one') if x < 100: print('Less than 100') print('all done')
import cv2 import numpy as np image = cv2.imread('../images/sudoku.jpg') gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) canny = cv2.Canny(gray,100,170,apertureSize=3) lines = cv2.HoughLines(canny,1,np.pi/180,240) for rho,theta in lines[0]: a = np.cos(theta) b= np.sin(theta) x0 = a*rho y0 ...
""" Created on Mon Aug 17 23:29:48 2020 @author: rahul """ class Node: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.size = 0 self.head = None def __repr__(self): arr = [] node = self.head whi...
""" Created on Wed Sep 23 19:34:01 2020 @author: rahul """ stack=[] def add(item): if stack: stack.append((item,min(item,stack[-1][1]))) else: stack.append((item,item)) def pop(): return stack.pop()[0] def minimum(): return stack[-1][1]
import json import random import string import pyperclip accounts = "accounts.json" def login(username, password): """ Log in a new user """ global accounts accounts = list_accounts() for account in accounts: if account['account'] == username and account['password'] == password: r...
import collections class TrieNode(object): def __init__(self): self.children = collections.defaultdict(TrieNode) self.is_word = False class Trie(object): def __init__(self): self.root = TrieNode() def insert(self, word: str) -> None: node = self.root for c...
from threading import Condition class FizzBuzz: def __init__(self, n: int): self.n = n self.work = Condition() def fizz(self, printFizz: 'Callable[[], None]') -> None: for i in range(self.n): if i % 3 == 0 and i % 5 != 0: printFizz() sel...
from typing import List, Set import pprint class NQueensSolver(object): def __init__(self, n: int): self.n = n def get_all_solutions(self): self.rows = [0] * self.n self.cols = [0] * self.n self.diags = [0] * (2 * self.n + 1) self.antidiags = [0] * (2 * self.n +...
from heapq import heappop, heappush def compute_hindex(citations): q = [] hindices = [] hi = 0 for cit in citations: while q and q[0] <= hi: heappop(q) if cit > hi: heappush(q, cit) if len(q) > hi: hi += 1 hindices.append(hi) return hindices def main(): tcs = int(input()) for case in range(1, ...
class Solution: def reverse(self, x: int) -> int: if x >= pow(-2, 31) and x <= (pow(2,31) - 1): rev=0 orig=x if orig < 0: x=x+(2*(-x)) while x > 0: rem=x%10 rev=rev*10+rem x=int(x/10) ...
''' 全探索 ''' def check(n, target, i, sum): if i == n: return sum == target if check(n, target, i + 1, sum + A[i]): return True if check(n, target, i + 1, sum): return True return False n = int(input()) A = list(map(int, input().split())) m...
import tkinter as tk class ISECredentials: """ Class responsible for setting user credentials to Cisco ISE """ __root = None __ip = None __user = None __pwd = None __ip_val = None __user_val = None __pwd_val = None @staticmethod def prompt_credentials(): """ Method to ...
nums=[10,9,8,7,6,5] nums[0]=nums[1]-5 if 4 in nums: print(nums[3]) else: print(nums[4]) nums=[1,2,3] print(not 4 in nums) print(4 not in nums) print(not 3 in nums) print(3 not in nums)
from datetime import datetime import time from os import system import RPi.GPIO as GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(3, GPIO.OUT) GPIO.setup(2, GPIO.IN) estadoAnterior = 0 while True: tiempo = datetime.now() if GPIO.input(2) and estadoAnterior == 0: GPIO.output(3, Fals...
print(4>5) print(1<0)
def draw_circle(x, y, r): import turtle turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.circle(r) turtle.penup() def draw_rectangle(x, y, width, height): import turtle turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.forward...
import urllib from urllib.request import urlopen def calc_level(ASL, ASW): level = (0.39 * ASL) + (11.8 * ASW) - 15.59 return level def get_ASL(word_list): sent_count = len(word_list) word_count = 0 for sent in word_list: word_count += len(sent) ASL = word_count / sent_count return ASL, wo...
from cs50 import SQL import itertools import math import networkx as nx db = SQL("sqlite:///blocking.db") def utility(combo): util = 0 for i in combo: member = db.execute("SELECT * from responses WHERE id = :id", id = i)[0] for j in combo: for k in range(1, 8): ...
def solve(bo): find = find_empty(bo) if not find: return True else: row, col = find for i in range(1, 10): if valid(bo, i, (row,col)): bo[row][col] = i if (solve(bo)): return True bo[row][col] = 0 return False def valid(bo, num, pos): row = pos[0] col = pos[1] for i in range(len(bo))...
mark = 56 """ 0 - 35 - F9 36 - 44 - P8 45 - 49 - P7 50 - 54 - C6 55 - 59 - C5 60 - 65 - C4 66 - 74 - C3 75 - 79 - D2 80 - 100 - D1 Grading system that assigns grade to students based on marks """ if mark <= 35: print("F9") elif mark <= 44: print("P8") elif mark <= 49: print("P7") elif...
""" Created on Thu Mar 12 15:11:06 2020 @author: krishnendu code: solve a set of linear eqaution using numpy.linalg.solve """ import numpy as np A=np.array([[1,0.67,0.33],[0.45,1,0.55],[0.67,0.33,1]]) b=np.array([2,2,2]) print(np.linalg.solve(A,b))
import random def escape_from_hell(bottom, top, tries): number_of_guesses = 0 tries_remaining = tries print ("\n>>>>>>>>>>>>>> ESCAPE FROM HELL <<<<<<<<<<<<<<\n") print ("OK human! My name is Beelzebub the King of the Hell.\nIf you wanna be free you have to guess the number that I\'m thinking of!...
def divider(user_num): try: return (10 / user_num) except ZeroDivisionError: return ('fail') def line_counter(file_name): try: f = open(file_name, 'r') length = len(f.readlines()) f.close() return length except IOError: return (0)...
from tkinter import * top = Tk() size = 300 canvas = Canvas(top, bg="#222", height=size, width=size) def line_drawer(x, y): return canvas.create_line(x, y, size/2, size/2, fill='coral') line_drawer(20, 40) line_drawer(130, 50) line_drawer(220, 100) canvas.pack() top.mainloop()
from tkinter import * top = Tk() size = 300 lines = 3 canvas = Canvas(top, bg="#222", height=size, width=size) def square_drawer(x, y): return canvas.create_rectangle(x, y, x+50, y+50, fill='coral') square_drawer(20, 40) square_drawer(130, 50) square_drawer(220, 100) canvas.pack() top.mainloop()
from tkinter import * top = Tk() x = 300 canvas = Canvas(top, bg="#333", height=x, width=x) canvas.create_line(0, 0, x, x, fill='light green') canvas.create_line(0, x, x, 0, fill='light green') canvas.pack() top.mainloop()
from tkinter import * import webcolors top = Tk() size = 300 canvas = Canvas(top, bg="#0d355a", height=size, width=size) def rainbow_rect(x, color): canvas.create_rectangle(size/2-x/2, size/2-x/2 , size/2+x/2, size/2+x/2, fill=color) rainbow_colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', ...
students = [ {'name': 'Rezso', 'age': 9.5, 'candies': 2}, {'name': 'Gerzson', 'age': 10, 'candies': 1}, {'name': 'Aurel', 'age': 7, 'candies': 3}, {'name': 'Zsombor', 'age': 12, 'candies': 5} ] def ill_find_you(inventory): limit = 10 candies_sum = 0 for x in inventory: ...
m1 = 124 m2 = 456 def is_even(x,y): if x % 2 == 0 and y % 2 == 0: return True else: return False print (is_even(m1,m2))
def recursive(n): if n == 1: return (n) else: return n + recursive(n-1) print (recursive(5))
import os fout = open('file contents.txt','w') line1 = "File name Size \n" fout.write(line1) files = os.listdir('H:\\backup\\docx') for file in files: location = os.path.join('H:\\backup\\docx\\',file) line = file +" "+ str(os.path.getsize(location)) +...
import matplotlib.pyplot as plt x=[2,4,6,8,10] x2=[1,3,5,7,9] y=[4,7,4,7,3] y2=[5,3,2,6,2] plt.bar(x,y,label="One",color='m') plt.bar(x2,y2,label="Two",color='g') plt.xlabel('bar number') plt.ylabel('bar height') plt.title('Bar Chart tutorial') plt.legend() plt.show()
def shippingCost(orderSubTotal): shippingCost = 2.99 if orderSubTotal >= 10: shippingCost = 0 return shippingCost def unitTest(): print("Shipping cost if subtotal < 10.00:\n", shippingCost(5.99)) print("Shipping cost if subtotal = 10.00:\n", shippingCost(10.00)) print("Shi...
from sklearn.feature_extraction.text import CountVectorizer import numpy as np import pandas as pd def df_to_numeric(train_df, test_df): count_vec = CountVectorizer(max_df=0.85,min_df=0.05) X_train = count_vec.fit_transform(train_df['text']).toarray() X_train = np.hstack((X_train, np.on...
import cv2 as cv def showimage(img): screen_res = 1280, 720 scale_width = screen_res[0] / img.shape[1] scale_height = screen_res[1] / img.shape[0] scale = min(scale_width, scale_height) window_width = int(img.shape[1] * scale) window_height = int(img.shape[0] * scale) cv.namedWindow('ima...
class Node: def __init__(self, val): self.val = val self.next = None class Queue: def __init__(self): self.front = self.rear = None def isEmpty(self): return not self.front def enQueue(self, val): newNode = Node(val) if self.isEmpty(): self....
from random import shuffle WIDTH = 1024 HEIGHT = 768 class Card: def __init__(self, suit, rank): self.suit = suit self.rank = rank def __str__(self): return f"{self.rank} of {self.suit}" def value(self): face = ['J','Q','K'] if self.rank in fa...
class Dict: def __init__(self): filepath = 'polimorfologik-2.1/polimorfologik-2.1.txt' self.dict = set() with open(filepath) as fp: line = fp.readline() while line: splitted = line.split(';') self.dict.add(splitted[1].lower()) line = fp.readline() def has_key(self, ...
even_numbers = [2,4,6,8,10] odd_numbers = [1,3,5,7,9] number01 = 4 number02 = 7 if number01 in even_numbers: print(str(number01) + " is an even number") else: print(str(number01) + " is an odd number") if number02 in odd_numbers: print(str(number02) + " is an odd number") else: print(str(number02) +...
def count(): fs = [] for i in range(1, 4): def f(): return i * i fs.append(f) return fs def counts(): def f(j): def g(): return j * j return g fs = [] for i in range(1, 4): fs.append(f(i)) return fs ...
def not_empty(s): return s and s.strip() def arr_start_2(): num = 2 while True: yield num num = num + 1 def is_primes(prime): return lambda x: x % prime > 0 def primes(): arr = arr_start_2() while True: prime = next(arr) yield prime arr = fi...
def LCP(str): new = "" prefix = str[0] for x in str: new = find(prefix, x) if new == "": print ("No LCP") quit() prefix = new return prefix def find(str1, str2): newstring = "" for i, j in zip(str1, str2): if i is j: newstr...
""" Title : day2_operators Subdomain : 30 days of code Domain : Python Author : Sai Ram Adidela Created : 18 April 2018 """ if __name__ == "__main__": meal_cost = float(input().strip()) tip_percent = int(input().strip()) tax_percent = int(input().strip()) tip = float(meal_cost*(tip_percent/1...
""" Title : Set Symmetric Difference Subdomain : HackerRank/Python/Challenges/sets Domain : Python Author : Sai Ram Adidela Created : 2 May 2018 """ if __name__ == '__main__': set1_n = int(input()) set1 = set(map(int, input().split())) set2_n = int(input()) set2 = set(map(int, inp...
""" Title : collections.Counter() Subdomain : HackerRank/Python/Challenges/Collections Domain : Python Author : Sai Ram Adidela Created : 15 May 2018 """ from collections import Counter no_of_shoes = int(input()) shoe_sizes = Counter(map(int, input().split())) no_of_customers = int(input()) t...
""" Title : Lists Subdomain : HackerRank/Python3/Challenges/Basic Data Types Domain : Python Author : Sai Ram Adidela Created : 23 April 2018 """ if __name__ == '__main__': N = int(input()) L = [] for i in range(0, N): tokens = input().split() if tokens[0] == 'insert': ...
""" Title : Company Logo Subdomain : HackerRank/Python/Challenges/Collections Domain : Python Author : Sai Ram Adidela Created : 22 May 2018 """ from collections import Counter s = sorted(input().strip()) s_counter = Counter(s).most_common() s_counter = sorted(s_counter, key=lambda x: (x[1] * -1...
""" The following script opens a csv file with bank data and returns the following results: 1) The total number of months included in the dataset 2) The net total amount of "Profit/Losses" over the entire period 3) The average of the changes in "Profit/Losses" over the entire period 4) The greatest increase in pr...
import string; import fileHandle; patterns = [('JJ', 'NN'), ('NN', 'NN'), ('JJ', 'NNS'), ('NN', 'NNS'), ('NN'), ('NN', 'NN', 'NN')]; def tagAcronym(tokens): keyPhrase = []; small = string.lowercase; i = 0; count = len(tokens); while i < count: j = 0; strlen ...
""" Write a programme to generate the lucky numbers from the range(n). These are generated starting with the sequence s=[1,2,...,n]. At the first pass, we remove every second element from the sequence, resulting in s2. At the second pass, we remove every third element from the sequence s2, resulting in s3, and we ...
import numpy as np def SieveOfAtkin(limit): """usage SieveOfAtkin(limit) This function returns a list of all primes below a given limit. It is an implimentation of the Sieve of Atkin. The primary logic is a reimplimentation of the example on Wikipedia. en.m.wikipedia/wiki/Sieve_of_Atkin""" sq...
''' Util functions to analyze Excel files for the initial phase of indexers' selection for MESINESP task. Author: alejandro.asensio@bsc.es Based on the original script made by: aitor.gonzalez@bsc.es ''' import re import os import xlrd from typing import List def read_excel_file(filename: str) -> List[list]: '''...
def main(): print("\t Items for Hire - by Shankar Ramesh Vasudev") MENU = "Menu: \n(L)ist all items\n(H)ire an item\n(R)eturn an item\n(A)dd new items to stock\n(Q)uit" items = load_item() print(MENU) choice = input(">>> ").upper() while choice != 'Q': if...
import sqlite3 conn = sqlite3.connect('northwind_small.sqlite3') curs = conn.cursor() print(curs.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;").fetchall()) """[('Côte de Blaye',), ('Thüringer Rostbratwurst',), ('Mishi Kobe Niku',), ("Sir Rodney's Marmalade",), ('Carnarvon Tigers'...
from Queue import PriorityQueue """ Entries are typically tuples of the form: (priority number, data). """ class minpriorityqueue(): def __init__(self): self.pq = PriorityQueue() def push(self, x): rank, key = x self.pq.put((rank, key)) def pop(self): rank, key = self...
list = [int(i) for i in input('Enter values: ').split()] list.sort() list.reverse() print(list)
num=int(input()) for i in range(1,num+1): if i%2: temp=1 else: temp=0 for j in range(1,num+1): print(temp,end="") if temp==0: temp=1 else: temp=0 print()
n=int(input()) data=[0 for i in range(n)] for i in range(n): val=int(input()) data.append(val) print(data)
import unittest def AND( v1, v2 ) : w1,w2,theta = 0.5,0.5,0.7 func = v1*w1+v2*w2 if func <= theta: return 0 elif func > theta: return 1 def OR( v1, v2 ) : w1,w2,theta = 0.5,0.5,0.2 func = v1 * w1 + v2 * w2 if func <= theta: return 0 elif func > theta: ...
def room1_1(): print("You can travel (N)orth.") direction = input("Direction: ") if direction == "n" or direction == "N": room1_2() else: print("Not a valid direction!") room1_1() def room1_2(): print("You can travel: (N)orth or (E)ast or (S)outh.") direction = input...
import tkinter from tkinter import Button class Gui: def __init__(self, master, game): self.master = master self.game = game master.title("OBSTRUCTION") self.start() def start(self): """ Our board consists of buttons. When we click on a button...
import math class Neuron: def __init__(self, weights, bias): self.bias = bias self.weights = weights self.sumInvoer = None def calculate_input(self, invoer: [float]): """Deze functie berekent de som van de inputs met we weights en telt daarbij de bias op""" self.sumInvo...
def hi(name): print('Hi ' + name + '!') people = ['Rakshith','silu','harvester','tracter','manchester'] for name in range(1,6): print(name)
def computepay(): hrs = input("Enter Hours:") rate = input("Enter rate:") h = float(hrs) r = float(rate) if h<41 : pay=h*r else : ot=h-40 pay=(h-ot)*r+ot*(1.5*r) return(pay) print(computepay())
from time import sleep import RPi.GPIO as GPIO greenLed = 18 yellowLed = 22 redLed = 25 pushNum = 4 GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(greenLed,GPIO.OUT) GPIO.setup(yellowLed,GPIO.OUT) GPIO.setup(redLed,GPIO.OUT) GPIO.setup(pushNum,GPIO.IN, pull_up_down=GPIO.PUD_UP) print("T...
def _sqrt(a): x1 = a x2 = a/2 while abs(x1-x2) > 0.00000001: x1 = x2 x2 = (x1+a/x1)/2 return x1 if __name__ == '__main__': print(int(_sqrt(25)))
""" 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。 要求不能创建任何新的结点,只能调整树中结点指针的指向。 """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def Convert(self, pRootOfTree): if pRootOfTree is None: return None leftNode ...
def setZeroes(matrix): n = len(matrix) if n == 0: return [] m = len(matrix[0]) for i, li in enumerate(matrix): for j in range(len(li)): if li[j] == 0: matrix[i] = [0 for _ in range(m)] for i in range(n): matrix[i][j] = 0 ...
""" 将像"I am a student."这样的字符串进行翻转,翻转后结果为:"student. a am I"。 思路:先转单词,再转句子。 """ def reverse(words): for i in range(len(words) >> 1): words[i], words[-i - 1] = words[-i - 1], words[i] return words def ReverseSentence(s): wordstart = 0 s = list(s) for i in range(len(s)): if s[i]...
""" 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。 保证base和exponent不同时为0 """ class Solution: def Power(self, base, exponent): if exponent == 0: return 1 ret = base if exponent > 0: for i in range(1, exponent): ret *= base ...
""" leetcode 438 给定一个字符串 s 和一个非空字符串 p, 找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。 输入: s: "cbaebabacd" p: "abc" 输出: [0, 6] 解释: 起始索引等于 0 的子串是 "cba", 它是 "abc" 的字母异位词。 起始索引等于 6 的子串是 "bac", 它是 "abc" 的字母异位词。 """ import collections def findAnagrams(s, p): pLen = len(p) sLen = len(s) if sLen < pLen or s == [] or p == [...
while True: number = input("Choose any number you want! ") number = int(number) if number == 2: print("PRIME!") elif number == 3: print("PRIME!") elif number == 5: print("PRIME!") elif number == 7: print("PRIME!") elif number == 11: print("PRIME!") ...
a = int(input("masukan nilai a: ")) b = int(input("masukan nilai b: ")) c = int(input("masukan nilai c: ")) maks = 0 if a > b: maks = a else: maks = b if c > maks: maks = c print ("terbesar:",maks)
""" Created on Wed Jul 6 10:24:01 2016 @author: student """ ''' hex_digit=input("Hex input:") print(chr(int("0x"+hex_digit,16))) ''' letter=input("Enter letter:") print(hex(int(ord(letter))))
class ShoppingCart: def __init__(self, employee_discount=None): self.employee_discount = employee_discount self.total=0 self.items=[] def add_item(self, name, price, quantity=1): q=0 while q <quantity : self.items.append({name : price}) ...
"""~google <search term> will return three results from the google search for <search term>""" import re import requests from random import shuffle from googleapiclient.discovery import build import logging my_api_key = "Your API Key(Link: https://console.developers.google.com/apis/dashboard)" my_cse_id = "Your Custo...
print("hello, Python"); if True: print("true") else: print("flase") item_one=1 item_two=2 item_three=3 total = item_one+\ item_two+\ item_three print(total) item_one="hello" item_two="," item_three="python" total = item_one+\ item_two+\ item_three print(total) days=["Mond...
from random import randint import io import os import random class EmailGenerator: def __init__(self, path_domains, path_names): self.path_domains = path_domains self.path_names = path_names self.get_names() self.get_domains() def get_domains(self): """Opens file doma...
number = 0 sum = 0 while number != "": sum = sum + int(number) number = input("Enter a number:") print(sum) mailing_list = [ ["Roary", "roary@moth.catchers"], ["Remus", "remus@kapers.dog"], ["Prince Thomas of Whitepaw", "hrh.thomas@royalty.wp"], ["Biscuit", "biscuit@whippies.park"], ["Rory...
import brick import pygame, sys from pygame.locals import* GREEN = (0, 102, 71) RED = (255, 0, 0) BLUE = (0, 0, 255) GOLD = (255, 209, 63) PURPLE = (255, 0, 255) SPACE = 5 HEIGHT = 20 x_number_bricks = 9 colors = [RED, BLUE, GOLD, PURPLE, GREEN] pygame.init() main_surface = pygame.display.set_mode((500, 250), ...
import os MENU = ''' -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- 1.-Agregar nueva moneda 2.-Borra una moneda 2.-Cambio de divisa 3.-Salida''' class modifi_coins(): """docstring for coin.""" def add_coin(coins): coins_clas = dict(**coins) print(coins_clas) prin...
import random def run(): number_foud = False rand_number = random.randint(0, 20) while not number_foud: number = int(input('Intenta un numero: ')) if number == rand_number: print('Felicidades encontraste el numero') number_foud = True elif number > rand_nu...
import os cliente,RUC,carro01,carro02,carro03,precio_del_carro01,precio_del_carro02,precio_del_carro03="",0,"","","",0.0,0.0,0.0 cliente=os.sys.argv[1] RUC=int(os.sys.argv[2]) carro01=os.sys.argv[3] carro02=os.sys.argv[4] carro03=os.sys.argv[5] precio_del_carro01=float(os.sys.argv[6]) precio_del_carro02=...
from collections import namedtuple Position = namedtuple('Position', 'Index_in_HT Data') class HashTable: """Hash table using chain method.""" def __init__(self, size): assert type(size) == int, "Must be type int" self.size = size self.table = [[] for _ in range(size)] def _functi...
from PIL import Image from PIL import ImageDraw import time from rgbmatrix import RGBMatrix, RGBMatrixOptions options = RGBMatrixOptions() options.rows = 64 options.cols = 64 options.chain_length = 1 options.parallel = 1 options.hardware_mapping = 'adafruit-hat' options.led_rgb_sequence = 'RBG' matrix = RGBM...
import math def palindrome_num(x): reverse = 0 temp = x if x<=0: return 0 else: try: while temp: reverse = reverse*10 + (temp%10) temp//=10 if x == reverse: return True else: return False except e: return e print(palindrome_num(11)) print(palindrome_num(2221)) p...
class ListNode: """docstring for ListNode. implementing a singly linked list class""" def __init__(self, data=0, next=None): self.data = data self.next = next def search_list(L, key): while L and L.data != key: L = L.next return L def insert_after(node, newnode): newnode.next = node.next no...
"""a binary search tree, in which for every node x and it's left and right nodes y and z, respectively. y <= x >= z""" class BinaryTreeNode: """docstring for BT Node""" def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right def preorder(root): if root:...
def generate_primes(n): primes = [] is_primes = [False, False] + [True]*(n-1) for p in range(2,n+1): if is_primes[p]: primes.append(p) for i in range(p,n+1,p): is_primes[i] = False return primes print(generate_primes(35))
import speech_recognition as sr r = sr.Recognizer() file = sr.AudioFile("output.wav") print("eeee") while(True): with file as source: r.adjust_for_ambient_noise(source) audio = r.record(source) result = r.recognize_google(audio,language='es') if "hola" in result.split(' '): b...
x=float(input('Enter number of hours...\n')) while True: try: type (x) != float print('Please enter a number') except: print ('Number of hours is', x) break
''' This script scrapes IMDB and outputs a CSV file with highest rated tv series. ''' import csv from pattern.web import URL, DOM TARGET_URL = "http://www.imdb.com/search/title?num_votes=5000,&sort=user_rating,desc&start=1&title_type=tv_series" BACKUP_HTML = 'tvseries.html' OUTPUT_CSV = 'tvseries.csv' rows = [] ...
from FSNode import FSNode class FSNode_File(FSNode): """ A file in the file system. Just contains text data """ def __init__(self, name, parent): FSNode.__init__(self, name, parent) self.data = "" def get_type(self): return "FSNODE_FILE" def write(self, offset, data): ...
def isCryptSolution(crypt, solution): word3len=len(crypt[2]) num1 = [] num2 = [] num3 = [] def wordgrab(crypt, solution): word_count=0 for word in crypt: word_count=word_count+1 word_letter(word,word_count, solution) def word_letter(w...
""" Use AI TextGen to generate a response in kind based on the given input. """ from aitextgen import aitextgen import random ai=aitextgen(model="minimaxir/reddit") def returngeneratedtext(inputtext,minsize=20, maxsize=50): return random.choice(ai.generate(n=1, prompt=inputtext, max_length=len(inputtext) + max...