text stringlengths 5 121k |
|---|
def FirstFactorial(num):
num = int(num)
factorial = 1
while num > 1:
factorial = factorial * num
num = num - 1
return factorial
print(FirstFactorial(raw_input()))
|
from tkinter import *
from random import *
class MathQuiz:
def __init__(self, parent):
"""Widgets for frame 1"""
self.frame1 = Frame(parent)
self.frame1.grid(row = 0, column = 0)
self.TitleLabel = Label(self.frame1, bg = "black", fg = "white", width =... |
def solution(X, Y, D):
totalDistance = Y-X
if totalDistance % D == 0:
return totalDistance//D
else:
return totalDistance//D + 1
solution(1,1,3)
|
"""
This file contains utilities for sqlite data access.
"""
import sqlite3
from typing import List, Tuple
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn... |
from turtle import Turtle
from turtle import Screen
import sys
sys.setExecutionLimit(65000)
class Mike(Turtle):
firstname = 'Mike'
def __init__(self, color, speed):
Turtle.__init__(self)
self.shellcolor = color
self.color(color)
self.speed(speed)
def drawAndBack(self, len... |
from util import Stack, Queue
test_ancestors = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)]
def earliest_ancestor(ancestors, starting_node):
q = Queue()
visited = set()
most_recent = []
if has_parents(ancestors,starting_node) is Fa... |
import pyttsx3
import datetime
import pywhatkit as kitty
import speech_recognition as kan
import wikipedia
import webbrowser
jarvis = pyttsx3.init('sapi5')
voices = jarvis.getProperty('voices')
jarvis.setProperty('voice', voices[1].id)
def speak(audio):
jarvis.say(audio)
jarvis.runAndWait()
... |
"""
@Project : StudyPython0-100
@File : map&reduce.py
@Time : 2019-07-11 08:40:54
@Author : indeyo_lin
@Version :
@Remark :
"""
"""
练习题1
利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。
输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']
"""
"""
练习2:
Python提供的sum()函数可以接受一个list并求和,
... |
"""
# @Author : indeyo_lin
# @Time : 2020/6/5 11:01 下午
# @File : most_item_in_list.py
"""
def get_most_in_list(arr: list):
"""
富途笔试题
找出列表中出现次数最多的元素
"""
if not arr:
return -1
count = {}
result = []
for i in arr:
count[i] = arr.count(i)
max_count = max(count.val... |
"""
# @Author : indeyo_lin
# @Time : 2020/5/28 4:20 下午
# @File : insertion_sort.py
"""
def insertion_sort(arr):
if not arr:
return -1
for i in range(1, len(arr)):
current = arr[i]
pre_index = i - 1
while pre_index >= 0 and arr[pre_index] > current:
... |
names = ['kuraki', 'lingbo', 'damon', 'Jordan']
ages = [26, 25, 100, 50]
for name, age in zip(names, ages):
print(name, 'is', age, 'year old')
|
name = ''
while not name or name.isspace():
name = input('Please enter your name: ')
print('Hello, {}!'.format(name))
for number in range(1, 101):
print(number)
|
x = input("Enter a sentence")
x = x.lower()
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_count = {}
for char in x:
if char in alphabet:
if char in letter_count:
letter_count[char] = letter_count[char] + 1
else:
letter_coun... |
import random
def max(alist):
maxnum=0
for i in alist:
if maxnum<i:
maxnum=i
return maxnum
def main():
f=[]
for i in range(100):
f.append(random.randint(0, 1000))
print(max(f))
if __name__=="__main__":
main()
|
deg_f = int(input("What is the temperature in farengeigth? "))
deg_c = (deg_f -32)*5/9
print(deg_f, " degrees Celsius is", deg_c, " degrees Farenheit.")
|
print("Welcome to the Loop Hole!")
print("Today's Manager's Special is :")
print("Donnuts: A traditional jelly donut in which the jelly filling is made entirely of Capn' Crunch Berries Oops All Berries")
num_donuts=int(input("How many do you like?"))
price=float(input("How much would you like to pay per donut 'suggeste... |
def intergerNum(num):
nstring=str(num)
return len(nstring)
print(intergerNum(34))
|
import turtle
tanenbaum = turtle.Turtle()
tanenbaum.hideturtle()
tanenbaum.speed(20)
for i in range(350):
tanenbaum.forward(i)
tanenbaum.right(98)
|
import turtle
wn = turtle.Screen()
norvig = turtle.Turtle()
for i in range(3):
norvig.forward(100)
norvig.left(360/3)
wn.exitonclick()
import turtle
wn = turtle.Screen()
kurzweil = turtle.Turtle()
for i in range(4):
kurzweil.forward(100)
kurzweil.left(360/4)
wn.exitonclick()
import t... |
def is_palindrome(text):
left=0
rigth=len(text)-1
while left<=rigth:
if text[left]==text[rigth] or text=="":
return True
else:
left+=1
rigth+=1
return False
testEqual(is_palindrome('abba'), True)
testEqual(is_palindrome('abab... |
from random import randint
num = randint(1, 6)
print ("Guess a number between 1 and 6")
answer = int(raw_input())
if answer==num:
print ("you guess the number")
elif num<answer:
print ("your number is less than the random #")
elif num>answer:
print("your number is bigger than the random #")
|
def insertion_sort(arr):
"""Sorts the list in-place using Bubble Sort algorithm.
:param arr: The array.
>>> arr = [1, 2, 3]
>>> insertion_sort(arr)
>>> print(arr)
[1, 2, 3]
>>> arr = [3, 2, 5, 4, 4, 0]
>>> insertion_sort(arr)
>>> print(arr)
[0, 2, 3, 4,... |
a = 50
b = 8
print("the remainder when a is divided by b is :", a%b) |
for i in range(10):
print(i)
x = [i for i in range(10)]
print(x)
list_ = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', ]
y = {i: list_[i] for i in range(len(list_))}
print(y)
z = dict(enumerate(list_))
print(z)
a = 42
b = list(a + i for i in range(10))
print(b)
c = 42
d = [a + i for i in range(10)]
... |
import time
ticks = time.time()
print("Ticks since epoch:", ticks)
timenow = time.localtime(time.time())
print("Current time :", timenow)
timenow = time.localtime(time.time())
print("Year:", timenow[0])
print("Month:", timenow[1])
print("Day:", timenow[2])
timenow = time.asctime(time.localtime(time.time()))
p... |
def dog_sound():
return 'hau hau'
def cat_sound():
return 'Me au'
def horse_sound():
return 'R R R R'
def cow_sound():
return 'M U U U'
def no_sound():
return "Total silence"
switch = {
'dog': dog_sound,
'cat': cat_sound,
'horse': horse_sound,
'cow': cow_sound,
}
... |
import math
def pythagoras(a, b):
value = math.sqrt(a * a + b * b)
return value
def fib(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end=" ")
a, b = b, a + b
print()
fib(200000)
def fib2(n):
a,... |
n=int(input("Enter a number-I"))
def fizzbuzz(n):
if (n%3==0 and n%5==0):
print(str(n)+"=Fizz Buzz")
elif (n%3==0):
print(str(n)+"=Fizz")
elif (n%5==0):
print(str(n)+"=Buzz")
else:
print(str(n)+"=Not Fizz or Buzz")
fizzbuzz(n)
|
""" Alarm Clock.
"""
import datetime
def ring():
print('Beep')
user_input_hour = int(input('Enter Hour'))
user_input_minutes = int(input('Enter minutes'))
beep = True
while beep:
now = datetime.datetime.now()
print(now.hour, now.minute, now.second)
if user_input_hour == now.hour and user_input_minutes == now.mi... |
""" Reverse a string.
"""
if __name__ == '__main__':
string = input('Please enter string ')
print(string[::-1]) |
"""
Sieve of Eratosthenes.
1. Generate numbers to the limit.
2. Start with 2, eliminate multiples of 2.
3. Proceed to next number (3), eliminate multiples of 3
4. Keep looping until p2 > n.
"""
userInput = int(input('Please enter the upper limit'))
def primes_sieve2(limit):
a = [False] * 2 + [True] * (limit-2) ... |
""" Pig Lating Conversion
"""
def convert_to_pig_latin(word):
""" Returns the converted string based on the
rules defined for Pig Latin.
"""
vowels = ['a', 'e', 'i', 'o', 'u']
char_list = list(word)
""" Vowel Rule.
"""
if char_list[0] in vowels:
resultant_word = word + 'way'
""" Consonant Rule.
"""
... |
import random
game_in_progress = True
x_char = 'X'
o_char = 'O'
space_char = ' '
board = [space_char, space_char, space_char,
space_char, space_char, space_char,
space_char, space_char, space_char]
player_character = ''
computer_character = ''
def drawBoard(data):
print("""
1 |2 |3
%s | %s | %s
| ... |
import cv2
import numpy as np
img = np.zeros((512,512,3), np.uint8)
cv2.line(img,(0,0), (300,300), (0, 255, 0), 3)
cv2.rectangle(img, (0,0), (250, 350), (0,0,255), 2, cv2.FILLED)
cv2.circle(img, (400, 200), 30, (255, 255, 0), 2)
cv2.putText(img, "OpenCV ROCKS!", (200, 100), cv2.FONT_HERSHEY_DUPLEX, 1,... |
fhand = open("therepublic.txt")
count = 0
def find_a_word(fname, key_word):
for line in fhand:
if line.lower().startswith(key_word):
count = count + 1
return count
find_a_word("therepublic.txt", "plato")
print(key_word + " showed up " + str(count) + " times in " + fname)
|
try:
fname = input('Enter file name: ')
fhand = open(fname)
readfile = fhand.read()
words = readfile.split()
for word in words:
if words.count(word) == 1:
uniqueWords = []
uniqueWords.append(word)
print(uniqueWords)
except:
print('Invalid Input for fi... |
import re
from typing import Tuple
_whole_word = lambda x: re.compile(r"\b{}\b".format(x))
_date_iso8601_pat = _whole_word(r'(\d{4})-(0\d|1[0-2])-(0[1-9]|[12][0-9]|3[01])')
_date_month_word_pat = _whole_word(r'(\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4})');
_mixed_ordinal_pat = _whole_word(r'-?\d... |
"""
Advent of Code 2018. Day 4
Usage:
day4.py part1
day4.py part2
day4.py test
"""
from docopt import docopt
PART1_SOLUTION = 337
PART2_SOLUTION = 231
def load_input_data():
with open("input") as f:
return [line.strip() for line in f]
def part1():
passphrases = load_input_data()
va... |
def subnet_binary(s):
""" Takes a slash notation subnet and calculates the
number of host addresses """
if s[0] == "/":
a = int(s.strip("/"))
else:
a = int(s)
addresses = (2**(32-a))
return addresses
s = input("Enter your slash notation. Use a number or a slash (/27... |
def triMultiply(num):
for i in range(1, int(num/2)):
for j in range(i, int(num/2)):
if i**2 + j**2 == (num-(i+j))**2:
return i*j*(num-(i+j))
return False
print(triMultiply(1000))
|
num=int(input("enter the number:"))
i=1
sum=0
while(i<=5):
sum=sum+num
print(sum)
i=i+1
|
a = int(input())
b = int(input())
n = int(input())
cost = n * (100 * a + b)
print(cost // 100, cost % 100)
|
def print_star():
print((" " * (space_count / 2)) + "*" * star_count + (" " * (space_count / 2)))
total_width = 10
star_count = 1
space_count = total_width - star_count
loop_count = 1
while loop_count <= 10:
if star_count % 2 == 1:
print_star()
star_count += 1
space_count -= 1
loop_count +=... |
def print_top(num):
print("*" * num)
def print_bottom(num):
print("*" * num)
def print_middle(message):
print("*" + " " + message + " " + "*")
text = raw_input("What will the banner say? ")
width = len(text) + 4
print_top(width)
print_middle(text)
print_bottom(width) |
def latest(scores):
return scores[-1]
def personal_best(scores):
return max(scores)
def personal_top_three(scores):
top_scores = [0]*min(len(scores),3)
for score in scores:
for top_score in top_scores:
if score > top_score:
idx = top_scores.index(top_score)
top_scores.insert(idx, score)
top_sco... |
class Solution:
"""
@param nums: an integer array
@param low: An integer
@param high: An integer
@return: nothing
"""
def partition2(self, nums, low, high):
if not nums:
return
start, end = 0, len(nums) - 1
while start <= end:
while s... |
grid = [
["G", "G", "B", "R"],
["G", "B", "R", "B"],
["R", "B", "B", "B"]
]
highest = {
"color": "",
"count": 0
}
iterated = {}
def main():
for row in range(len(grid) - 1):
for col in range(len(grid[row]) - 1):
if "R" + str(row) + "C" + str(col) in iterat... |
"""
Created on Mon May 18 21:56:49 2020
@author: Jorge
"""
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
dataset = pd.read_csv('./resturantData.csv')
population = dataset.i... |
"""
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it
returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. There is no restriction on how your
encode/decode algorithm should work. You j... |
"""
24. Swap Nodes in Pairs
Medium
1720
152
Add to List
Share
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
"""
class... |
"""
In a town, there are N people labelled from 1 to N. There is a rumor that one
of these people is secretly the town judge.
If the town judge exists, then:
The town judge trusts nobody.
Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies properties 1 and 2.
You... |
"""
Given a matrix A, return the transpose of A.
The transpose of a matrix is the matrix flipped over it's main diagonal,
switching the row and column indices of the matrix.
"""
class Solution:
def transpose(self, A: List[List[int]]) -> List[List[int]]:
res = []
for i in range(len(A[0])):
... |
"""
Given an array of integers, return indices of the two numbers such that they add up
to a specific target.
You may assume that each input would have exactly one solution, and you may not use
the same element twice.
"""
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
... |
def conv(my_string, seperator):
var = [my_string[0].lower()]
for x in my_string[1:]:
if x in ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
var.append(seperator)
var.append(x.lower())
else:
var.append(x)
return ''.join(var)
my_string = 'ThisIsCamelCased'
print(co... |
import argparse
class StoreDictKeyPair(argparse.Action):
"""Action that can parse a python from comma-separated key-value pairs passed to the parser."""
def __call__(self, parser, namespace, values, option_string=None):
"""Parses comma-separated key-value pairs passed to the parser into a dict, addin... |
from pathlib import Path
def rambunctious_recitation(starting_numbers_path: Path, num_turns: int) -> None:
with open(starting_numbers_path) as file:
starting_numbers = [int(number) for number in file.read().split(",")]
numbers = {number: turn for turn, number in enumerate(starting_numbers[:-1], 1)}
... |
'''
https://practice.geeksforgeeks.org/problems/is-binary-number-multiple-of-3/0
'''
while(n>0):
s=input()
k=0
g=len(s)
odd=0
even=0
for i in range(g-1,-1,-1):
j=g-1-i
if(s[i]=='1'):
if(j%2==0):
odd=odd+1
else:
even=even+1
... |
class Matchup:
def __init__(self, winner_name, winner_seed, loser_name, loser_seed):
self.winner_name = winner_name
self.winner_seed = winner_seed
self.loser_name = loser_name
self.loser_seed = loser_seed
class Tier:
def __init__(self, number):
self.number = number
self.matchups = []
def addMa... |
def about_books(author_name,**var):
list_1 = [var]
print(list_1)
for el in list_1:
for elem in el:
if el[elem][0] == author_name:
print(elem,el[elem][1])
about_books('dyuma',askanio = ('dyuma',1965),sherlock = ('conan doyle',1887),thrones=('martin ge... |
a = [[10,9,6,3,7],
[6,10,2,9,7],
[7,6,3,8,2],
[8,9,7,9,9],
[6,8,6,8,2]]
i = -1
j = 0
new_a = []
def rotateImage(a):
global i,j,new_a
if j >= len(a):
return new_a
row = []
while abs(i) <= len(a):
row.append(a[i][j])
i -= 1
new_a.append(row)
j += 1
... |
list_1 = [9,5,8,5,20,1,2,-3,-2,-1,0]
list_1.sort()
list_1.reverse()
list_2 = list_1[0:3]
list_3 = list_1[len(list_1)-2:len(list_1)]
list_3_count=1
for el in list_3:
list_3_count *= el
list_3_count *=list_1[0]
list_2_count = 1
for elem in list_2:
list_2_count*=elem
if list_3_count > list_2_count:
print(list_... |
class Employee:
company='Collins'
def __init__(self,name,dept):
self.name=name
self.dept=dept
def showDetails(self):
print(f"Employee Name: {self.name}")
print(f"Departmet: {self.dept}")
def showComputerType(self):
print("PC/Laptop")
class Developer(Emp... |
num=[23,56,72,7]
if num[0]>num[1]:
c1=num[0]
else:
c1=num[1]
if num[2]>num[3]:
c2=num[2]
else:
c2=num[3]
if c1>c2:
greatest = c1
else:
greatest=c2
print("Greatest Number is",greatest)
|
y=int(input("Enter number of Row (Odd number between 7 and 101: "))
x=y*3
count=3
fill='.|.'
for i in range(y):
if i<y//2:
print('-'*((x-count)//2)+fill*(2*i+1)+'-'*((x-count)//2))
count +=6
filltemp=2*i+1
elif i==y//2:
print('-'*((x-7)//2) + 'WELCOME' + '-'*((x-7)//2))
else:... |
import cv
def MedianFilter(image):
w = image.width
h = image.height
size = (w,h)
iMFilter = cv.CreateImage(size,8,1)
for i in range(h):
for j in range(w):
if i in [0,h-1] or j in [0,w-1]:
iMFilter[i,j] = image[i,j]
else:
a= [0]*9
... |
def isPhonenumberIN(num):
if len(num) != 13 :
return False
if num[0:3] != "+91":
return False
if not num[3:13].isdecimal():
return False
return True
message = "On my wall i found some writen number +918108855425 and 913215854512"
for i in range(len(message)):
part = message[... |
import re
isPhoneIn = re.compile(r'(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}')
mo = isPhoneIn.search("wall det +917894561230")
print("Phone number found: "+mo.group()) |
import string
def create_password_checker(min_uppercase, min_lowercase, \
min_punctuation, min_digits):
"""Function to return that checks pw for complexity rules"""
def checker(pw):
rules_dict = {}
digit_cntr = upper_cntr = lower_cntr = punc_cntr = 0
... |
def decodeHuff(root, s):
result=""
current=root
for i in s:
if int(i)==0:
current=current.left
else:
current=current.right
if current.left==None and current.right==None:
result+=current.data
current=root
print(result)
|
board = ["1","2","3",
"4","5","6",
"7","8","9"]
def play_game():
winner="continue"
current_player=choice()
display_board()
while(winner=="continue"):
ask_input(current_player)
display_board()
winner=check_winner(current_player)
if(winner!="continue"):
break
current_player=flip_play... |
from typing import List
def getIndexToIns(arr: List, num: int) -> int:
for i in range(len(arr) - 1):
for j in range(len(arr) - i -1):
if arr[j + 1] < arr[j]:
tmp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = tmp
for i in range(len(a... |
class BankAccount:
def __init__(self, int_rate, balance):
self.interest = int_rate
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
self.balance -= amount
re... |
"""
script to calculate how many years it will take to reach a better salary
s1 - current (lower) salary
s2 - future/wanted/promissed salary
i1 - yearly salary increase for the current salary (%)
i2 - yearly salary increase at the other company that you are thinking of going (%)
"""
s1 = 500
s2 = 800
i1 = 5
i2 = 2
... |
def gen(n):
for i in range(n):
if i % 2 == 0:
yield i
x = 5
g = gen(x)
while True:
try:
print(next(g))
except StopIteration:
break
|
import random
import time
def insertion_sort(mylist, ascending=True):
tic = time.perf_counter()
for i in range(1, len(mylist)):
current = mylist[i]
while True:
ascending_sort = i > 0 and mylist[i - 1] > current and ascending
descending_sort = i > 0 and mylist[i - 1... |
import math
def toFixed(numObj, digits=0):
return f"{numObj:.{digits}f}"
def d(point1, point2):
x1 = point1[0]
x2 = point2[0]
y1 = point1[1]
y2 = point2[1]
return math.sqrt((x2-x1)**2 + (y2 - y1)**2)
sum = 0
pi = math.pi
N, R = map(float, input().split())
points = list()
for _ in range(int... |
grades = []
for i in range(int(input())):
grades.append(int(input()))
if 3 in grades:
print('None')
elif sum(grades)/len(grades) == 5:
print('Named')
elif sum(grades)/len(grades) >= 4.5:
print('High')
else:
print('Common')
|
import re
string = input()
num = re.findall('(\d+)', string)
letter = re.findall('[A-Za-z]', string)
if int(num[0]) <= 2:
if letter[0] in ('A', 'D'):
print('window')
else:
print('aisle')
elif int(num[0]) <= 20:
if letter[0] in ('A', 'F'):
print('window')
else:
print... |
def findPal(string):
def findOdd(string):
max = 1
for Middle in range(len(string)):
leftBorder = Middle - 1
rightBorder = Middle + 1
while (leftBorder >= 0 and rightBorder < len(string) and string[leftBorder] == string[rightBorder]):
new_str = stri... |
import math
ad, ac, bd, bc = map(int, input().split())
if ad*ac == bd*bc:
print('Impossible.')
exit(0)
t1 = (ad**2+ac**2)*2.0*bd*bc-(bd**2+bc**2)*2.0*ad*ac
t2 = 2*bd*bc-2*ad*ac
tt = t1*1.0/t2
if tt < 0:
print('Impossible.')
else:
tt = math.sqrt(tt)
print("Distance is %(tt).0lf km." % {"tt": tt*1... |
strin1 = input()
strin = int(strin1)
numberleft = strin-1
numerright = strin+1
strleft = str(numberleft)
strright = str(numerright)
if len(strin1) != len(strleft):
strleft = strleft.rjust(6, '0')
if len(strin1) != len(strright):
strright = strright.rjust(6, '0')
left = []
right = []
left1 = []
right1 = []
fo... |
def sieve_of_eratosthenes(n):
list = []
for i in range(0, n):
for j in range(0,i):
if i % j == 0:
break
list.append(i)
return list
a = int(raw_input("Enter a number | ex: 5"))
sieve_of_eratosthenes(a) |
import numpy as np
import pandas as pd
'''
the math behind pd.dataframe.cov() and pd.dataframe.corr()
'''
def covariance_try(x,y):
'''
INPUT: a numpy array or pandas scalar
Return: the covariance of the data
'''
cov = 0
x_mean = x.mean()
y_mean = y.mean()
'''
for ind in ... |
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
result = []
if(len(nums)<3):
return result
if(nums[-1] < 0):
return result
if(nums[0] > 0):
... |
from typing import List
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
h = 0
end = len(A)-1
temp = 0
j=0
i=0
while i < end:
if A[i] %2 != 0:
temp = A[i]
j = i+1
while j <=end:
... |
def modInverse(a, m) :
a = a % m;
for x in range(1, m) :
if ((a * x) % m == 1) :
return x
return 1
def addition(x1, y1, x2, y2, field):
xd = (x2 - x1)
xf = modInverse(xd, field)
slope = (y2 - y1) * xf
slope = slope % field
xnew = (slope * slope - x1 - x2) % field
ynew = (-y1 + slope * (x1 - xnew)) % fiel... |
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if strs==[]:
return ""
res=""
min_len=min([len(word) for word in strs])
for i in xrange(min_len):
... |
class Solution(object):
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
low=1
high=n
num=(low+high)/2
while guess(num)!=0:
if guess(num)<0:
high=num
num=(low+high)/... |
class Solution(object):
def projectionArea(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
top=0
front=0
side=0
tgr... |
class Solution(object):
def maxValue(self, strs):
strs_len=len(strs)
maxv=-1
for i in xrange(strs_len):
v=int(strs[i])
if maxv<=v:
maxv=v
maxi=i
return maxv, maxi
def maximumSwap(self, num):
... |
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
sl=[]
for word in s.split(' '):
wordl=[]
for i in xrange(len(word)-1,-1,-1):
wordl.append(word[i])
sl.ap... |
"""
How To Dialog Box class for tkinter application.
Created on 19 Apr 2020
@author: semuadmin
"""
from tkinter import Toplevel, Label, Button, LEFT
from webbrowser import open_new_tab
from .strings import HELPTXT, COPYRIGHTTXT, DLGHOWTO, GITHUBURL
class HowtoDialog:
"""
How To dialog box class
"""
... |
import sys
def start(maze_input_file, current_health):
maze = []
for i in maze_input_file:
maze.append(list(i.split()[0]))
sol = [[0 for j in range(len(maze[i]))] for i in range(len(maze))]
x, y = 0, 0
for i in maze:
if "S" in i:
x, y = (maze.index(i),... |
from itertools import combinations
def print_powerset(string):
for i in range(0,len(string)+1):
for element in combinations(string,i):
print(''.join(element))
string=['a','b','c']
print_powerset(string) |
def ans1():
count = 0
r = 0
c = 0
while r + 1 < len(G):
r += 1
c += 3
if G[r][c % len(G[r])] == "#":
count += 1
return count
def ans2():
count = 0
slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
ans = 1
for (dc, dr) in slopes:
c = 0
... |
from init_db import CreateShapesDB
import shapes
class PrettyPrint():
def __init__(self):
self.db = CreateShapesDB()
self.sortedShapes = sorted(self.db.data, key=self.getKey)
self.shape_counts = {'circle':0, 'square':0, 'triangle':0}
self.shape_objects = ... |
def count(arr,lis):
arr1=list()
for j in range(1,len(arr)):
if arr[j]>arr[0]:
arr1.append(lis[j-1])
else:
arr1.append(0)
return max(arr1)
arr = list()
n = int(input("how many no. you want to enter : "))
lis = [0]*n
print("enter numbers : ")
for i in range(n):
arr.append(int(input()))
for i in rang... |
import numpy as np
import scipy.signal
from scipy.signal import fftconvolve as convolve
class ConvLayer():
"""
2D convolutional layer.
This layer creates a convolution kernel that is convolved with the layer
input to produce a tensor of outputs.
Arguments:
in_channels:... |
num=int(input("Enter Number: "))
factorial=1
if num<1:
print("Factorial is not available for negative number:")
elif num==0:
print("factorial of 1 is zero: ")
else:
for i in range(1,num+1):
factorial=factorial*i
print("factorial of",num,"is",factorial) |
t = 0
while t <= 50:
a= int(input ('add number: '))
t = t + a
j= str (t)
print ('the total is' + j)
else:
print('the total is more than the 50')
n=0
while n<=5:
n=int(input('Enter a number:'))
print('The last number you entered was a ' + n)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.