text stringlengths 5 121k |
|---|
import pygame
from spritesheet import spritesheet
from pygame.locals import *
import numpy
"""1 is water, 2 is ship, 3 is HIT, 4 is miss, 5 is opponent ship"""
class Board(object):
def __init__(self):
self.Matrix = [[1 for x in range(10)] for y in range(10)]
self.opp_ship_spaces = 10
def setSpace(self,x,y,new... |
def datSim():
cuenta = int(input("cuantos datos deseas procesar? \n"))
datos = []
conteo=1
while conteo <= cuenta:
dato = input("dato a procesar: \n")
datos.append(dato)
conteo = conteo + 1
else:
print(datos)
def datMed():
dato = {}
cuenta = int(inp... |
def add_up(x, y):
return x + y
print(add_up(10))
|
def counter(func):
count = 0
def inc_count():
func()
nonlocal count
count += 1
print(" Called", count, "times")
return inc_count
def hello():
print("Hi PyCon")
inc = counter(hello)
inc()
inc()
inc()
def create_logic(func):
def when(a,b):
if not (callab... |
class Cell(object):
""" Stores the possible Pieces for any given Cell. """
def __init__(self, height):
self.height = height
self.colors = list("RGBPYO")
self.proposal = None
def set_color(self, color):
if not color in self.colors:
raise Exception("color already ... |
def main():
average = 0
score1 = 0
score2 = 0
score3 = 0
score4 = 0
score5 = 0
score1 = int(input("Score one: "))
... |
nmb_day = input("What number of the day is it?: ")
int_nmb_day = int(nmb_day)
if int_nmb_day == 1:
print("Monday")
elif int_nmb_day == 2:
print("Tuesday")
elif int_nmb_day == 3:
print("Wednesday")
elif int_nmb_day == 4:
print("Thursday")
elif int_nmb_day == 5:... |
def smart_divide(func):
def inner(a,b):
if b == 0:
print("Cannot divide by zero")
return None
return func(a,b)
return inner
@smart_divide
def divide(a,b):
return a/b
result = divide(6,2)
print(result) |
import copy
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
p=Point(1,2)
q = copy.copy(p)
q.x = 2
print(p==q)
print(p.x)
print(q.x) |
prime=int(input("Enter your number\n"))
if prime>1:
for i in range(prime):
if (prime % 2)==0:
print(prime,"is not a prime number")
break
else:
print(prime," It is a prime number")
|
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
rows = [''] * numRows
str_idx = 0
i = 0
down = True
while str_idx < len(s):
r... |
import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
"""Manages the ship"""
def __init__(self, ai_game):
super().__init__()
self.screen = ai_game.screen
self.screen_rect = ai_game.screen.get_rect()
self.settings = ai_game.settings
self.image = pygame.image.load('images/BEER.bmp')
self.r... |
"""Class that provides function(s) related to calcuations of
Fibonacci numbers.
TODO: Add some additional error handling:
- How do I handle desiredSequence and ensuring it is an integer.
TODO: Overflow handling?
TODO: Can I cleanup the calculation
"""
class Fibonacci:
"""This class provides Fibonacci... |
"""Plot the function sin(1 / XY)."""
import matplotlib.pyplot as plt
import numpy as np
sz = 5000
X = np.linspace(-1, 1, sz)
Y = np.linspace(-1, 1, sz)
X, Y = np.meshgrid(X, Y)
Z = np.sin(1 / (X * Y))
fig, ax = plt.subplots(1)
im = ax.imshow(Z, cmap=plt.get_cmap("plasma"),
origin="lower", extent=(-1... |
import math
def suma(a1, b1, a2, b2):
return f"Result: {a1 + a2} + {b1 + b2}i"
def resta(a1, b1, a2, b2):
return f"Result: {a1 - a2} + {b1 - b2}i"
def multi(a1, b1, a2, b2):
return f"{a1*a2 - b1*b2} + {a1*b2 + a2*b1}i"
def div(a1, b1, a2, b2):
return f"{(a1*a2 + b1*b2)/(a2**2 + b2**2)} +... |
import unittest
def find_duplicate(int_list):
list2=[]
length=len(int_list)
for i in range(0,length):
index = int_list[i]%length
int_list[index] = int_list[index]+length
for i in range(0,length):
if(int_list[i]/length)>1:
return i
... |
try:
n = range(int(raw_input("Fizz buzz counting up to ")))
except ValueError:
print("Please only input integers.")
n = range(int(raw_input("Fizz buzz counting up to ")))
for i in n:
if i % 3 == 0 and i % 5 == 0:
print("fizz buzz")
elif i % 5 == 0:
print("buzz")
elif i % 3 == 0:
... |
a = int(input())
arr = []
for i in range(a):
x = int(input())
arr.append(x)
for i in arr:
arr.reverse()
print(arr) |
n = int(input("Enter list lenth: "))
list_elements = []
for i in range(n):
number = int(input("Enter number:"))
list_elements.append(number)
print(list_elements)
while True:
print("""
1) Print the entire list
2) Add a new one to the list
3) Average odd from the whole... |
from typing import List
def numberOfSubarrays(nums: List[int], k: int) -> int:
if len(nums) < k:
return 0
left, right = -1, 0
odd_cnt = 0
while right < len(nums):
if nums[right] % 2 == 1:
odd_cnt += 1
if odd_cnt == k:
break
right += 1... |
chr=(input("Enter Charactor:"))
if (ord(chr) >=65) and (ord(chr)<=90):
print("its a CAPITAL Letter")
elif (ord(chr>=97) and ord(chr<=122)):
print ("its a Small charector")
else:
print("errrrr404") |
print(chr(65))
print(ord("B"))
listOfNo= [1,2,3,4,5,6,7,8,9,10]
listOfCharacters=[]
for no in listOfNo:
listOfCharacters.append(chr(no+64))
print(listOfCharacters) |
A=int(input("enter your percentage in \"A\""))
B=int(input("enter your percantage in \"B\""))
if (A>=55) and (B>=45):
print("Pass [Grade 1] ")
elif(A>=45) and (A<=55) and (B>=55):
print ("pass [Grade]2")
elif(B<45) and (A>=65):
print ("you are allwed to reappear")
else:
print("fail - game over! Try A... |
hardness = int (input("Enter the hardness:" ))
carbonContent = float (input("Enter the carbon content:" ))
tensileStrength = int (input("Enter the tensile strength:" ))
def IsCondition1Passed():
if hardness>50:
return True
else:
return False
def IsCondition2Passed():
if carbonContent<0.7:
... |
t=int(input("enter the number : "))
for table in range (1,10+1):
print (t, "x",table, "=", t * table ) |
x=int(input("enter the point in \"x\""))
y=int(input("enter the point in \"y\""))
if (x==0 and y==0):
print("Point lies on the Origin\n")
elif(x==0):
print("point lies on y- axis")
elif(y==0):
print("point lies on x- axis")
else:
print ("Error")
|
try:
pc_point = 0
player_point = 0
roundn = 0
while roundn < 10:
roundn = roundn + 1
import random
list2 = ["snake", "water", "gun"]
list1 = random.choice(list2)
print("\n snake , water , gun")
inp1 = input("choose one of this : ")
... |
import tweepy
import random
"""
Procedure
* Sign in Twitter Accout
* Make list object that contains tweet content
* Randomly select one tweet content, and tweet
* automate tweeting
"""
CONSUMER_KEY = 'psWut2vFh9e1dX0gCV5ICj5rk'
CONSUMER_SECRET = '5MXkpqqEe00Kn5ue1Ie6esBpQa8ocNub7gBCSGXqc4ylNmiMFp'
ACCESS_TOKEN =... |
jogador = dict()
gols = list()
jogador = {'nome': '', 'gols': gols, 'n_partidas': 0}
jogador['nome'] = str(input("Nome do jogador: "))
jogador['n_partidas'] = int(input(f"Quantas partidas {jogador['nome']} jogou? "))
for n in range(0,jogador['n_partidas']):
gols.append(int(input(f"Quantos gols marcados... |
class DisjointSet:
def __init__(self, matrix):
self.matrix = matrix
self.nodesCount = len(matrix)
self.parent = [i for i in range(self.nodesCount)]
def find(self, x):
if self.parent[x] == x:
return x
self.parent[x] = self.find(self.parent[x])
return ... |
def rotate(matrix):
l = len(matrix)
for row in matrix:
print(row)
print()
for i in range(l):
for j in range(i, l):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for row in matrix:
print(row)
print()
for i in range(l):
for j i... |
"""
arr[] = {1, 2, 10, 5, 5}
dep[] = {4, 5, 12, 9, 12}
Below are all events sorted by time. Note that in sorting, if two
events have same time, then arrival is preferred over exit.
Time Event Type Total Number of Guests Present
------------------------------------------------------------
1 Ar... |
def bfs(n, m, edges, s):
graph = {i: [] for i in range(1, n + 1)}
visited, queue, level = [False] * (n + 1), [], [0] * (n + 1)
queue.append(s)
visited[s] = True
level[s] = 0
while queue:
vertex = queue.pop(0)
for neighbor in graph[vertex]:
if visit... |
def isListPalindrome(l):
stck = []
head = l
while head != None:
stck.append(head.value)
head = head.next
while l != None:
if stck.pop(-1) != l.value:
return False
l = l.next
return True
|
def longest_palindrome_length(string):
N = len(string)
cache = [[None]*N for _ in range(N)]
left, right = 0, 0
def find_length(i, j):
if(cache[i][j]!=None):
return cache[i][j]
if(i>j):
return 0
if(i==j):
return 1
if(string[i]==strin... |
def firstDuplicate(array):
l = len(array)
for i in range(l):
if array[abs(array[i])-1] < 0:
return abs(array[i])
array[abs(array[i])-1] = -array[abs(array[i])-1]
print(firstDuplicate([2,1,1]))
|
from collections import defaultdict
def dfs_visit(node, graph, color, time, d, f):
time+=1
color[node] = 'Gray'
d[node] = time
for neighbour in graph[node]:
if(color[neighbour]=='Black'):
continue
elif(color[neighbour]=='Gray'):
return True
elif(dfs_visit... |
def LIS(array):
l = len(array)
cache = [None]*(l+1)
dir = [-1]*(l+1)
def longest(i):
if cache[i]!=None:
return cache[i]
maxi = 0
for j in range(i+1, l):
if(array[j]> array[i]):
if longest(j) > maxi:
maxi = longest(j)
... |
def uniqueEmails(emails):
uniq_mails = set()
for email in emails:
formatted_email = ''
splits = email.split('@')
flag = True
for c in splits[0]:
if c=='+':
flag=False
if c=='.':
continue
if flag:
... |
"""
The Blocks World AI problem implemented and sovled with Python.
Creator: Apostolos Anastasios Kouzoukos, dai17038
Email: kouzoukos97@gmail.com
Github: https://github.com/kouzapo
"""
import time
import sys
import os
from state import State
from searching import breadth_first_search, depth_first_searc... |
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
fig = plt.figure()
ax = plt.axes(xlim=(0.0, 0.4), ylim=(0, 3.0e5))
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
def animate(i):
k = str(i)
k = (3-len(k))*'0'+k
fl = op... |
print("IF IT DOESN'T WORKING READ README")
print("To learn the commands type hlp()")
def calc():
a = input()
b = input()
print("The sum is:", a + b)
def mu():
c = input()
d = input()
print("The sum is:", c * d)
def ext():
print("CLOSING")
exit()
def hlp():
print("To s... |
x=100
word='dog'
letter_left=list(word)
score_board=['_']*len(word)
stages=['','________ ','| | ','| O ','| | ','| /|\ ','| / \ ','| ']
wrong_guesses=0
win=False
print('Welcome to Hang Man!')
print('It\'s a ',len(word),'-letter word:')
print(''.join(score_board))
while wrong_guesses<len(stages)-1:
guess=in... |
def my_sqrt(x):
"""Returns the square root of x"""
guess = 1
while(abs(guess*guess-x)>0.0001):
guess = (1/2)*(guess+x/guess)
return guess |
import pyglet
a = [0, 1, -3, 6, 2, 10]
numbers = [[str(item) for item in a]]
def bubble_sort_algo(lst):
move = []
for t in range(len(lst)):
swap = False
for i in range(len(lst) - 1):
move.append(('n', lst[i], lst[i + 1]))
if lst[i + 1] < lst[i]:
lst[i], ... |
class Potato():
def __init__(self):
self.name = "Jim Bob, Chubbbbby Donkey & Choompa"
def displayChubsters(self):
print(self.name)
print(self.name)
p1 = Potato()
p1.displayChubsters() |
message = input("Enter message")
charCount=0
wordCount =1
for i in message:
charCount=charCount+1
print(i+str(charCount))
if(i==" "):
wordCount=wordCount+1
print("Word count" + str(wordCount))
|
from collections import Counter
numbers = [1,2,3,4,5,6,7,8,4,5,6,7,8,6]
print(Counter(numbers))
z = Counter(numbers)
max = 0
for p in z:
if z[p]> max:
max = z[p]
for p in z:
if z[p]== max:
print(p)
|
class Car:
def __init__(self):
self.type = ""
self.model = ""
self.wheels = 4
self.doors = 3
self.seets = 5
def print_model(self):
print("This car is a {model}: {type}, Wow!".format(model=self.model,type= self.type))
def print_space(self):
print("The... |
farms = [{"name": "NE Farm", "agriculture": ["sheep", "cows", "pigs", "chickens", "llamas", "cats"]},
{"name": "W Farm", "agriculture": ["pigs", "chickens", "llamas"]},
{"name": "SE Farm", "agriculture": ["chickens", "carrots", "celery"]}]
yuck= ["carrots","celery", "apples", "bananas", "ora... |
from random import randint
class Player:
def __init__(self):
self.dice = []
def roll(self):
self.dice = []
for i in range(6):
self.dice.append(randint(1,6))
def get_dice(self):
return self.dice
class Dependapotomus(Player):
def love(self, depe... |
"""The puropose of this program is to display every NFL players data. By: Damian Mercado"""
import random
import csv
def print_random_column(data):
csv_reader = csv.reader(data)
nfl_player_data = list(csv_reader)
random_question = random.choice(nfl_player_data)
print(random_question... |
class tester:
"""
tester class verifies the input
"""
def __init__(self):
pass
def test_string(self,address):
"""
Function to test if the type is a string
:param address: string
:return: assert
"""
t=type(address) == str
assert t, "not... |
showroom = set()
showroom.add('Honda')
showroom.add('Ford')
showroom.add('Dodge')
showroom.add('RAM')
print(len(showroom))
showroom.add("Honda")
print(showroom)
showroom.update({"Truck", "Car"})
showroom.discard("Car")
junkyard = {"Honda", "Smart", "RAM", "BMW"}
inBoth = showroom.intersection(junkyard)... |
stockDict = {
"GM": "General Motors",
"CAT":"Caterpillar",
"EK":"Eastman Kodak",
"GE": "General Electric"
}
purchases = [
( 'GE', 100, '10-sep-2001', 48 ),
( 'CAT', 100, '1-apr-1999', 24 ),
( 'GE', 200, '1-jul-1998', 56 )
]
for purchase in purchases:
stock_abrv = purchase[0]
stock_... |
numero = int(input())
horas = int(input())
salario = float(input())
salario = float(salario * horas)
print("NUMBER = {}".format(numero))
print("SALARY = U$ %.2f" %(salario)) |
def isPalindrome(n):
if n < 0:
return False
sum = 0
origin = n
while n:
num = n % 10
sum = sum*10 + num
n /= 10
print(sum)
if sum == origin:
return True
else:
return False
print(isPalindrome(121)) |
class Solution:
def maxProfit(self, prices):
if prices is None:
return 0
minPrices = prices[0]
maxProfit = 0
for index, value in enumerate(prices):
if prices[index] < minPrices:
minPrices = prices[index]
elif prices[index]... |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def __init__(self):
self.flag = True
def create(self, dataList):
root = TreeNode(dataList[0])
if len(dataList) >= 2:
... |
def twoSum(nums, target):
"""
双指针实现
两数之和
"""
assert len(nums) >= 2
l, r = 0, len(nums)-1
while l < r:
if nums[l] + nums[r] == target:
return l+1, r+1
if nums[r] + nums[l] < target:
l += 1
else:
r -= 1
print('The i... |
with open ('reversed.txt') as text_reversed:
print(text_reversed.read()[::-1])
|
def fib(max):
n,a,b=0,0,1
while n<max:
yield b
a,b=b,a+b
n=n+1
return 'end'
a=fib(10)
print(a.__next__())
print("--------")
print(a.__next__())
print("--------")
print(a.__next__())
print("--------")
|
a=20
b=0
num=0
while True :
if b<a:
b+=3
num+=1
if b<a:
b-=2
else:
print("第",num,'天能跳出来')
break
else:
print("第", num, '天能跳出来')
break
|
List = [1,4,7,5,8,2,1,3,4,5,9,7,6,1,10]
setL = set(List)
for i in range(len(setL)):
view = setL.pop()
print("{0}出现了{1}次。".format(view,List.count(view))) |
def add(amount):
def func(value):
return value + amount
return func
adds_5 = add(5)
adds_10 = add(10)
adds_1000 = add(1000)
print(adds_5(60))
print(adds_5(15))
print(adds_5(995))
print(adds_1000(60))
print(adds_1000(15))
print(adds_1000(995)) |
class Polynomial:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __repr__(self):
return "Polynomial({}x^2 + {}x + {})".format(self.a, self.b, self.c)
def __add__(self, other):
return Polynomial(self.a + other.a, self.b + other.b, self.c + o... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
crime_data = pd.read_csv('crime_data.csv')
def norm_func(i):
x = (i-i.mean())/(i.std())
return (x)
df_norm = norm_func(crime_data.iloc[:,1:])
from scipy.cluster.hierarchy import linkage
import scipy.clus... |
while True:
print('To quit program enter "q"')
val1 = input('Enter a first number: ')
if val1 == 'q':
break
val2 = input('Enter a second number: ')
if val2 == 'q':
break
try:
val1 = int(val1)
val2 = int(val2)
except ValueError:
print('one of entere... |
from decorator.decorators import do_twice
"""
Returning Values From Decorated Functions
"""
@do_twice
def greet(name):
print(f"Hello {name}")
print(greet("sujon"))
@do_twice
def return_greating(name):
print("Creating greading")
return f"Hi {name}"
hi_emon = return_greating("Emon")
print(hi_emon) |
"""
It’s possible to define functions inside other functions.
Such functions are called inner functions
"""
def parent():
print("printing from the parent() function")
def first_child():
print("printing from the first_child() function")
def second_child():
print("printing from the second... |
def fact(num):
if num==1or num==0:
return 1
else:
return fact(num-1)*num
print('n e')
print('- -----------')
for i in range(0,3):
res=0
if i==2:
for j in range(0, i + 1):
res += float(1 / fact(j))
print(i,res)
else:
for j in range(0,i+1):
... |
from time import sleep
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
ans = 1
while ans == 1:
matches = list()
player = dict()
sumtotal = 0
... |
from time import sleep
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
trip = int(input("Enter your travel distance in km: "))
print("{}Loading...{}".forma... |
from datetime import date
from time import sleep
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
gender = int(input("Before continuing the enlistment Enter... |
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
name = input('Enter your name: ')
print('{}Nice to meet you, {}{}{}'
.format(colors["blue"], colors["... |
from time import sleep
from datetime import date
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
ans = 1
while ans == 1:
people = list()
person = d... |
from datetime import date
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
today = date.today().year
old = 0
new = 0
for c in range(1, 8):
major = int(i... |
from time import sleep
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
ans = 1
while ans == 1:
values = list()
for c in range(0, 5):
values... |
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
n1 = int(input('Enter a number: '))
n2 = int(input('Enter a number: '))
sum = n1 + n2
print('Your first num... |
from time import sleep
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
ans = 1
while ans == 1:
values = list()
while True:
print("if you wa... |
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
num = ("Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
"Eleve... |
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
ans = 1
while ans == 1:
tuple = ()
ans2 = 1
sum = 0
while ans2 == 1:
produ = str(in... |
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
sumc = 0
cont = 0
for c in range(1, 7):
print("{}----- {} Number -----{}".format(colors["cian"], c, col... |
class Atm:
def __init__(self,cardNumber,pin):
self.cardNumber = cardNumber
self.pin = pin
def checkBalance(self):
print("Your Balance Is 10,000")
def withdrawl(self,amount):
newAmount = 10000 - amount
print("You Have Withdrawhed: "+str(amount)+" Your ... |
import csv
with open('Demographic_Statistics_By_Zip_Code.csv',newline='')as infile:
data = list(csv.reader(infile))
def get_csv_rowInstance(row_name):
row_instance = []
row_index = data[0].index(row_name)
for row in data[1:]:
row_instance.append(int(row[row_index]))
return row_instance
de... |
import collections
Person = collections.namedtuple("Person", 'name age gender')
P1 = Person(name='Jhon', age=28, gender='남')
P2 = Person(name='Sally', age=28, gender='여')
P3 = Person._make(['Peter', 24, '남'])
P4 = Person._make(['Ary', 23, '여'])
for n in [P1, P2, P3, P4]:
print('%s은(는) %d세의 %s성 입니다.' % n)
... |
def factorial(a):
if a==1:
return 1
else:
return a*factorial(a-1)
b=factorial(3)
print("Factorial of 3 is",b)
|
"""
multiarmed_bandit.py (author: Anson Wong / git: ankonzoid)
Classical epsilon-greedy agent solving the multi-armed bandit problem.
Given a set of bandits with a probability distribution of success, we
maximize our collection of rewards with an agent that explores with
epsilon probability, and exploits... |
import math
class ListNode:
def __init__(self,x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self,l1, l2):
root = ans_ll = ListNode(-math.inf)
carry, val = 0, 0
while l1 or l2 or carry:
val1, val2 = 0, 0
if l1:
... |
import math
class Node:
def __init__(self, val):
self.value = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_val):
new_node = Node(new_val)
new_node.next = self.head
self.head = new_node
class Solution:
... |
from collections import Counter
def palindrome_permutation(s):
d = Counter(s.lower().replace(" ",""))
count = 0
for value in d.values():
if value % 2: count += 1
return count <= 1
def char_number(c):
a = ord('a')
z = ord('z')
A = ord('A')
Z = ord('Z')
val = ord(c)
... |
def is_unique(str):
if len(str) > 128:
return False
is_unique_list = list()
for char in str:
if char in is_unique_list:
return False
else:
is_unique_list.append(char)
return True
string = "dikshaa"
print(is_unique(string))
|
def check_permutation_symetric(str1, str2):
if len(str1) != len(str2):
return False
char_count = [0] * 128
for char in str1:
char_count[ord(char)] += 1
for char in str2:
char_count[ord(char)] -= 1
if char_count[ord(char)] < 0:
return False
re... |
class Animal(object):
def __init__(self, name=None, type=None):
self.name = name
self.type = type
self.timestamp = 0
self.next = None
class AnimalShelter(object):
def __init__(self):
self.cat_head = None
self.cat_tail = None
self.dog_head = None
... |
names = ["karthick", "kaviya", "kavinilaa"]
name1 = "kannan"
for name in names:
print(name)
for n in name1:
print(n) |
import asyncio
from asyncio import StreamReader
from typing import AsyncGenerator
async def read_until_empty(stream_reader: StreamReader) -> AsyncGenerator[str, None]:
while response := await stream_reader.readline():
yield response.decode()
async def main():
host: str = 'www.example.com'
reque... |
import random
cards = [2,3,4,5,6,7,8,9,10]
coloda = []
vzyal = []
chisla = 0
def it():
while True:
i = random.randint(0, 35)
if i not in vzyal:
break
vzyal.append(i)
else:
continue
return i
for row in cards:
for r in range(4):
coloda.append(row)
random.shuffle(coloda)
for row in range(2):
i = rando... |
from logger import Logging
class LoadError(Exception):
""" Raised when an error occurs while loading the config file. """
class BaseConfiguration:
"""
Abstracts the access to the configuration file. This is the base class
to access configuration files. It accepts any parameter key and value.
The... |
def fibo(n):
if n==0:
return 1
elif n==1:
return 1
else:
return fibo(n-1)+fibo(n-2)
def fiboL(n):
fibol=[]
for i in range(0,n+1):
fibol=fibol+[fibo(i)]
return fibol
def redfibo(n):
Fibol=list(fiboL(n))
def reducingMulti(a,b):
return a*b
redFibo=reduce(reducingMulti,Fibol)
return redFibo
|
from random import randint
import time
while True:
x = 0
y = int(input('How many array\'s would you like created?'))
while x < y:
myList = [0, 0, 0]
toChange = randint(0, 2)
if toChange == 0:
myList[0] = 1
if toChange == 1:
myList[1] = 1
if toC... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.