text
stringlengths
5
121k
import re from blist import blist def get_answer(number_of_players, number_of_marbles): scores = [0 for i in range(number_of_players)] circle = blist([0]) current_marble_index = 0 marble_value = 1 while marble_value < number_of_marbles + 1: if marble_value % 23 == 0: player...
from PIL import Image import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans filename = 'supermarket.jpg' image = Image.open(filename) im = np.array(image) reshaped = im.reshape(im.shape[0]*im.shape[1], 3) plt.imshow(im) plt.show() kmeans = KMeans(n_clus...
""" # tag::STRATEGY_TESTS[] >>> joe = Customer('John Doe', 0) # <1> >>> ann = Customer('Ann Smith', 1100) >>> cart = [LineItem('banana', 4, .5), ... LineItem('apple', 10, 1.5), ... LineItem('watermelon', 5, 5.0)] >>> Order(joe, cart, fidelity_promo) # <2> <Order total: ...
str = raw_input("Enter some words seperated using , : ") words = str.split(",") words.sort() for i in words: print(i)
class User(object): def __init__(self,first_name,last_name): self.FN = first_name self.LN= last_name def describe(self): print ('The username is: ' + str(self.FN) + str(self.LN))
print('\033[1;34mSeja bem-vindo ao Carvalho Cambios\033[m') S = float(input('\033[1;31mQuantos reais voce tem?\033[m')) Z = str(input('\033[1;32mQual moeda voce quer comprar?\033[m')).lower() if Z == 'dolar': D = float(5.22) if Z == 'euro': D = float(5.67) if Z == 'libra': D = float(6.52) T = S ...
def selection_sort(a): """ Selection sort :param a: list :return: list """ if not a or len(a) <= 1: return for i in range(len(a)): p = i for j in range(i + 1, len(a)): if a[j] < a[p]: p = j a[p], a[i] = a[i], a[p] return a
UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" LOWERCASE = UPPERCASE.lower() DIGITS = [str(i) for i in range(10)] SPECIAL = "*.!?&#,;:-_" def threshold_checker(password): upper = [char for char in password if char in UPPERCASE] lower = [char for char in password if char in LOWERCASE] numbers = [char for char in...
''' Project Name: Pizza Order Author: Sushant Tasks: 1. Ask customer for size of pizza 2. Do they want to add pepperoni? 3. Do they want extra cheese? Given data: Small piza: $15 Medium pizza: $20 Large pizza: $ 25 Pepperoni for Small Pizza: +$2 Pepperoni for medium & large pizza: +$3 Extra cheese ...
''' Project Name: Bank roulette Author: Sushant ''' import random name_str = input("Give me everybody's name, seprated by a comma. ") names = name_str.split(",") person_who_pays = random.choice(names) print(f'{person_who_pays} is going to pay for everyone')
def factorial(n): if n>12 or 0>n: raise ValueError('Provided value not within set limit (0 to 12)') elif n == 0: return 1 else: mylist = [] for i in range(1,n+1): mylist.append(i) value = 1 for x in mylist: value = value * x re...
import re def reverse_alternate(string): temp = re.sub (' +', ' ', string) temp = temp.split(' ') out = [] for i in range(len(temp)): if (i+1) %2==0: out.append(temp[i][::-1]) else: out.append(temp[i]) out1 = ' '.join(out) return out1.strip()
from math import sin, cos, pi for i in range(0,360,15): x = sin((i*pi)/180) y = cos((i*pi)/180) print(i, '---',round(x,4),round(y,4))
for i in range(5): print('i') print(sep='') print('A') print('B') for i in range (5): print('C') print('D') print('E') print(sep='') print('A') print('B') for i in range (5): print('C') for i in range (5): print('D') print('E') print(sep='') for i in range(3): p...
from random import randint L = [] for i in range(50): L.append(randint(1,100)) print(L)
from random import choice names = ['Joe','Bob','Sue','Sally'] current_player = choice(names) print(current_player)
x = eval(input('Enter a year:')) if (x%4) == 0: if(x%100) ==0: if (x%400) == 0: print(x,'Leap year') else: print(x,'Not leap year') else: print(x,'Leap year') else: print(x,'Not leap year')
s = 0 for i in range(1,51): s = s + i print(s)
from random import choice alphabet = 'abcdefghijklmnopqrstuvwxyz' s = ''.join( choice(alphabet) for i in range(100) ) print(s)
from math import sin, pi x = eval(input('Enter an angle in degrees:')) print(sin((x*pi)/180))
x = eval(input('Enter number:')) flag = 0 for i in range (2,x): if x%i == 0: flag = 1 if flag == 1: print(x,'is not prime') else: print (x,'is prime')
x = 1 y = 2 z = 3 hold = x x = y y = hold hold = y y = z z = hold hold = z z = x z = hold print('Value of x =',x) print('Value of y =',y) print('Value of z =',z)
import string L = [] for i in range(50): L.append(i) print('A list consisting of the integers 0 through 49:\n',L,'\n') N = [] for j in range(1,51): N.append(j**2) print('A list containing the squares of the integers 1 through 50:\n',N,'\n') s = string.ascii_lowercase print('Via enume...
from random import randint scores = [] for i in range(10): scores.append(randint(0,10)) scores.sort() print(scores) print('Two lowest scores:',scores[0],scores[1]) print('Two highest scores:',scores[-1],scores[-2]) print('Average:',sum(scores)/len(scores))
from random import randint for i in range (0,50): x = randint(3,6) print(x,end=' ')
import math e = 2.718 x = eval(input('Enter a number:')) s = 0 for i in range(1,x+1): s = s + 1/i print('The natural logarithm of',x,'is',s) y = math.log(x,e) print('ln(',x,') is',round(y,3))
import socket import sys import threading def send_message(clientSock): username = input("Input username: ") while True: message = input() message_send = username + ': ' + message clientSock.sendto(message_send.encode("utf-8"), (UDP_IP_ADDRESS, UDP_PORT_NO)) ...
import requests from bs4 import BeautifulSoup as bs import pandas as pd targetUrl = "https://maoyan.com/films?showType=3" header = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36", "cookie": "uuid=33...
""" Summarizes deltas. """ import pandas as pd from click import * from logging import * @command() @option('--input', required=True, help='the CSV file to read deltas from') @option('--output', required=True, help='the CSV file to write summaries to') def main(input, output): basicConfig( level=INFO, ...
""" Obtains optimal thresholds for partial localization. This threshold is determined by where the most negative slope occurs. """ import pandas as pd from click import * from logging import * @command() @option('--input', required=True, help='the CSV file to read stats from') @option( '--output', required...
from math import isnan, isinf def is_number(num, if_bool=False): """ :return: True if num is either an actual number, or an object that converts to one """ if isinstance(num, bool): return if_bool elif isinstance(num, int): return True try: number = float(num) return ...
""" Created on Tue Apr 2 14:00:42 2020 @author: sabkhalid """ import unittest class Unique_birthDate_firstName(unittest.TestCase): def test_unique_childIDs_true(self): result = unique_childID(['xyz', 'abc','123']) self.assertTrue(result, 'True') def test_unique_childIDs_equal(self): ...
""" Created on Tue Apr 7 22:18:31 2020 @author: sabkhalid """ from datetime import * def partial_date(date): try: date_dt = datetime.strptime(date, '%d %b %Y') Year = date_dt.year except: False return Year def s41test(info, file): for indiv in info[...
from turtle import * shape("turtle") color("WhiteSmoke") bgcolor("MidnightBlue") def quadrado(): for i in range(4): forward(100) right(90) def retangulo(): for i in range(2): right(90) forward(150) right(90) forward(90) quadrado() penup() backwa...
person = {'name':'Jenn', 'age': 23} import datetime my_date = datetime.datetime(2016,9,24,12,30,45) sentence = '{0:%B %d, %Y} fell on a {0:%A} and was the {0:%j} day of the year.'.format(my_date) print(sentence)
from unittest import TestCase from typing import List class Solution: def reverseVowels(self, s: str) -> str: vowels = ['a', 'e', 'i', 'o', 'u'] s = list(s) vowel_index = [(idx, char) for idx, char in enumerate(s) if char.lower() in vowels] j = 0 for i in range(len(vowel_ind...
from unittest import TestCase from typing import List class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: idx = 0 planted = 0 for i in range(n): while idx < len(flowerbed): if flowerbed[idx]: idx += 1 ...
import os kata = ['','one ','two ','three ','four ','five ','six ','seven ','eight ','nine '] belasan = ['','eleven ','twelve ','thirteen ','fourteen ','fifthteen ','sixteen ','seventeen ','eighteen ','nineteen '] puluhan = ['','ten ','twenty ','thirty ','fourty ','fifty ','sixty ','seventy ','eighty ','ninety '] d...
class Utils: def get_current_letter(self, tag_position): return tag_position[0] def get_current_number(self, tag_position): return tag_position[1] def letter_to_number(self, letter): letters_and_numbers = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8} retu...
import random while True: choice=input("Do you want to Roll Dice or exit:Y/N").capitalize() if choice=="Y": print(random.randint(1,6)) elif choice=="N": print("Bye") break
S = input() if S.isupper(): print('A') else: print('a')
abc = list(map(int, input().split())) count = (len(abc) + len(set(abc))) - 3 print(count)
a = [1] + [int(input())] b = [2] + [int(input())] c = [3] + [int(input())] rank = [a, b, c] rank.sort(key=lambda x:-x[1]) for i in range(3): rank[i].append(i+1) rank.sort(key=lambda x:x[0]) for i in range(3): print(rank[i][2])
a = int(input()) b = int(input()) c = int(input()) d = int(input()) if a >= b and c >= d: print(b + d) elif a >= b and c < d: print(b + c) elif a < b and c >= d: print(a + d) else: print(a + c)
n = int(input()) a = int(input()) ans = n % 500 if ans <= a: print('Yes') else: print('No')
print('Hello Notitia-AI C2 Fellow') def greet(): name = input("Please enter your name\n") print("Welcome to Notitia-AI" + "" + name) greet()
import os import matplotlib.pyplot as plt import numpy as np print(os.getcwd()) path = "C:\\Users\\Adem\\PycharmProjects\\GörüntüIsleme" file_name_with_path = path + "\pic_1.jpg" print(file_name_with_path) img_0 = plt.imread(file_name_with_path) plt.imshow(img_0) plt.show() print(img_0.ndim,img_0.s...
from pynitefields import * class Curve(): """ Class to hold all points in a curve. Curves are sets of points of the form :math:`(\\alpha, c(\\alpha)` for all :math:`\\alpha` in a specified GaloisField, where .. math:: c(\\alpha) = c_0 + c_1 \\alpha + c_2 \\alpha^2 + ...
f=open('zfc.txt','r',encoding='utf-8') for line in f: list1=line.split('"') for x in list1: res=x.startswith('h') if res==True: print(x) else: continue f.close()
def gcd(a,b): while( b!=0): temp = a a = b b = temp % b return a print(gcd(60, 96))
import math import numpy as np alpha_encrypt = {' ': 0, 'A': 3, 'B': 6, 'C': 9, 'D': 12, 'E': 15, 'F': 18, 'G': 21, 'H': 24, 'I': 27, 'J': 30, 'K': 33, 'L': 36, 'M': 39, 'N': 42, 'O': 45, 'P': 48, 'Q': 51, 'R': 54, 'S': 57, 'T': 60, 'U': 63, 'V': 66, 'W': 69, 'X': 72, 'Y': 75...
from datetime import datetime now = datetime.now() currentDt = now.strftime("%d/%m/%Y %H:%M:%S") allowedUsers = ['Seyi', 'Sam', 'Love'] allowedPassword = ['passwordSeyi', 'passwordSam', 'passwordLove'] Balance = 0 name = input('What is your name? \n') if name in allowedUsers: password = input('Your password \n') ...
a = int(input('Please input the First Number:')) b = int(input('Please input the Second Number:')) while b != 0: gcd = b b = a % b a = gcd print(gcd) ''' for i in range(1,b+1): if a % i == 0 and b % i == 0: gcd = i print(gcd)'''
""" Created on 11/04/2020 @author: SkyCharmingDeamon _Umuzi_ Pre-bootcamp challenges tast 3: functions A function that takes 2 numbers as input. If either of the numbers is 65, OR if the sum of the numbers is 65 then return true. Otherwise return false, """ def function(a,b): return (a == 65 or b ==...
from copy import copy from typing import List class Knapsack: def __init__(self): self.maxW = 9 self.items = [2, 2, 4, 6, 3] self.values = [3, 4, 8, 9, 6] print(f"item weight: {self.items}") def backtracking(self, i, bag): if i >= len(self.items): y...
from typing import List from queue import PriorityQueue import sys class ListNode: __slots__ = 'val', 'next' def __init__(self, x): self.val = x self.next = None def __lt__(self, other): return self.val < other.val class MergeSortedLists: def mergeKLists(self, list...
from Graph import AdjacencyMap def topological_sort(graph: AdjacencyMap): incount = dict() queue = list() for vertex in graph.vertices: incount[vertex] = graph.degree(vertex, False) walk = None while len(incount): if walk == incount: break walk = incou...
from typing import List from array import array import copy class NQueue: def solveNQueens(self, n: int) -> List[List[str]]: chessboard = [array('u', '.' * n) for i in range(n)] output = list() for complete_chessboard in self.assign(chessboard, 0): so...
"""This is the list of my practical work of learning OOP. (Uncomment he part of code you want to run)""" """Class and object creation""" """Constructor __init__""" """Inheritance""" """Polim...
n=int(input("enter the number")) sum = 0 while (num > 0): sum += int(n % 10) n = int(n / 10) print(sum)
'''reverse the given number''' n=int(input()[::-1]) print(n)
import math import os import random import re import sys if __name__ == '__main__': n = int(input().strip()) def is_even(n): if n % 2 == 0: return True return False if not is_even(n): print("Weird") if is_even(n) and n in range(2, 6): print("Not Weird"...
fruit = "banana" index = 0 while len(fruit) > index: letter = fruit[index] print (letter) index += 1
from scipy.stats import pearsonr from tkinter import * from tkinter import filedialog def main(url = "adult.csv", data1="age", data2="y"): direc="C:/Users/Ammon Van/Desktop/Fun Projects/Statistic Analysis/Tests" filetypes = (("CSV", "*.CSV"), ("All Files", "*.*")) url = filedialog.askopenfilename(ini...
import picodisplay as display import utime buf = bytearray(display.get_width() * display.get_height() * 2) display.init(buf) display.set_backlight(0.5) def clear(): display.set_pen(0, 0, 0) display.clear() display.update() while True: if display.is_pressed(display.BUTTON_A): ...
def are_they_the_same(a, b): counter = {} counter2 = {} for i in a: counter[i] = 0 for i in a: counter[i] += 1 for i in b: counter2[i] = 0 for i in b: counter2[i] += 1 resultFalse = 0 ...
import LinkedList as ll if __name__ == '__main__': print('Hello LinkedList!!!\n') llist = ll.LinkedList() llist.add(1) llist.add(2) llist.add(3) llist.add('What the bloody horse lungs....????') llist.shift(0) llist.shift(-1) llist.shift(-2) llist.shift(-3) llist.p...
print(list(range(5))) print(list(range(0,20,2)))
x="hello" print("-".join(x)) my_str="python" my_Strn1="scripting" my_Str2="lang" print(f'{my_str.center(12)}\n{my_Strn1.center(20)}\n{my_Str2.center(20)}') zero="python" print(zero.zfill(10))
''' usr_strng= input("Enter your string: ") index=0 # index var is defined for each_char in usr_strng: print(f' {each_char} -->{index}') index=index+1 # we're increasing index value by 1 ''' import os req_path= input("Enter your dir path: ") if os.path.isfile(req_path): print(f' the {req_path} is a file pl...
x = 3 y = 5 print(x) myname="himanshu" print(myname,type(myname))
''' def addition(a,b): result = a+b return result # this value we're sending back to main func to print def main(): a = eval(input("Enter your number: ")) b = eval(input("Enter your 2ndnumber: ")) result = addition(a,b) # calling addition func & argument value and storing in result print(f...
from math import sqrt from parameterized import parameterized import unittest class Test(unittest.TestCase): @parameterized.expand([ (11, True), (15, False), (1, False), (5, True), (4, False), (49, False) ]) def test(self, target, is_prime_expected): ...
""" Given an array A [ ] having distinct elements, the task is to find the next greater element for each element of the array in order of their appearance in the array. If no such element exists, output -1. https://practice.geeksforgeeks.org/problems/next-larger-element/0 """ from heapq import heappush, heappop from p...
from copy import copy def _rec(arr, n, m): if n < 1: return yield from _rec(arr, n-1, m) for i in range(1,m): arr_loop = copy(arr) arr_loop[n-1] = i yield arr_loop yield from _rec(arr_loop, n-1, m) def main(n, m): arr = [0]*n yield arr yield from _r...
import unittest from parameterized import parameterized class Test(unittest.TestCase): @parameterized.expand([ ("provided example 0", [5, 3, 7, 10], 15), ("provided example 1", [8, 15, 3, 7], 22), ("one number", [1], 1), ("two numbers highest", [1, 2], 2), ("three numbers",...
"""Given an array A[] of n numbers and another number x, determine whether or not there exist two elements in A whose sum is exactly x.""" from parameterized import parameterized import unittest class Test(unittest.TestCase): @parameterized.expand([ (16, [1, 4, 45, 6, 10, 8], True), (10, [1, 2, ...
import unittest from parameterized import parameterized class Test(unittest.TestCase): @parameterized.expand([ ("provided example", [3, 34, 4, 12, 5, 2], 9, True), ("single value true", [1], 1, True), ("single value false", [1], 2, False), ("three values true", [1, 2, 3], 5, True),...
import sqlite3 as sqlite import datetime conn = sqlite.connect('Northwind_small.sqlite') cur = conn.cursor() def extra_credit(): statement = 'SELECT CustomerId,OrderDate ' statement += 'FROM [Order] ' statement += 'ORDER BY CustomerId' row = cur.execute(statement) ids = [] print('CustomerID, '+...
import sys def main(): with open(sys.argv[1]) as f: num = int( f.readline().strip()) for _ in range(num): line = f.readline().strip() opens = [] isValid = True open_char = "([{<" close_char = ")]}>" for i in range(len(line)): ...
number = input('Enter an integer: ') numb = str(number + ' ') print(10*numb)
scores = [3 ,4 ,21 ,36 ,10 ,28 ,35, 5 ,24 ,42] def breakingRecords(scores): temporary_max = scores[0] temporary_min = scores[0] maximum_score = [] minimum_score = [] result_arr = [] for score in scores: if score<temporary_min: minimum_score.append(score) ...
import re phoneNumGroup = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') mo2 = phoneNumGroup.search('my phone number is 415-555-5555') print(mo2.group(1)) print(mo2.group(2)) print(mo2.group(0)) print(mo2.group()) heroRegex = re.compile(r'Batman | Tina Fey') mo3 = heroRegex.search('Batman & tina f...
print("Hello World!") msg = "Hello World!" name = "Carlos" print("Hello", name,"!") print("Hello " + name + "!") number = 42 print("Hello" , name, "!", "My favorite number is", number,".") print(f'{"Hello " + name + "!" + " My favorite number is" } {number}{"."}') print("Hello " + name + "!" + " My favorite number i...
def a(): return 5 print(a()) def a(): return 5 print(a()+a()) def a(): return 5 return 10 print(a()) def a(): return 5 print(10) print(a()) def a(): print(5) x = a() print(x) def a(b,c): print(b+c) def a(b,c): return str(b)+str(c) print(a(2,5)) def a(): b =...
def solution(number): return sum([i for i in range(number) if (i % 5 == 0 or i % 3 == 0)]) print(solution(10))
""" Created on Sun Oct 3 18:24:55 2021 @author: hp """ from tkinter import* import random root=Tk() root.title("RANDOM LIST ANS LUCKY FRIEND GENERATER") root.geometry("700x400") enter_country=Entry(root) enter_country.place(relx=0.5,rely=0.2,anchor=CENTER) enter_city=Entry(root) enter_city.plac...
from Tkinter import * top=Tk() top.config(background="brown4") top.title("WELCOME") top.geometry("1600x900") Label(top,text="SUBJECT NAME=",fg="black",bg="brown4",bd=14,font=("times",27)).place(x=300,y=215) el=Entry(top,font=("arial",21)) el.place(x=690,y=230) Button(top,text="submit ",fg="white...
fruits = ['Nanas', 'Apel', 'Pepaya', 'Kentang'] for i in range (4) : print(fruits[i]) length = len(fruits) i = 0 while i < length: print(fruits[i]) i += 1
import numpy as np import Utils class Classifier: training = None train_arr = None classes = None def __init__(self, training, train_arr, CLASSES = 3): self.training = training self.train_arr = train_arr self.classes = CLASSES def OneNNClassify(self, test_set, K): ...
import nltk from nltk.corpus import words nltk.download('words', quiet=True) word_list = words.words() def encrypt(plain_text, key): encrypted_word = '' print(f'The plain text word is{plain_text}.') for i in range(len(plain_text)): char = plain_text[i] if (char...
def fizzBuzz(self, s): string = [] for n in range(1, s + 1): if n % 3 == 0 and n % 5 == 0: string.append("FizzBuzz") elif n % 3 == 0: string.append("Fizz") elif n % 5 == 0: string.append("Buzz") else: ...
import numpy as np class Perceptron(object): def __init__(self, rate = 0.01, niter = 10): self.rate = rate self.niter = niter def fit(self, X, y): """ Fit training data :param X: Training vectors, X.shape: [samples, features] :param y: Target value, y.shape : ...
def gc(a, b): r = a % b a = a - r return a print(gc(a=int(input('a: ')), b=3))
""" Solutions for https://adventofcode.com/2020/day/10 """ from collections import Counter, UserList from itertools import chain, combinations from math import prod class OutputJoltages(UserList): """ Data Model for output joltages from data file """ @classmethod def from_file(cls, file_path): ...
""" Solutions for https://adventofcode.com/2020/day/1 """ with open('data/day01_report_repair-data.txt') as fp: data_values = [int(line.rstrip()) for line in fp] differences_from_2020 = { 2020 - v for v in data_values } for v in data_values: if v in differences_from_2020: print(f'...
""" Solutions for https://adventofcode.com/2020/day/6 """ from collections import UserDict class GroupResponses(UserDict): """ Data Model for "question group_responses" from data file """ def __init__(self): super().__init__() self.group_size = 0 def add_responses(self, responses):...
rowlist = list() with open('d_big.in' , 'r') as f: line_one = f.readline().split() R = line_one[0] C = line_one[1] L = line_one[2] H = line_one[3] if (int(H) > int(C)): H = C print('Rows: ' + R) print('Columns: ' + C) print('Min Ingredient: ' + L) print('Max Cells: ' + H) print(' ' ...
''' Dominos Pizza API utility functions. ''' import re def enum(**enums): ''' Utility function to create a simple enum-like data type. Behind the scenes it is just a list. :param list enums: A list of key value pairs. :return: A simple list. :rtype: list ''' return type('Enum', (), enu...
list = [1, 2, 3, 4] dictionary = current = {} for name in list: current[name] = {} current = current[name] print(dictionary)