text
stringlengths
5
121k
def product_finder(factors, limit): product_list = [] x = 0 if 0 in factors: print('Cannot have a zero as one of the factors.') else: while x < len(factors): if factors[x] > limit: print('Cannot have a factor larger than the limit value.') ...
import os from PIL import Image class ImgOperate(): """图像处理的几个例子""" def __init__(self): self.catIm = Image.open("zophie.png") def save_as(self): """图片另存为其他格式""" try: catIm = self.catIm print(catIm.size) width,height = catIm.size print("图片宽为:"+str(width)+",高为:"+str(height)) print("图片格式...
from os import system, name cnt=1 move_player=1 p1='' p2='' win_flag=0 l_row1 = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] def clear(): if name == 'nt': _ = system('cls') def print_board(): global win_flag clear() b1=' {} | {} | {} '.format(l_row1[0],l_row1[1],l_row1[2]) b3=' ...
import os import re def search(): folders = [] for folder in os.listdir(): if os.path.isdir(folder): dirpath, filename = os.path.split(folder) r = re.search("[a-zA-Z0-9]|[,—\[\]↑№!\"\'«»?.,;:-|/+*{}<>@#$%-^&()]", filename) if not r: folders.append(f...
''' This script is functioning as expected. Creates a list of values, elements of either 1 or 0 depending on specifications. ''' j = 1 k = 0 lic = 4 lec = 2 lsc = 7 ct = [] for i in range(0, lsc): if j!=0: for cell in range(0,lic): ct.append(1) j = 0 k = 1 elif k!=0: for cell in range(0,lec): ct...
from itertools import groupby string="aabnnn" print(groupby(string[1]))
def print_reverse(string_list): dict = {} for str in string_list: print(str) if dict[str]: print(str) print(''.join(reversed(str))) dict[''.join(reversed(str))] = 1 list="youarewthene" print_reverse(list)
list1 = (1, 2, 10, 34, 22) def addlist(listing): if len(listing) == 1: return listing[0] else: return listing[0] + addlist(listing[1:]) print(addlist(list1))
name = "Shreeti" newstr = "" def reversing(string): newstring = string[::-1] return newstring print(reversing("Shreeti"))
import hashlib g=int(input("Enter value of g: ")) p=int(input("Enter value of p: ")) a=int(input("Enter random number for alice: ")) b=int(input("Enter random number for bob: ")) A = (g**a) % p B = (g**b) % p print('g: ',g,' (a shared value), n: ',p, ' (a prime number)') print('\nAlice calculates:') print('a (Ali...
def apply_twice(f, x): """Return f(f(x)) >>> apply_twice(square, 2) 16 >>> from math import sqrt >>> apply_twice(sqrt, 16) 2.0 """ return f(f(x)) def square(x): return x * x result = apply_twice(square, 2) def make_adder(n): """Return a function that takes one argumen...
from itertools import groupby def check_adjacent(number_list): adjacent_groups = [len(list(g)) for k, g in groupby(number_list)] identical_adjacent_digits_counter = len( list(u for u in adjacent_groups if u > 1)) return identical_adjacent_digits_counter def check_increasing_numbers(number_list...
import threading import time def func(): print("I am running.........") time.sleep(4) print("I am done......") if __name__ == "__main__": t = threading.Timer(6, func) t.start() i = 0 while True: print("{0}***************".format(i)) time.sleep(3) i += 1
def kernelTrans(X, A, kTup): m, n = shape(X) K = mat(zeros((m, 1))) if kTup[0] == 'lin': K = X * A.T elif kTup[0] == 'rbf': for j in range(m): deltaRow = X[j, :] - A K[j] = deltaRow * deltaRow.T K = exp(K / (-1 * kTup[1] ** 2)) else: rai...
from tkinter import * win = Tk() sports = ["棒球", "篮球", "足球", "网球", "排球"] def showSelection(): choice = "您的选择是:" + sports[var.get()] label.config(text = choice) var = IntVar() radio1 = Radiobutton(win, text=sports[0], variable=var,value=0,command=showSelection) radio2 = Radiobutton(win, text=sports[1], v...
from tkinter import * win = Tk() frame = Frame(win, relief=RAISED, borderwidth=2, width=400, height=300) frame.pack(side=TOP, fill=BOTH, ipadx=5, ipady=5, expand=1) button1 = Button(frame, text="Button 1") button1.place(x=40, y=40, anchor=W, width=80, height=40) button2 = Button(frame, text="Button 2") button2....
import os import zipfile class DirMngmt(object): """1) Creates folders and unzip files containing zip extension 2) Read '.safe' file and process SAR data """ def __init__(self, main_dir, subfolder_1, subfolder_2, subfolder_3): """Note: Give 'subfolder_1' name and folder containing S...
import re vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U') def find_vowels(s, v): newstring = s for x in s: if x in v: newstring = newstring.replace(x, "") print("Optimized string is :", newstring) string = input("Please enter the string: ") find_vowels(...
def add(x, y): return x + y def substract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): if y == 0: print("Cannot devide by zero") return x / y print(add(4, 5))
class Chunk(object): def __init__(self, *words): self.words = [] for word in words: if len(word) == 0: continue self.words.append(word) def total_word_length(self): length = 0 for word in self.words: length += len(wo...
list = [3, 6, 8, 2, 34, 379, 98, 7, 355, 6, 73] list.sort() print(list) def find(sorted_list, num_to_find): for i in list: if i == num_to_find: return True print(i) return False print(find(2, 5))
print("\t\t\tSelamat datang di Mobiline") print("\t\t\tBelajar bisa,Bisa belajar,Saya bisa") a = input("\nSiapakah nama Anda? :") print("Nama Anda adalah",a) b = int(input("Berapa usia Anda? :")) print("Usia Anda adalah",b,"tahun") if b < 21 : print("\nMaaf Anda terlalu muda untuk masuk ke sini") input("Sila...
from PIL import Image name = input("File name: ") red_tint = int(input("Red tint: ")) green_tint = int(input("Green tint: ")) blue_tint = int(input("Blue tint: ")) img = Image.open(name) red, green, blue = img.split() for y in range(img.height): for x in range(img.width): orginal_value_red =...
input_text = input("Line: ") for letter in reversed(input_text): print(letter, end='')
input_words = [] input_word = input("Word: ") while input_word != '': input_words.append(input_word) input_word = input("Word: ") print("You know {} unique word(s)!".format(len(set(input_words))))
number = int(input("Enter a number: ")) anotherOne = int(input("Enter another number: ")) if number > anotherOne: print("{0} is greater than {1}.".format(number, anotherOne)) else: print("{0} is less than or equal to {1}.".format(number, anotherOne))
guess = input('Guess: ') guesses = set() while guess != "": if guess not in guesses: print("Hit {}".format(guess)) guesses.add(guess) else: print("You've chosen that square already") guess = input('Guess: ')
word = input("What did you say? ") print("{0}".format(word)) print("{0} {0}".format(word)) print("{0} {0} {0}".format(word))
num1 = int(input("Number 1: ")) num2 = int(input("Number 2: ")) print(num1, "plus", num2, "is", (num1+num2)) print(num1, "times", num2, "is", (num1*num2))
input_steps = int(input("How many steps? ")) step = 1 print("__") while step < input_steps: print(" "*2*step + "|_") step += 1 print("_"*2*step + "|")
""" This script scrapes IMDB and outputs a CSV file with highest rated movies. """ import csv from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup TARGET_URL = "https://www.imdb.com/search/title?title_type=feature&release_date=2008-0...
def add_numbers(x,y): """add x and y""" return x + y def subtract_numbers(x,y): """substract y from x""" return x - y
""" Given a String of length S, reverse the whole string without reversing the individual words in it. Words are separated by dots. """ def reverseWords(s): l = list(s.split('.')) l = reversed(l) return '.'.join(l) if __name__ == "__main__": t = int(input()) for i in range(t): string = str(i...
""" Given two strings a and b. The task is to find if a string 'a' can be obtained by rotating another string 'b' by 2 places. """ def areSame(a, b): x = a[2:]+a[:2] y = a[-2]+a[:-2] print(x, y) if b == x or b == y: return 1 else: return 0 if __name__ == "__main__": t = int(inpu...
""" Given an string in roman no format (s) your task is to convert it to integer .Given an string in roman no format (s) your task is to convert it to integer . """ def RomantoInt(s): romans = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000} value = romans[s[-1]] for i in range(len(s) - 1): if ...
import numpy as np mat = [] def isPossible(y, x, n): global mat for i in range(0,9): if mat[y][i] == n: return False for i in range (0,9): if mat[i][x] == n: return False y0, x0 = (y//3) * 3, (x//3) * 3 for j in range(y0, y0...
def second_highest(students): if len(students) < 2: print("Need at least 2 students!") else: sorted_score = sorted([score[1] for score in students], reverse = True) second_score = sorted_score[1] for student in students: if student[1] == second_score: ...
import os import csv csvpath = os.path.join('budget_data.csv') with open(csvpath, newline="") as budget: csvreader = csv.reader(budget, delimiter=",") budget.readline() total = 0 rows = 0 MaxV = 0 MaxD = "" MinV = 0 MinD = "" change = 0 Taverage = 0 val1 = 0...
import unittest from utils import create_board_from_str from colors import Color from piece import Piece class PieceTestCase(unittest.TestCase): def setUp(self): self.white_piece = Piece(Color.white, (0,0), None) self.black_piece = Piece(Color.black, (0,0), None) def test_piece_as_str(self):...
import pandas path = 'fruits.csv' dataframe = pandas.read_csv(filepath_or_buffer=path, sep=',', skip_blank_lines=True) print(dataframe.head(2)) print("****************") print(dataframe.tail(1)) print("****************") print(dataframe)
import numpy as np from sklearn.linear_model import LogisticRegression, LogisticRegressionCV from sklearn import datasets from sklearn.preprocessing import StandardScaler iris = datasets.load_iris() features = iris.data[:100, :] target = iris.target[:100] scaler = StandardScaler() features_standardized = scaler.fi...
''' Polynomial Class ''' from operator import add class Polynomial(object): coeffs = [] def __init__(self, coeffs): """ Constructor to form a polynomial """ self.coeffs = coeffs def order(self): """ Method to return order of polynomial """ ...
'''Pseudocode: The program is designed to solve qudratics. It finds it's zeros and vertex. It does this by asking the user for the 'a', 'b', and 'c' of the quadratic. With these pieces of information, the program plugs in the variables into the quadratic formula and the formula to solve for the vertex. It then o...
""" Stack data structure implementation based on linked lists """ class _Node: """ Simple node used for representing values inside the stack. """ def __init__(self, value): self.value = value self.next = None class Stack: """ Stack data structure. """ def _...
class FruitInfo: __fruit_name_list = ["Apple", "Guava", "Orange", "Grape", "Sweet Lime"] __fruit_price_list = [200, 80, 70, 110, 60] @staticmethod def get_fruit_price(fruit_name): if(fruit_name in FruitInfo.__fruit_name_list): index = FruitInfo.__fruit_name_list.index(fr...
""" This example shows how to use matplotlib to provide a data cursor. It uses matplotlib to draw the cursor and may be a slow since this requires redrawing the figure with every mouse move. Faster cursoring is possible using native GUI drawing, as in wxcursor_demo.py. The mpldatacursor and mplcursors thi...
num1=int(input("Enter first number: ")) num2=int(input("Enter second number: ")) num1 = num1+num2 num2= num1-num2 num1= num1-num2 print("After Swapping") print("Value of num1:",num1) print("Value of num2:",num2)
filename = input("Enter the file name: ") if filename=="na na boo boo": print('Here is a funny message') else: fhand = open(filename + ".txt") count = 0 average = 0 for line in fhand: line = line.rstrip() if line.startswith('X-DSPAM-Confidence:') : count = count...
def computemin(numbercheck): return min(numbercheck) def computemax(numbercheck): return max(numbercheck) minval = None maxval = None values = list() while True: line = input('Enter a number: ') if line == 'done' : print(computemin(values),computemax(values)) break...
""" Created on 29 Sep 2019 Class definition of LSTM multi input unit output framework. @author: Achut Manandhar Adapted from the following example: https://machinelearningmastery.com/how-to-develop-lstm-models-for-time-series-forecasting/ """ from keras.models import Sequential from keras.layers import LST...
names = ("ZL", "World") a, b = names print(a) print(b) a, b = divmod(10, 3) print(a) print(b) local = [(1, "hello"), (2, "world"), (3, "bonjure")] for _, word in local: print(word) t = (3, 1, 1, 0, 10) a, b, *rest = t print(a) print(b) print(rest) metro_areas = [ ('Tokyo','JP',36.933,(35.6897...
from typing import List class Solution: def searchMatrix1(self, matrix, target): if not matrix: return False for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == target: return T...
""" std lib -- string ! why do I need it when I have tools like str class, format() function and % etc? :: this lib provides other tools to make advanced text manipulation simple.. ? hmm, advanced text manipulations :: I'm not aware of these manipulations... TODOS: learns advanced text manipulations. string |-- stri...
""" ------------------------------------------------- File Name: yield_from Description : Author : wellqin date: 2020/2/11 Change Activity: 2020/2/11 ------------------------------------------------- """ from collections import namedtuple Result = namedtuple("Result", "count average") ...
""" ------------------------------------------------- File Name: 二叉树的最左下树节点的值 Description : Author : wellqin date: 2020/1/31 Change Activity: 2020/1/31 ------------------------------------------------- """ from DataStructure.二叉树.二叉树的搜索.CreateTree import Node, Tree def traverse(root)...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if head is None or head.next is None or k <= 0: return head cur = head ...
from typing import List class Solution: def subsets(self, nums): if not nums: return [] res = [] n = len(nums) def helper(idx, temp_list): res.append(temp_list) for i in range(idx, n): ...
""" Q: wtf is `...` in Python? A: it is `Ellipsis` object. Python > 3, using `...`, Python < 3, using `Ellipsis` Q: why the fuck do we need this? A: for showoff? i have no funcking idea. Ellipsis is just a normal object. Ellipsis itself has no special methods or properties. Official document says Ellipsis usual...
import array numbers = array.array('h', [-2, -1, 0, 1, 2]) memv = memoryview(numbers) print(len(memv)) print(memv[0]) memv_oct = memv.cast('B') print(memv_oct.tolist()) memv_oct[5] = 4 print(numbers)
""" ------------------------------------------------- File Name: test Description : Author : wellqin date: 2020/3/12 Change Activity: 2020/3/12 ------------------------------------------------- """ import random def insertSort(nums): pass de...
""" ------------------------------------------------- File Name: 数字 Description : Author : wellqin date: 2019/8/1 Change Activity: 2019/8/1 ------------------------------------------------- """ import math print(7.5//2) print(math.modf(7.5)) print(math.modf(7)) print(round(3.1415...
import string def str_tmp(s, insert_val): t = string.Template(s) return t.substitute(insert_val) def str_interplote(s, insert_val): return s % insert_val def str_format(s, insert_val): return s.format(**insert_val) def str_tmp_safe(s, insert_val): t = string.Template(s) try: return ...
def singleton(cls): _instance = {} def _singleton(*args, **kargs): if cls not in _instance: _instance[cls] = cls(*args, **kargs) return _instance[cls] return _singleton @singleton class A(object): """ 装饰器解析 A = singleton(A) -> 此步骤返回了_singleton这个函数 """ a...
from abc import abstractmethod, ABCMeta class Iterator(metaclass=ABCMeta): @abstractmethod def hasNext(self): pass @abstractmethod def next(self): pass class Container(metaclass=ABCMeta): @abstractmethod def getIterator(self): pass class NameIterator(Iterator...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ if not head or not head.next: return he...
class Computer: def __init__(self, name): self.name = name def __str__(self): return 'the {} computer'.format(self.name) def execute(self): return self.name + 'executes a program' class Synthesizer: def __init__(self, name): self.name = name def __str__(self): ...
""" ------------------------------------------------- File Name: travelTest Description : Author : wellqin date: 2020/3/13 Change Activity: 2020/3/13 ------------------------------------------------- """ class Node: def __init__(self,val): self.val = val self.left...
""" ------------------------------------------------- File Name: postOrder Description : Author : wellqin date: 2020/1/31 Change Activity: 2020/1/31 ------------------------------------------------- """ class Node(object): def __init__(self, val): self.val = val sel...
import collections class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ from heapq import heappush, heappop node_poo...
class Node: def __init__(self, item): self.val = item self.left = None self.right = None class Tree: def __init__(self): self.root = None def add(self, item): node = Node(item) if self.root is None: self.root = node ...
""" https://github.com/Suor/funcy """ from itertools import count from pprint import pprint import funcy as fc """Sequences""" item = [1, 2, 3] def sequences_generate(): pprint([item] * 3) pprint(item * 3) if __name__ == "__main__": sequences_generate()
""" ------------------------------------------------- File Name: 链表实现队列 Description : Author : wellqin date: 2019/7/11 Change Activity: 2019/7/11 ------------------------------------------------- """ class QueueError(ValueError): def __init__(self, text='队列为空,不可进行操作!'): pr...
""" ------------------------------------------------- File Name: 验证ip地址 Description : Author : wellqin date: 2019/9/16 Change Activity: 2019/9/16 ------------------------------------------------- """ import sys class Solution: def vaild_ipaddr(self, str): ip = str.split('.'...
import dis def fib(n): r = [0, 1] if n < 2: return r[n] else: for i in range(2, n + 1): r.append(r[i-1] + r[i-2]) return r[n] if __name__ == "__main__": dis.dis(fib) dis.show_code(fib)
class Connection: """ Class connection which allow to link two cities, contains the length of this connection """ def __init__(self, city1, city2, distance): """ Constructor :param city1: City n°1 :param city2: City n°2 :param distance: distance between th...
str1 = 'SAIRAM' str2 = 'SAI RAM' str3 = 'sAI RAM' print(str1.isupper(),str2.isupper(),str3.isupper())
lst = [5,20,-6,-4,1,3] temp1 = lst[0] for i in lst: if i < temp1: temp1 = i temp2 = lst[0] for j in lst: if j > temp2: temp2 = j print("Smallest number is {} and Largest number is {}".format(temp1,temp2))
n = int(input("Enter Number: ")) lst = list(str(n)) k = 0 for i in lst: k = k+pow(int(i),3) if k == n: print("Yes") else: print("No")
from random import randint import time class Tiger: animalName = '老虎' def __init__(self,weight): self.weight = weight def call(self): print('WOW !!,体重减少5') self.weight -= 5 def eat(self,food): if food == 'meat': self.weight += 10 print('喂食正确,体重增加10...
def mySort(List): newList=[] for i in range(len(List)): newList.append(min(List)) List.remove(min(List)) return newList print(mySort([1,0,2,5,7]))
class Solution(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if head == None or k == 0: return head dummyHead = ListNode(0) dummyHead.next = head p = dummyHead ...
def parse(sentence, previous=None): if not previous: sentence = sentence.lower() if sentence is '': return previous else: length = len(sentence) for i in list(range(2, length + 1)) + [1]: nextWord = sentence[0:i] if nextWord in wordSet: ...
from stack import Stack def convert_int_to_bin(dec_num): rem = Stack() bin_num = "" while dec_num > 0: rem.push(dec_num % 2) dec_num //= 2 while not rem.is_empty(): bin_num += str(rem.pop()) return bin_num print(convert_int_to_bin(4))
def empty_(cell): return cell == 0 def blocked_(cell): return cell != 0 def blocks_amount(board): i = 0 for row in board: for cell in row: if blocked_(cell): i += 1 return i def max_board_height(board): for idx, row in enumerate(board):...
import json userJSON = '{"first_name": "vivesh", "last_name": "yadav", "age": 21}' user = json.loads(userJSON) print(user) print(user['first_name']) car = {'brand': 'Tesla', 'model': 'X', 'body-style':'5 door SUV'} carJSON = json.dumps(car) print(carJSON)
class Solution: def kSimilarity(self, A: str, B: str) -> int: a = list(A) b = list(B) k = 0 queue = [] queue.append(A) result = {A:0} i=0 while queue: string = queue.pop() items = self.get_poss_swaps(list(string),b) ...
def check(ip): ip = ip.split(".") for i in ip: if(len(i) > 3 or int(i) > 255 or int(i) < 0): return False if(len(i) > 1 and int(i) == 0): return False if(len(i) > 1 and int(i) != 0 and i[0] == '0'): return False return True def convert(ip): si...
def primess(n): lis = [True] * n for i in range(3,int(n**0.5)+1,2): if lis[i]: lis[i*i::2*i]=[False]*int((n-i*i-1)/(2*i)+1) return [2] + [i for i in range(3,n,2) if lis[i]] def binarySearch (arr, l, r, x): if r >= l: mid = l + (r - l) // 2 if arr[mid] == x: ...
import sys M= int(sys.argv[2]) N= int(sys.argv[3]) numbers= sys.argv[1].split(',') for i in range(0, len(numbers)): numbers[i]= int(numbers[i]) MyIncrement = int(1) CheckIt = int(N) for i in range(0,len(numbers),1): print(MyIncrement) if(MyIncrement == CheckIt): numbers[i] = numbers[i] * M ...
emailList = ['cersei.lannister@got.eu', 'j.a.m.i.eLan@goteu', 'nedstark_got.eu'] emailValidation = re.compile(r'''([a-zA-Z0-9._&=-]+@[a-zA-Z0-9.-]+(\.[a-zA-Z] (2,4)))''', re.VERBOSE) for email in emailList: if re.match(emailValidation, email): print(email, "is valid") else: print(email, "is invalid")
import time from random import choice from itertools import combinations def zero_optimal(num_list): """ Quadratic algorithm from https://en.wikipedia.org/wiki/3SUM """ output = set() num_list.sort() length = len(num_list) for i in range(length-2): a = num_list[i] star...
def is_reverse(w1, w2): if len(w1) != len(w2): return False i = 0 j = len(w2)-1 while not j < 0: print(i, j) if w1[i] != w2[j]: return False i = i+1 j = j-1 return True print(is_re...
def ack(m, n): if m < 0 or n < 0: print("Ackermann is not defined for negative integers") elif m == 0: return n+1 elif n == 0: return ack(m-1, 1) else: return ack(m-1, ack(m, n-1)) print(ack(3, 4))
def is_triangle(length1, length2, length3): case1 = length1 + length2 case2 = length1 + length3 case3 = length2 + length3 if length1 > case3 or length2 > case2 or length3 > case1: print("No") elif length1 == case3 or length2 == case2 or length3 == case1: print("Degenerate triangle") ...
def avoids(words, forbw): for letter in forbw: if letter in words: return False return True def permutations_with_repetition(permutable): base = len(permutable) for n in range(base ** base): yield "".join(permutable[n // base ** (base - d - 1) % base] for d in range(base)) ...
import math def area(radius): a = math.pi * radius**2 return a def absolute_value(x): if x < 0: return -x else: return x def compare(x, y): if x > y: return 1 elif x == y: return 0 else: return -1 def distance(x1, y1, x2, y2): dx = x2 - x1 ...
import math def eval_loop(): while True: ein = input() if not ein == 'done': eval_result = eval(ein) print(eval_result) else: return eval_result if __name__ == '__main__': print(eval_loop())
def cumsum(seq): new_list = [] for i in range(0, len(seq)): new_list.append(sum(seq[0:i+1])) return new_list if __name__ == '__main__': my_list = [1, 2, 3, 67] print(cumsum(my_list))
import tensorflow from keras_preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) """### Gene...
def main(): input_user = input("Please input a valid credit card number: ") if isValid(input_user): print(getTypeCard(input_user[0])) print("The number is valid") else: print("Your credit card number is invalid") def isValid(card_number): valid_card = True check_numbers = (sumOfDoubleEvenPlace(card_n...