blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
d92501ce4a18e290730d186094a9432691fe50a2 | OctavioRey/algoritmos_octaviorey | /TP_1.py | 2,238 | 3.875 | 4 | # Ejercicio 8
# def decimal_a_binario(numero):
# if numero == 0:
# return ""
# else:
# return decimal_a_binario(numero // 2) + str(numero % 2)
# print (decimal_a_binario(28))
# Ejercicio 5
# Valores = {"": 0, "M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1}
# def romano_a_decimal(romano):
# if romano in Valores:
# return Valores[romano]
# primero, segundo = map(romano_a_decimal, romano[:2])
# if primero < segundo:
# return segundo - primero + romano_a_decimal(romano[2:])
# else:
# return primero + romano_a_decimal(romano[1:])
# print (romano_a_decimal('IV'))
# Ejercicio 22
# datos = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# mochila = ['Pan', 'Capa', 'Sable de luz', 'otro']
# def usar_fuerza(mochila, pos):
# if(pos< len(mochila)):
# if(mochila[pos] == 'Sable de luz'):
# return print('El Sable de luz se encuentra en la mochila, la cantidad de objetos que se sacó fue: ' ,pos)
# else:
# return usar_fuerza(mochila, pos+1)
# else:
# return -1
# print(usar_fuerza(mochila, 0))
# Ejercicio 23
# def salida_laberinto(matriz, x, y, caminos=[]):
# """Salida del laberinto."""
# if(x >= 0 and x <= len(matriz)-1) and (y >= 0 and y <= len(matriz[0])-1):
# if(matriz[x][y] == 2):
# caminos.append([x, y])
# print("Saliste del laberinto")
# print(caminos)
# caminos.pop()
# elif(matriz[x][y] == 1):
# matriz[x][y] = 3
# caminos.append([x, y])
# # print("mover este")
# salida_laberinto(matriz, x, y+1, caminos)
# # print("mover oeste")
# salida_laberinto(matriz, x, y-1, caminos)
# # print("mover norte")
# salida_laberinto(matriz, x-1, y, caminos)
# # print("mover sur")
# salida_laberinto(matriz, x+1, y, caminos)
# caminos.pop()
# matriz[x][y] = 1
# lab = [[1, 1, 1, 1, 1, 1, 1],
# [0, 0, 0, 0, 1, 0, 1],
# [1, 1, 1, 0, 1, 0, 1],
# [1, 0, 1, 1, 1, 1, 1],
# [1, 0, 0, 0, 0, 0, 0],
# [1, 1, 1, 1, 1, 1, 2]]
# salida_laberinto(lab, 0, 0) |
e0beb0c0bef556738aeb16ad27d63db70a42b974 | SwarajyaRBhanja/Learn_PythonBasics | /conditionalStatement.py | 414 | 3.78125 | 4 | a= int(input("Please enter your age: "))
if(a>21 and a<60):
print("You can work with us")
else:
print("You are not eligible to work with us")
print("Thanks for applying")
a= None
if(a is None): #Yes. will check for object reference
print("Yes")
else:
print("No")
if(a==None): #Will check for object value
print("Yes")
else:
print("No")
x= [5,6,7]
print(6 in x) #True |
04f66c2429a8bad301e6828637de1f3f3ef4b970 | cameron-teed/ICS3U-3-01-PY | /adding.py | 505 | 4.125 | 4 | #!usr/bin/env python
# Created by: Cameron Teed
# Created On: September 2019
# This program adds two numbers together
def main():
# This program adds two numbers together
# Input
first_number = int(input("enter the first number: "))
second_number = int(input("enter the second number: "))
# Procces
sum_ = first_number + second_number
# Output
print("")
print("The sum of {} + {} = {}".format(first_number, second_number, sum_))
if __name__ == "__main__":
main()
|
c7a13944c8ad37075e06fd0d6873b30b5791e70b | Bismoy943/STA_Assigns_Bismoy | /W01D04/1.py | 65 | 3.515625 | 4 | name=input("Please enter your name:")
print("Entered Name:",name) |
91044fc3d09d2bc85a1d1cee5c37612cbcb1ec1a | BruceHi/leetcode | /month12/exchange.py | 493 | 3.6875 | 4 | # 剑指 offer 21.调整数组顺序使奇数位于偶数前面
from typing import List
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
i = 0
for j, num in enumerate(nums):
if num & 1:
nums[i], nums[j] = num, nums[i]
i += 1
return nums
s = Solution()
nums = [1,2,3,4]
print(s.exchange(nums))
nums = [1]
print(s.exchange(nums))
nums = []
print(s.exchange(nums))
nums = [2]
print(s.exchange(nums))
|
ab90375fbb053c5fa8c21b8105ddeff271ae3272 | NicolaCVL/beginners_programming | /Exos/BasePython.py | 7,218 | 3.953125 | 4 | #############################################
######### PREMIER PAS SUR PYTHON ############
#############################################
#EXERCICE 8
# Définir 2 variables : 1 contenant un age en nombre et l'autre contenant votre prénom.
# Créez une troisième variable qui devra contenir la phrase suivante : "Je suis [NOM] et j'ai [AGE] ans."
# Enfin, afficher cette dernière variable
# age = 22
# prenom = "nicola"
# t = "je suis", prenom, "et jai", age, "ans"
# print(t)
# c = "freddy"
# print(c)
#t = 1
#x = 2
#print(p * 4)
#print (p + 1)
#print (p + t)
#print (p - 1)
#print (p - t)
#p = 5
#print (p * 2)
#print (p * x)
#print (p / 2)
#print (p / x)
#EXERCICE 9
# a = 3
# b = 8
# c = a
# a = b
# b = c
# print(a, b, c)
#EXERCICE 11
# a = 10
# print(a)
# print(a / 2)
# print(a // 2)
# print(a % 2)
# print(a^3)
#EXERCICE 12
#pht = int(input("Entrer le prix :"))
#art = int(input("Entrer le nombre d'article :"))
#tva = 1.2
#Prixfinal = (pht * art) * tva
#print(Prixfinal)
#############################################
############### LES LISTES ##################
#############################################
#EXERCICE 13/14
# list = [4, 5, "fred"]
# list.append("yop")
# print(list[3])
# print(type(list[3]))
#EXERCICE 15
#list1 = [1,2,3,4]
#list2 = [5,7,8,9]
#list3 = list1 + list2
#print(list3)
#EXERCICE 16
# list = [0,1,2,3,4,5,6,7,8,9]
# mini = min(list)
# maxi = max(list)
# somme = sum(list)
# tot = 0
# longueur = len(list)
# print(list)
# Perso = {
# "Vie" : 10,
# "Mana" : 20,
# "Attaque" : 100,
# "Defense" : 50
# }
# print(Perso)
# def maximum(list):
# max = list[0]
# longueur = len(list)
# for Compt in range (longueur):
# if list[Compt] >= max:
# maxi = list[Compt]
# return max
# for i in list:
# tot = tot + i
# tot
# del list[1]
# max(list)
# min(list)
# print(Perso["Vie"])
# print(list[3])
# print(list[3:5])
# print(list[2:8:2])
# print(len(list))
# print(maxi)
# print(mini)
# print(somme)
# print("le total est", tot)
# print(list)
#list2 = ["ok", 4, 2,78, "bonjour"]
#list2[1] = "toto"
#print(list2)
# list3 = [0,1,2,3,4,5]
# V = (0,1,2,3,4,5)
# list4 = [V]
# print(list3,list4)
#EXERCICE 18
# list5 = []
# for i in range (0, 6):
# list5 += [i]
# print(list5)
#############################################
################LES DICTIONNAIRES############
#############################################
#EXERCICE 19
#Dico = {
# "key" : "valeur",
# "key2": "valeur2"
# }
#Dico["titi"] = "toto"
#Dico["tata"] = Dico["titi"]
#del Dico["titi"]
#V = Dico["key"]
#del Dico["key"]
#Dico2 = {
# "Dico1" : Dico
# }
#print(V)
#print(Dico)
#print(Dico2)
#############################################
######LISTES, DICTIONNAIRES, TUPLES##########
#############################################
#EXERCICE 20
# x = 1
# y = 2
# Tup = [("x", "y") , ("x", "y") ,("x","y"),("x", "y")]
# Tup.append("a")
# Tup.extend("b")
# Tup2 = [(1,2,3)]
# Tup.extend(Tup2)
# Tup3 = Tup + Tup2
# Tup[3] = 2
# Tup3 = Tup2
# print(Tup3)
# print(Tup)
# print(Tup3)
# del Tup2[:]
# print(Tup2)
#############################################
############### LES TESTS ###################
#############################################
#EXERCICE 1
#A = int(input("Entrer le premier nombre :"))
#B = int(input("Entrer le deuxieme nombre :"))
#C = A * B
#if C > 0:
# print("Positif")
#elif C < 0 :
# print("Negatif")
#else :
# print("Nul")
#EXERCICE 2
#Age = int(input("Entrer votre age :"))
#if Age >= 18:
# print("Vous etes majeur !")
#elif Age < 18 :
# print("Vous n'etes pas majeur...")
#A = int(input("Entrer un nombre :"))
#if A > 5 and A < 10 : # Si A est compris entre 5 et 10 (10 exclus)
# print(A > 5 and A < 10)
#else :
# print("False")
#if A > 5:
##if A < 10.5:
### print("True")
#### else:
#####print("False")
#else:
# print("True")
#############################################
############## LES BOUCLES ##################
#############################################
# EXERCICE 1
# créez une boucle for qui affiche les numéros de 0 à 5
# for compt in range(0, 6):
# print(compt)
# for compt in (v):
# print(compt + "*")
##EXERCICE 3
# Soit la variable x = "anticonstitutionnellement".
# A l'aide d'une boucle for, afficher les lettres présentes dans x.
# for test in v:
# print("longueur de la chaine", test, '=', len(test))
# list2 = "anitconstitutionnellement"
# index2 = 0
# AntiC = list2
# for compt2 in (AntiC):
# print(compt2 + "*")
# EXERCICE 10
# Grâce à la liste suivante : ordi = ["apple", "asus", "dell", "samsung"],
# utilisez la boucle While pour afficher toutes les marques d'ordinateur
# P = "Apple"
# F = "Asus"
# C = "Dell"
# S = "Samsung"
# index = 0
# list = [P,F,C,S]
# v = list
#EXERCICE 10
# while index < len(v):
# print(list[index])
# index += 1
#EXERCICE 11
# text = input("Ecrire un mot : ")
# while text != "exit":
# text = input("Ecrire un mot : ")
# print(text)
#EXERCICE 12
# v = 0
# while v <= 100:
# print(v)
# v += 5
#############################################
############## LES FONCTIONS ################
#############################################
#EXERCICE 1
# def multi(x, ):
# return x*5
# T = int(input("Donner un nombre : "))
# x = T
# a = multi(T,)
# print(a)
#EXERCICE 2
#list = [2,1,54,83,108,97,7]
# list2 = []
# a = 0
# max = 5
# print(list2)
# print(a)
# list2 = [max]
# while a < max :
# b = int(input("Entrer un nombre : "))
# list2.append(b)
# a += 1
# print(list2)
# def nombres(list2):
# for i in range (0, len(list2)):
# if list2[i] % 2 == 0:
# print(list2[i])
# if list2[i] % 2 != 0:
# list2.remove[i]
# nombres(list2)
# print(b)
# print(list2)
# def paires (list2):
# paires (list2)
# print(a)
# print(v)
# print(list2)
# for i in range (0, len(list2):
# if list2[i] % 2 == 0:
# print (list2[i])
# nombre = [2, 5, 14, 16, 159, 198]
# def paires (nombre):
# for i in range (0, len(nombre)):
# if nombre[i] % 2 == 0:
# print (nombre[i])
# paires (nombre)
#EXERCICE 3
# def fibo(x, n+x)
# import random
# list2 = []
# a = 0
# max = 25
# u = 0
# n = random.randint(1, 100)
# list2 = [n]
# while a < n :
# b = random.randint(0, n+1)
# list2.append(b)
# a += 1
# def nombres(list2):
# for i in range (0, len(list2)):
# if list2[i] % 2 == 0:
# print(list2[i])
# else:
# break
# nombres(list2)
# print(b)
# print(list2)
# def paires (list2):
# paires (list2)
# def mult(nb):
# print(nb*5)
# print("Quel est votre nombre?")
# a=int(input())
# mult(a)
# def nbp(nb):
# if(nb%2==0):
# print("pair")
# else:
# print("pas pair")
# nbp(8)
# s1=1
# s2=1
# s3=0
# while s3<50:
# s3=s1+s2
# s1=s2
# s2=s3
# print(s2)
# mot=input("Entrer un mot : ")
# liste_voyelles=["a","e","i","o","u","y"]
# nb_voyelles = 0
# for lettre in mot :
# if lettre in liste_voyelles :
# nb_voyelles+=1
# print(nb_voyelles)
# nbr = int(input('Entrez un nombre : '))
# fact = 1
# for i in range(1, nbr+1):
# fact = fact * i
# print (nbr,'! = ',fact)
|
014a9248e8ee1f9f01c5b6ddd0de856d06c8a903 | Aasthaengg/IBMdataset | /Python_codes/p02859/s991609034.py | 217 | 3.59375 | 4 | # coding: utf-8
import sys
def main(argv=sys.argv):
r = int(input())
pai = 3
times = (r ** 2 * pai) // (1 ** 2 * pai)
print(times)
return 0
if __name__ == '__main__':
sys.exit(main())
|
dfb480d363a473d585c655bc3865be24a5483745 | i-aditya-kaushik/geeksforgeeks_DSA | /Matrix/Codes/boundary_traversal.py | 3,554 | 4.28125 | 4 | """
Boundary traversal of matrix
You are given a matrix A of dimensions n1 x m1. The task is to perform boundary traversal on the matrix in clockwise manner.
Input:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase two lines of input. The first line contains dimensions of the matrix A, n1 and m1. The second line contains n1*m1 elements separated by spaces.
Output:
For each testcase, in a new line, print the boundary traversal of the matrix A.
Your Task:
This is a function problem. You only need to complete the function boundaryTraversal() that takes n1, m1 and matrix as parameters and prints the boundary traversal. The newline is added automatically by the driver code.
Constraints:
1 <= T <= 100
1 <= n1, m1<= 30
0 <= arri <= 100
Examples:
Input:
4
4 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
3 4
12 11 10 9 8 7 6 5 4 3 2 1
1 4
1 2 3 4
4 1
1 2 3 4
Output:
1 2 3 4 8 12 16 15 14 13 9 5
12 11 10 9 5 1 2 3 4 8
1 2 3 4
1 2 3 4
Explanation:
Testcase1: The matrix is:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
The boundary traversal is 1 2 3 4 8 12 16 15 14 13 9 5
Testcase 2: Boundary Traversal will be 12 11 10 9 5 1 2 3 4 8.
Testcase 3: Boundary Traversal will be 1 2 3 4.
Testcase 4: Boundary Traversal will be 1 2 3 4.
** For More Input/Output Examples Use 'Expected Output' option **
Output:
For each testcase, in a new line, print the boundary traversal of the matrix A.
Your Task:
This is a function problem. You only need to complete the function boundaryTraversal() that takes n1, m1 and matrix as parameters and prints the boundary traversal. The newline is added automatically by the driver code.
Constraints:
1 <= T <= 100
1 <= n1, m1<= 30
0 <= arri <= 100
Examples:
Input:
4
4 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
3 4
12 11 10 9 8 7 6 5 4 3 2 1
1 4
1 2 3 4
4 1
1 2 3 4
Output:
1 2 3 4 8 12 16 15 14 13 9 5
12 11 10 9 5 1 2 3 4 8
1 2 3 4
1 2 3 4
Explanation:
Testcase1: The matrix is:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
The boundary traversal is 1 2 3 4 8 12 16 15 14 13 9 5
Testcase 2: Boundary Traversal will be 12 11 10 9 5 1 2 3 4 8.
Testcase 3: Boundary Traversal will be 1 2 3 4.
Testcase 4: Boundary Traversal will be 1 2 3 4.
Output:
For each testcase, in a new line, print the boundary traversal of the matrix A.
Your Task:
This is a function problem. You only need to complete the function boundaryTraversal() that takes n1, m1 and matrix as parameters and prints the boundary traversal. The newline is added automatically by the driver code.
Constraints:
1 <= T <= 100
1 <= n1, m1<= 30
0 <= arri <= 100
Examples:
Input:
4
4 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
3 4
12 11 10 9 8 7 6 5 4 3 2 1
1 4
1 2 3 4
4 1
1 2 3 4
Output:
1 2 3 4 8 12 16 15 14 13 9 5
12 11 10 9 5 1 2 3 4 8
1 2 3 4
1 2 3 4
Explanation:
Testcase1: The matrix is:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
The boundary traversal is 1 2 3 4 8 12 16 15 14 13 9 5
Testcase 2: Boundary Traversal will be 12 11 10 9 5 1 2 3 4 8.
Testcase 3: Boundary Traversal will be 1 2 3 4.
Testcase 4: Boundary Traversal will be 1 2 3 4.
"""
def BoundaryTraversal(a,n,m):
if(n==1):
for x in range(0,m):
print(a[0][x],end=" ")
return
if(m==1):
for y in range(0,n):
print(a[y][0],end=" ")
return
for x in range(m):
print(a[0][x],end=" ")
for x in range(1,n-1):
print(a[x][m-1],end=" ")
for x in range(m-1,0,-1):
print(a[n-1][x],end=" ")
for x in range(n-1,0,-1):
print(a[x][0],end=" ") |
0d07195b028642aaecf6825dd004a7ea04751d21 | Near-River/leet_code | /81_90/82_remove_duplicates_from_sorted_list_ii.py | 1,252 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None: return head
preHead = ListNode(-1)
preHead.next = head
prev = preHead
start, end = head, head.next
while end is not None:
if start.val != end.val:
prev = start
start = end
end = end.next
else:
while end.next is not None and end.next.val == start.val:
end = end.next
behind = end.next
prev.next = behind
if behind is None: break
start = behind
end = behind.next
return preHead.next
if __name__ == '__main__':
solution = Solution()
|
91318fd4bdae3637bdb0cbd75aac5ac5138b5d45 | dedekinds/pyleetcode | /371_Sum of Two Integers _easy.py | 1,586 | 3.859375 | 4 | '''371_Sum of Two Integers
2017.5.20
49ms
beats 23.42%
'''
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
while b != 0:
carry = a & b
a = (a ^ b) % 0x100000000
b = (carry << 1) % 0x100000000
return a if a <= 0x7FFFFFFF else a | (~0x100000000+1)
#http://blog.csdn.net/coder_orz/article/details/52034541
#Python的整数不是固定的32位,所以需要做一些特殊的处理
'''
这样的办法对负数无效,但是在C++和JAVA是可以的
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
#http://blog.csdn.net/zhongjiekangping/article/details/6855864
#直到不产生进位为止
#x^y //执行加法
#(x&y)<<1 //进位操作
result=a^b
while(a&b):
b=(a&b)<<1
a=result
result=a^b
print(result)
return result
'''
递归
def getSum(self, a, b):
def add(a, b):
if not a or not b:
return a or b
return add(a^b, (a&b) << 1)
if a*b < 0: # assume a < 0, b > 0
if a > 0:
return self.getSum(b, a)
if add(~a, 1) == b: # -a == b
return 0
if add(~a, 1) < b: # -a < b
return add(~add(add(~a, 1), add(~b, 1)),1) # -add(-a, -b)
return add(a, b) # a*b >= 0 or (-a) > b > 0 |
9eb35fe5b4fd9f8873ffa55f8b2918c3421c97fe | jphouminh71/csci1300_StartingComputing | /HomeWork/Homework9/Homework9_phouminh.py | 5,471 | 3.703125 | 4 | # CS1300 Spring 2018
# Author:
# Recitation Tuesday 930am Akriti Kupar
# Cloud9 Workspace Editor Link: https://ide.c9.io/…
# Homework 9
import os.path
def update_dictionary(filename, dictionary):
dictionary_size = 0
new_list = {}
if os.path.exists(filename):
print(filename,"loaded successfully.")
infile = open(filename, 'r')
newSize = 0
for aline in infile:
newSize = newSize + 1 # this should be counting the amount of values in the dictionary
words = aline.split(',') # parsing the line
second_word = words[1].strip("\n") # getting rid of the endline character
new_list.update({words[0]:second_word})
dictionary.update(new_list)
dictionary_size = len(dictionary)
print("The dictionary has",dictionary_size,"entries.")
infile.close()
return dictionary
else:
print(filename,"does not exist.")
print("The dictionary has",dictionary_size,"entries.")
return dictionary
def deslang(string, d):
myArray = string.strip().split()
sequence = ""
for word in myArray:
if word in d:
sequence+=d[word]
else:
sequence+=word
sequence+=" "
return sequence[0:-1]
def main():
quit = 0
dictionary = {}
#update_dictionary(filename, dictionary)
while quit == 0:
choice = input("Would you like to (a)dd words to the dictionary, (d)e-slang a sentence, or (q)uit?: ")
while choice == "" or choice not in "aAdDqQ":
choice = input("Would you like to (a)dd words to the dictionary, (d)e-slang a sentence, or (q)uit?: ")
else:
if choice in 'aA':
fileInput = input("Enter a filename: ")
while fileInput == "":
fileInput = input("Enter a filename: ")
else:
update_dictionary(fileInput,dictionary)
elif choice in 'dD':
EnteredSentence = input("Enter a sentence: ")
while EnteredSentence == "":
EnteredSentence = input("Enter a sentence: ")
else:
print(deslang(EnteredSentence, dictionary))
elif choice in 'qQ':
quit = 1
main()
'''def update_dictionary(filename,dictionary):
infile = open(filename,'r')
if infile is not open:
print("File failed to open")
dictionary_size = 0
slang_spelling_size = 0 # keep track of the size of each
slang_meaning_size = 0
slang_spelling = [] # just practicing working with arrays in python
slang_meaning = []
for aline in infile:
words = aline.split(',')
slang_spelling.append(words[0])
slang_spelling_size+=1
secondWord = words[1].strip("\n") # the text file had a \n at the end
slang_meaning.append(secondWord)
slang_meaning_size+=1
dictionary.append([words[0],secondWord])
dictionary_size+=1
infile.close()
return dictionary_size
def deSlangWords(string, dictionary):
arrayForString = []
word_count = 0
for i in range(len(string)):
if string[i] == " ":
word_count = word_count + 1
word_count = word_count + 1 # accounting for the last word
arrayForString = string.split(" ")
result = []
result = string.split(" ")
for i in range(word_count):
for j in range(dictionary_size):
if arrayForString[i] == dictionary[j][0]:
result[i] = dictionary[j][1]
sequence = ""
for k in range(word_count):
sequence = sequence + result[k] + " "
return sequence
def addWords(dictionary):
valid_input = False
while valid_input == False:
filename = input("Enter file name: ")
if filename != "":
valid_input = True
break
value = update_dictionary(filename, dictionary)
return value
def Quit():
print("Goodbye!")
return 0
def main():
global dictionary_size
dictionary_size = 0
dictionary = []
filename = "textToEnglish.txt" #passing this file name
dictionary_size = dictionary_size + update_dictionary(filename,dictionary) #filling the array for the dictionary and returning its size
print("The dictionary has", dictionary_size, "entries")
choice = input("Would you like to (a)dd words to the dictionary, (d)e-slang a sentence, or (q)uit?: ")
valid_input = False
while valid_input == False:
if choice not in "adqADQ":
valid_input = False
choice = input("Would you like to (a)dd words to the dictionary, (d)e-slang a sentence, or (q)uit?: ")
elif choice in 'aA':
valid_input = True
addWords(dictionary)
main()
elif choice in 'dD':
validInput = False
while validInput == False:
given_string = input("Sentence: ")
if given_string != "":
validInput = True
break
else:
validInput = False
result = deSlangWords(given_string, dictionary)
print(result)
main()
elif choice in 'qQ':
Quit()
break
main()'''
|
a2bf1c6f5de7a546567c578356a71c0bf048272b | hiroki8080/GitTest | /cal.py | 687 | 3.5625 | 4 | #coding : shift-jis
print "Calendar"
wday = ("sun","smon","tue","wed","thu","fri","sat")
#cal0(n,m)は1つの月のカレンダーを作成する。
#nは月の開始日の曜日を表す数字(0から6)であり、
#0は日曜日を意味する。
#mはその月の日数である。たとえば1月はm=31である。
#したがって2000年1月のカレンダーはcal0(6,31)で表示される。
def cal0(n,m):
for x in wday: print " ",x,
print
for x in range(0, n): print " ---",
for x in range(1, m+1):
print "%5d"%x,
if (x+n)%7==0 : print
print
cal0(6,31)
cal0(10,1)
cal0(10,2)
cal0(11,12) |
8f4521c2874e5648e14fe60b5271651772d3fda6 | ramonvaleriano/python- | /Livros/Introdução à Programação - 500 Algoritmos resolvidos/Capitulo 4/Exercicios 4a/Algoritmo189_para16.py | 467 | 3.828125 | 4 | # Program: Algoritmo189_para16.py
# Author: Ramon R. Valeriano
# Description:
# Developed: 02/04/2020 - 10:51
# Updated:
higher = int(input("Enter with the higher limit: "))
bottom = int(input("Enter with the bottom limit: "))
increment = int(input("Enter with the increment number: "))
if((higher>bottom)and(type(increment) is int)):
for e in range(bottom, higher+1, increment):
result = (5*(e-32))/9
print(result, "\n")
else:
print("Invalid Option!")
|
ce0591573c9fe2a794954f677dc67e68924bd56b | tadaspetra/csuniversity | /1_PythonForEverybody/2_Building Blocks/buildingblocks.py | 622 | 4.125 | 4 | print("CS UNIVERSITY")
print("-------------")
# messy variables, but code works
# saldfsdfa = 20
# jhwqbnower = 5
# wqsadfasd = saldfsdfa + jhwqbnower
# print(wqsadfasd)
# better variable name, and still works
# price = 20
# tax = 5
# total = price + tax
# total = total + 1
# print(total)
# converting data types
# x = "1"
# y = int(x) + 1
# print("convert data type:", y)
# user input
# name = input("What is your name? ")
# print("Hello,", name, "\n")
# converting celcius to fahrenheit
celcius = input("What is the temprature in Celcius? ")
fahrenheit = float(celcius)*(9/5) + 32
print("Fahrenheit: ", fahrenheit)
|
272d2de874f42de8236aa904ee6f2ec72b6922be | wenziyue1984/python_100_examples | /027递归打印.py | 326 | 3.71875 | 4 | # -*- coding:utf-8 -*-
__author__ = 'wenziyue'
'''
利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。
'''
def rev_print(s, l):
if l == 0:
return
print(s[l-1])
return rev_print(s, l-1)
if __name__ == '__main__':
s = input('请输入5个字符:')
l = len(s)
rev_print(s, l) |
4a3398f083edd4b66c90b4f118993222452f94c3 | zengwenhai/untitled1 | /day01/类继承.py | 440 | 3.90625 | 4 | class Fruit(object):
def __init__(self, name):
self.name = name
class Apple(Fruit):
def __init__(self, name, brand, color):
# Fruit.__init__(self, name)
super(Apple, self).__init__(name)
self.brand = brand
self.color = color
def info(self):
print("名称{0},品牌{1},颜色{2}".format(self.name, self.brand, self.color))
a = Apple('苹果', '红富士', '红色')
a.info() |
c2a8925aad0ca4f64f68df91d4003e787de1c00e | datou-leo/SpiderScrapyArticle | /common/worker.py | 1,117 | 3.6875 | 4 | import threading
class worker(threading.Thread):
def __init__(self,id, name):
threading.Thread.__init__(self)
self.id = id
self.name = name
self.thread_stop = False
def run(self):
while not self.thread_stop:
print("thread%d %s: waiting for task" %(self.ident,self.name))
# getStory(self.id)
self.thread_stop = True
def stop(self):
self.thread_stop = True
def createThread(id,Tnum):
threadList = []
for i in range(1,Tnum):
threadList.append(str(i))
threads = []
# 创建新线程
for tName in threadList:
thread = worker(id, tName)
thread.start()
threads.append(thread)
id += 1
# 等待所有线程完成
# join()方法的位置是在for循环外的,也就是说必须等待for循环里的两个进程都结束后,才去执行主进程。
#join()的作用是,在子线程完成运行之前,这个子线程的父线程将一直被阻塞。
for t in threads:
t.join()
# sleep(0.5) |
46998a1861fbbbe4d2a48e1bb870d6eb6b6af294 | mauriciocoder/mmath | /mmath/statistics.py | 3,359 | 3.734375 | 4 | # -----------------------------------------------------------
# Custom statistical functions for Python
#
# (C) 2020 Maurico Bonetti
# Released under GNU Public License (GPL)
# email: mauricio.coder@outlook.com
# -----------------------------------------------------------
import math
from functools import reduce
def assertList(values):
if not values:
raise ValueError
def mean(values):
"""Calculates the mean value from values list"""
assertList(values)
sum = reduce(lambda a, b: a + b, values)
return sum / len(values)
def mad(values):
"""Calculates the mad(mean absolute distribution) value from values list"""
assertList(values)
u = mean(values)
sum = reduce(lambda a, b: a + abs(b - u), values, 0)
return sum / len(values)
def median(values):
"""Calculates the median value from values list"""
assertList(values)
values.sort()
valuesLen = len(values)
if (valuesLen % 2 == 0):
i = valuesLen // 2
return (values[i - 1] + values[i]) / 2
else:
return values[valuesLen // 2]
def range(values):
"""Calculates the range from values list"""
assertList(values)
values.sort()
return values[-1] - values[0]
def quarter(values, index):
"""
Calculates the quarter based on the following rule
index = 0 -> returns the minimum value
index = 1 -> returns the first quarter value
index = 2 -> returns the median value
index = 3 -> returns the third quarter value
index = 4 -> returns the fourth quarter value
"""
assertList(values)
values.sort()
if (index == 0):
return values[0]
if (index == 1):
if (len(values) % 2 == 0):
return median(values[0: len(values) // 2])
else:
return median(values[0: (len(values) // 2) + 1])
if (index == 2):
return median(values)
if (index == 3):
return median(values[len(values) // 2:])
if (index == 4):
return values[-1]
def iqr(values):
"""Calculates the IQR from values"""
assertList(values)
values.sort()
return quarter(values, 3) - quarter(values, 1)
def variance(values, n):
"""Calculates the variance based on the sample and the population quantity n"""
assertList(values)
if (len(values) <= 1):
return values[0]
u = mean(values)
sum = reduce(lambda a, b: a + abs(b - u) ** 2, values, 0)
return sum / n
def variancePopulation(values):
"""Calculates the variance based on the whole population quantity (n)"""
return variance(values, len(values))
def varianceSample(values):
"""Calculates the variance based on the sample quantity (n - 1)"""
return variance(values, len(values) - 1)
def standardDev(values, n):
"""Calculates the standard deviation on the sample and the population quantity n"""
return math.sqrt(variance(values, n))
def standardDevPopulation(values):
"""Calculates the standard deviation on the whole population quantity (n)"""
return math.sqrt(variance(values, len(values)))
def standardDevSample(values):
"""Calculates the standard deviation on the sample and the population quantity n"""
return math.sqrt(variance(values, len(values) - 1))
def zScore(mean, sDev, value):
"""Calculates the z-score(standard deviation times that a value is from the mean)"""
return (value - mean) / sDev
|
56f4c246904d99e5792bd756a3ef4426ffdbca74 | Podlewski/IAD | /Rozgrzewka 5/Program.py | 3,530 | 3.609375 | 4 | #!/usr/bin/python
import math
import copy as cp
import numpy
import numpy.random as rand
import matplotlib.pyplot as plt
def Plot(it, prefix):
plt.clf()
plt.grid()
plt.xlim(-10, 10)
plt.ylim(-10, 10)
plotTitle = prefix + str(it) + ' epoka'
plt.title(plotTitle)
plt.scatter(arrX, arrY, color='k', s=3)
def RandomCirclePoints(arrX, arrY, x0, y0, r, maxIt):
it = 0
while it < maxIt:
x = rand.uniform(x0-r, x0+r)
y = rand.uniform(y0-r, y0+r)
if math.sqrt(pow(x0 - x, 2) + pow(y0 - y, 2)) <= r:
it += 1
arrX.append(x)
arrY.append(y)
def RandomSquarePoints(arrX, arrY, x0, y0, r, it):
for i in range(it):
arrX.append(rand.uniform(x0-r, x0+r))
arrY.append(rand.uniform(y0-r, y0+r))
def AssingPoint(x, y, krrX, krrY):
dMin = 100
for k in range(len(krrX)):
d = math.sqrt(pow((krrX[k] - x), 2) +
pow((krrY[k] - y), 2))
if d < dMin:
dMin = d
assigment = k
return assigment
def CountError(arrX, arrY, krrX, krrY):
error = 0
for a in range(len(arrX)):
assign = AssingPoint(arrX[a], arrY[a], krrX, krrY)
error += pow(arrX[a] - krrX[assign], 2)
error += pow(arrY[a] - krrY[assign], 2)
return error / len(arrX)
def SOM(arrX, arrY, krrX, krrY, alpha, theta):
oldX = cp.deepcopy(krrX)
oldY = cp.deepcopy(krrY)
for a in range(len(arrX)):
assign = AssingPoint(arrX[a], arrY[a], krrX, krrY)
for i in range(assign - theta, assign + theta + 1):
if (i >= 0) and (i < len(krrX)):
krrX[i] = krrX[i] + alpha * (arrX[a] - krrX[i])
krrY[i] = krrY[i] + alpha * (arrY[a] - krrY[i])
for k in range(len(krrX)):
if (math.fabs(oldX[k] - krrX[k]) > 0.01):
if (math.fabs(oldY[k] - krrY[k]) > 0.01):
return False
return True
arrX = []
arrY = []
wtaX = []
wtaY = []
wtaError = []
RandomCirclePoints(arrX, arrY, -3, 0, 2, 100)
RandomCirclePoints(arrX, arrY, 3, 0, 2, 100)
RandomSquarePoints(wtaX, wtaY, 0, 0, 10, 10)
wtmX = cp.deepcopy(wtaX)
wtmY = cp.deepcopy(wtaY)
wtmError = []
# fig size
figure = plt.gcf()
figure.set_size_inches(7, 7)
wtaIt = 0
condition = False
while condition is False:
wtaIt += 1
alpha = 0.05
if wtaIt > 2:
alpha = 0.01
Plot(wtaIt, 'WTA: ')
fileName = 'WTA/' + str(wtaIt) + '.png'
plt.plot(wtaX, wtaY, '-o', color='r')
plt.savefig(fileName, format='png')
theta = 0
wtaError.append(CountError(arrX, arrY, wtaX, wtaY))
condition = SOM(arrX, arrY, wtaX, wtaY, alpha, theta)
wtmIt = 0
condition = False
error = []
while condition is False:
wtmIt += 1
alpha = 0.05
if wtmIt > 2:
alpha = 0.01
Plot(wtmIt, 'WTM: ')
fileName = 'WTM/' + str(wtmIt) + '.png'
plt.plot(wtmX, wtmY, '-o', color='r')
plt.savefig(fileName, format='png')
theta = 1
wtmError.append(CountError(arrX, arrY, wtmX, wtmY))
condition = SOM(arrX, arrY, wtmX, wtmY, alpha, theta)
plt.clf()
plt.grid()
plt.xlabel('Iteracja')
plt.ylabel('Błąd kwantyzacji')
errX = numpy.arange(1, wtaIt+1)
errY = numpy.array(wtaError)
plt.plot(errX, errY)
fileName = 'outWTA.png'
plt.savefig(fileName, format='png')
plt.clf()
plt.grid()
plt.xlabel('Iteracja')
plt.ylabel('Błąd kwantyzacji')
errX = numpy.arange(1, wtmIt+1)
errY = numpy.array(wtmError)
plt.plot(errX, errY)
fileName = 'outWTM.png'
plt.savefig(fileName, format='png')
|
1ff42cb76b1331d5928e7fd7792f2a0ba16e7b2c | eflipe/juego-adivinar-numero | /game/machine_play.py | 6,808 | 3.765625 | 4 | from functions.numbers_generator import randomNumberGenerator, humanFriendly
from functions.numbers_comparation import numbersComparation
from functions.numbers_comparation import combinationsFunction
def machinePlay(humanNumber):
"""
The machine starts with a predefined strategy. For example, first start with the number 0123.
If the result is G: 1 then save that value in machineNumberGuess_1.
On the other hand, if it is R: 1, then try different combinations up to get G: 1.
Then, continue with the other strategies, 4567 and 0189.
"""
attempts = 0
regular = 0
good = 0
sum = 0
combinations = 1
strategy_1 = [0,1,2,3]
strategy_2 = [4,5,6,7]
strategy_3 = [0,1,8,9]
machineNumberGuess_1 = [0, 0, 0 ,0]
machineNumberGuess_2 = [0, 0, 0 ,0]
machineNumberGuess_3 = [0, 0, 0 ,0]
machineNumberGuessTotal = [0, 0, 0 ,0]
machineNumber = strategy_1 #start with the first strategy: 0123
print("The machine is playing...{} ".format(humanFriendly(machineNumber)))
score = numbersComparation(humanNumber, machineNumber)
regular = score[0]
good= score[1]
sum = score[2]
numero = score[3]
attempts += 1
print("R:{}".format(regular))
print("G:{}".format(good))
machineNumberGuess_1 = numero #saves the first number
machineNumberGuessTotal = [machineNumberGuess_1[i] + machineNumberGuess_2[i] + machineNumberGuess_3[i] for i in range(len(machineNumberGuessTotal))]
if good != 4:
while good != sum:
combinations += 1
machineNumber = combinationsFunction(machineNumber, combinations)
print("The machine is playing...{} ".format(humanFriendly(machineNumber)))
score = numbersComparation(humanNumber, machineNumber)
attempts += 1
regular = score[0]
good= score[1]
sum = score[2]
numero = score[3]
print("R:{}".format(regular))
print("G:{}".format(good))
machineNumberGuess_1 = numero
machineNumberGuessTotal = [machineNumberGuess_1[i] + machineNumberGuess_2[i] + machineNumberGuess_3[i] for i in range(len(machineNumberGuessTotal))]
if sum == 4:
while good != sum:
combinations += 1
machineNumber = combinationsFunction(machineNumber, combinations)
print("The machine is playing...{} ".format(humanFriendly(machineNumber)))
score = numbersComparation(humanNumber, machineNumber)
regular = score[0]
good= score[1]
sum = score[2]
numero = score[3]
print("R:{}".format(regular))
print("G:{}".format(good))
attempts += 1
machineNumberGuess_1 = numero
machineNumberGuessTotal = [machineNumberGuess_1[i] + machineNumberGuess_2[i] + machineNumberGuess_3[i] for i in range(len(machineNumberGuessTotal))]
elif sum != 4 :
combinations = 1
machineNumber = strategy_2 #second strategy: 4567
print("The machine is playing...{} ".format(humanFriendly(machineNumber)))
score = numbersComparation(humanNumber, machineNumber)
attempts += 1
regular = score[0]
good= score[1]
sum = score[2]
numero = score[3]
print("R:{}".format(regular))
print("G:{}".format(good))
machineNumberGuess_2 = numero #saves second number
machineNumberGuessTotal = [machineNumberGuess_1[i] + machineNumberGuess_2[i] + machineNumberGuess_3[i] for i in range(len(machineNumberGuessTotal))]
while good != sum:
combinations += 1
machineNumber = combinationsFunction(machineNumber, combinations)
print("The machine is playing...{} ".format(humanFriendly(machineNumber)))
score = numbersComparation(humanNumber, machineNumber)
regular = score[0]
good= score[1]
sum = score[2]
numero = score[3]
print("R:{}".format(regular))
print("G:{}".format(good))
attempts += 1
machineNumberGuess_2 = numero
machineNumberGuessTotal = [machineNumberGuess_1[i] + machineNumberGuess_2[i] + machineNumberGuess_3[i] for i in range(len(machineNumberGuessTotal))]
score = numbersComparation(humanNumber, machineNumberGuessTotal)
good= score[1]
if good == 2 or good == 3:
combinations = 1
machineNumber = strategy_3 #third strategy: 0189
print("The machine is playing...{} ".format(humanFriendly(machineNumber)))
score = numbersComparation(humanNumber, machineNumber)
attempts += 1
regular = score[0]
good= score[1]
sum = score[2]
numero = score[3]
print("R:{}".format(regular))
print("G:{}".format(good))
machineNumberGuess_3 = numero
machineNumberGuessTotal = [machineNumberGuess_1[i] + machineNumberGuess_2[i] + machineNumberGuess_3[i] for i in range(len(machineNumberGuessTotal))]
while good != sum:
combinations += 1
machineNumber = combinationsFunction(machineNumber, combinations)
print("The machine is playing...{} ".format(humanFriendly(machineNumber)))
score = numbersComparation(humanNumber, machineNumber)
attempts += 1
regular = score[0]
good= score[1]
sum = score[2]
numero = score[3]
print("R:{}".format(regular))
print("G:{}".format(good))
for num in range(len(numero)):
if numero[num] == 1:
numero[num] = 0
machineNumberGuess_3 = numero
machineNumberGuessTotal = [machineNumberGuess_1[i] + machineNumberGuess_2[i] + machineNumberGuess_3[i] for i in range(len(machineNumberGuessTotal))]
machineNumberGuessTotal = [machineNumberGuess_1[i] + machineNumberGuess_2[i] + machineNumberGuess_3[i] for i in range(len(machineNumberGuessTotal))]
score = numbersComparation(humanNumber, machineNumberGuessTotal)
good= score[1]
if good == 4:
print("\nThe machine won.\n")
print("\nThe number was: {}".format(humanFriendly(machineNumberGuessTotal)))
print("\nAttempts: {} ".format(attempts))
print("\nThe game is over.\n")
|
4efe21d88d24367b3b50a07d61cad60261e89a10 | spaceopsaus/SpaceOpsEducation | /picosat_sensor_module2/single_device_examples/compass.py | 694 | 3.828125 | 4 |
'''
Uses the on board magnetometer (compass) to determine the bearing of the device.
Try laying the microbit flat on a table and rotating it slowly whilst watching the plot of in the console.
The first time this is run, microbit may ask you to calibrate it by rotating the deive until all LEDs are lit.
'''
def on_forever():
degrees = input.compass_heading()
if degrees < 45:
basic.show_string("N")
elif degrees < 135:
basic.show_string("E")
elif degrees < 225:
basic.show_string("S")
elif degrees < 315:
basic.show_string("W")
else:
basic.show_string("N")
serial.write_value("Bearing:", degrees)
basic.forever(on_forever)
|
23625db2143b9930a4e39ea92e8d790c7579a906 | aptx4869/udacity | /programing/U2_41.py | 1,137 | 3.625 | 4 | word='abcde'
t=''
f=lambda x,i:x+'*'+str(10**-i)+'+'
lis=(f(word[i],i) for i in range(0,-len(word),-1))
for i in range(-1,-len(word)-1,-1) :
t+=f(word[i],i)
t=t[:-1]
enumerate
print t
print ''.join(lis)
print sum(lis)
def compile_word(word):
"""Compile a word of uppercase letters as numeric digits.
E.g., compile_word('YOU') => '(1*U+10*O+100*Y)'
Non-uppercase words unchanged: compile_word('+') => '+'"""
# Your code here.
f=lambda x,i:str(10**(-i-1))+'*'+x+'+'
lis=(f(word[i],i) for i in range(-1,-len(word)-1,-1))
t=''.join(lis)
return t[:-1]
print compile_word('YOU')
#def compile_word(word):
#"""Compile a word of uppercase letters as numeric digits.
#E.g., compile_word('YOU') => '(1*U+10*O+100*Y)'
#Non-uppercase words unchanged: compile_word('+') => '+'"""
## Your code here.
#t=''
#f=lambda x,i:x+'*'+str(10**-i)+'+'
#lis=(f(word[i],i) for i in range(0,-len(word),-1))
#t=''.join(lis)
#return t[:-1]
#for i in range(0,-len(word),-1) :
#t+=f(word[i],i)
#t=t[:-1]
#return t
##t.append(word[i]+'
##f=lambda : word[i]+'10**-i'
|
f7676a305860482be10f07561c55daa3a3bf4d59 | kickbean/LeetCode | /LC/LC_combinationSumII.py | 1,500 | 3.5 | 4 | '''
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, ... , ak) must be in non-descending order. (ie, a1 <= a2 <= ... <= ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
Created on Feb 2, 2014
@author: Songfan
'''
''' sort + dfs '''
def solution(A, t):
n = len(A)
if n == 0: return []
''' sort the array and we can prune the search procedure '''
A = sorted(A)
''' Awesome trick, bow down to myself:) : to track which element is used next '''
nextIdx = 0
res = []
_dfs(A, t, [], res, nextIdx)
return res
def _dfs(pool, target, currRes, res, nextIdx):
if target == 0:
tmp = currRes[:]
if tmp not in res: res.append(tmp)
return
n = len(pool)
if nextIdx == n: return
if target < pool[nextIdx]: return # pruning
for i in range(nextIdx, n):
currRes.append(pool[i])
''' we are force to choose element from index i+1, therefore, non-decreasing order is forced '''
_dfs(pool, target - pool[i], currRes, res, i + 1)
currRes.pop()
return
A = [10,1,2,7,6,1,5]
t = 8
print solution(A, t) |
3541b04bfb8bd807cf75f2739ce6c2bb3bdeb5b1 | ssmendon/pyrsa | /primes/primality.py | 3,792 | 3.625 | 4 | import random
import secrets
from modular import operations
from . import FOUND_PRIMES
def fermat_pseudoprime(candidate_prime):
"""Uses Fermat's theorem to test compositeness.
It returns 'True' if the number is a pseudoprime.
It runs in O(B^3), the same as modular exponentiation.
It errors on Carmichael numbers and other pseudoprimes,
but the error rate decreases to 0 as we go to infinity.
Based on the implementation from CLSR pg. 967.
"""
return False if operations.modular_exp(2, candidate_prime - 1, candidate_prime) != 1 \
else True
def clsr_miller_rabin(candidate_prime, iterations=32):
"""Uses the Miller-Rabin randomized primality test to
test compositeness.
Returns 'True' if the number is probably a prime.
It runs in O(sB) arithmetic-operations and O(sB^3) bit-arithmetic,
where s represents the number of iterations.
The error rate no longer depends on the candidate_prime,
and the error rate is 2^(-s) for incorrectly
testing compositeness (i.e. returns 'True' for a composite).
Based on the implementation from CLSR pg. 969 and 970.
"""
def witness(a, candidate_prime):
"""Returns True when a witness is found."""
if not candidate_prime & 1: # avoids hanging on evens
if candidate_prime == 2:
return False
return True
# first, construct t and u such thmilat
# candidate_prime - 1 = 2^t * u
# where u must be odd
t = 1
u = (candidate_prime - 1) // (1 << t)
while candidate_prime - 1 != (1 << t) * u or not u & 1:
t += 1
u = (candidate_prime - 1) // (1 << t)
x = [0] * (t+1)
x[0] = operations.modular_exp(a, u, candidate_prime)
for i in range(1, t + 1):
x[i] = operations.modular_exp(x[i-1], 2, candidate_prime)
if x[i] == 1 and x[i-1] != 1 and x[i-1] != candidate_prime - 1:
return True
if x[t] != 1:
return True
return False
for _ in range(iterations):
a = random.randint(1, candidate_prime - 1)
if witness(a, candidate_prime):
return False
return True
def nist_miller_rabin(candidate_prime, iterations=38):
"""Uses the Miller-Rabin compositeness test on a candidate prime.
Returns True if the number is probably prime.
Uses the NIST implementation from
https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
on pg. 71 to 72 in Appendix C.3.1
"""
# special case
if candidate_prime == 2:
return True
elif not candidate_prime & 1:
return False
# let a be the largest such integer that divides
# the candidate - 1
# i.e. 2^(a) * s = candidate - 1
a, s = 0, candidate_prime - 1
while not s & 1:
a += 1
s = s >> 1 # s = (candidate - 1)/2^a
for _ in range(iterations):
b = random.randint(2, candidate_prime - 2)
z = operations.modular_exp(b, s, candidate_prime)
if z == 1 or z == candidate_prime - 1:
continue
for __ in range(1, a):
z = operations.modular_exp(z, 2, candidate_prime)
if z == 1:
return False # it's not prime
elif z == candidate_prime - 1:
break # leave this inner loop and continue the outer loop
if z != candidate_prime - 1:
return False
return True
def trial_division(candidate_prime, B=None):
"""Checks if a number is divisible by some multiple of primes
until some value B.
Returns True if it's divisible, and False if it isn't.
"""
return any(candidate_prime % prime == 0 for prime in FOUND_PRIMES[:B]) |
aaeeda7a0924a40df89d6dbda8aabf019d3a0c47 | Talib07/Sorting-Algos | /LinkedLists.py | 2,038 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 27 13:14:20 2019
@author: Talib
"""
class node:
def __init__(self,names):
self.names = names
self.next = None
class initiallinker:
def __init__(self):
self.head = None
def Printlist(self):
nameval = self.head
while nameval is not None:
print(nameval.names)
nameval = nameval.next
# Insertion at beginning
def insertbeg(self,newdata):
NewNode = node(newdata)
#Update
NewNode.next = self.head
self.head = NewNode
#Insertion at end
def insertend(self,newdata):
NewNode = node(newdata)
#update
if self.head is None:
self.head = NewNode
return
last = self.head
while(last.next):
last = last.next
last.next = NewNode
#insert anywhere
def insertany(self,newdata,place):
if place is None:
print("No such place to insert")
else:
NewNode = node(newdata)
#update
NewNode.next = place.next
place.next = NewNode
def delete(self,key):
Headval = self.head
if Headval is not None:
if(Headval.names == key):
self.head = Headval.next
Headval = None
return
while(Headval is not None):
if Headval.names == key:
break
prev = Headval
Headval = Headval.next
if (Headval == None):
return
prev.next = Headval.next
Headval = None
ob1 = initiallinker()
ob1.head = node("Mon")
ob2 = node("Tue")
ob3 = node("Wed")
'''ob4 = node("Thur")
ob5 = node("Fri")'''
ob1.head.next = ob2
ob2.next = ob3
ob1.insertbeg("Sun")
ob1.insertend("Sat") |
c5af627bebef250c805158172cd5c2aaa79391ed | eukaryote/junkdrawer | /numbertheory.py | 2,035 | 3.734375 | 4 | """
Utility functions useful for euclid problems and the like.
"""
def modadd(x, y, n):
"""
Calculate modular addition: (x+y) mod n.
Args: integers x and y, and a positive integer n
>>> modadd(3, -10, 5)
3
>>> modadd(278, 199, 17)
1
"""
return (x + y) % n
def modexp(x, y, n):
"""
Calculate modular exponentiation: x^y mod n.
The time complexity of this algorithm is O(b^3), where
b is the number of bits of the largest of x, y, and n.
The algorithm performs at most n recursive calls, and
at each call, multiplies n-bit numbers modulo n.
The algorithm is based on the following rule:
x^y = (x^floor(y/2)) ^ 2 if y is even
= x * (x^floor(y/2)) ^ 2 if y is odd
Args:
* x: an integer
* y: a non-negative integer
* n: a positive integer
>>> modexp(2, 5, 6)
2
>>> modexp(43417, 53535, 34310)
12053L
>>> modexp(345343417, 542323535, 324244310)
23504373L
"""
if y == 0:
return 1
z = modexp(x, y / 2, n)
if y % 2 == 0:
return (z * z) % n
else:
return (x * z * z) % n
def euclid(a, b):
"""
Calculates the greatest common divisor of a and b.
Args:
* a: a non-negative integer >= b
* b: a non-negative integer <= a
>>> euclid(2, 2)
2
>>> euclid(99, 15)
3
>>> euclid(95, 100)
5
>>> euclid(56, 14)
14
>>> euclid(135749, 27482)
151
"""
if b == 0:
return a
return euclid(b, a % b)
def extended_euclid(a, b):
"""
Calculates integers x, y, d such that d = gcd(a, b) and
ax + by = d.
Args: non-negative integers a and b with a >= b >= 0.
>>> extended_euclid(7, 2)
(1, -3, 1)
>>> extended_euclid(81, 57)
(-7, 10, 3)
"""
if b == 0:
return (1, 0, a)
(x, y, d) = extended_euclid(b, a % b)
return (y, x - ((a / b) * y), d)
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
|
7bc88602ac6057434638d1c9508e61e93f77d7bb | erikliu0801/leetcode | /python3/solved/P665. Non-decreasing Array.py | 2,016 | 4.15625 | 4 | # ToDo:
"""
665. Non-decreasing Array
Easy
Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.
We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).
Example 1:
Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
Example 2:
Input: [4,2,1]
Output: False
Explanation: You can't get a non-decreasing array by modify at most one element.
"""
# Conditions & Concepts
"""
"""
# Code
## submit part
class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
## test part
def checkPossibility(nums):
"""
nums: List[int]
rtype: bool
"""
## code here
#1
"""
Wrong Answer
Input: [2,3,3,2,4]
Output: false
Expected: true
Success
Runtime: 212 ms, faster than 37.06% of Python3 online submissions for Non-decreasing Array.
Memory Usage: 14 MB, less than 93.33% of Python3 online submissions for Non-decreasing Array.
"""
def checkPossibility(nums):
nums0 = nums.copy()
for i in range(1,len(nums)):
if nums[i] < nums[i-1]:
nums[i-1] = nums[i]
new_nums_sorted = nums.copy()
new_nums_sorted.sort()
nums0[i] = nums0[i-1]
new_nums0_sorted = nums0.copy()
new_nums0_sorted.sort()
return nums == new_nums_sorted or nums0 == new_nums0_sorted
return True
# Test
## Functional Test
"""
# Conditions & Concepts
"""
if __name__ == '__main__':
input_nums = [[1,2,3],[4,2,3],[4,2,1],[3,4,2,3],[2,3,3,2,4]]
expected_output = [True, True, False, False, True]
for i in range(len(input_nums)):
if checkPossibility(input_nums[i]) != expected_output[i]:
print("Wrong!!!", ' Output:', checkPossibility(input_nums[i]), '; Expected Output:', expected_output[i])
else:
print("Right")
# print(checkPossibility(input_nums[-1]))
## Performance Test
import cProfile
cProfile.run('')
## Unit Test
import unittest
class Test(unittest.TestCase):
def test(self):
pass
if __name__ == '__main__':
unittest.main() |
6a8d715fceda73bd1dcb5d1efcd434fec19a68ac | monsterone/lemotest | /class01/class8_if.py | 1,745 | 4.34375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/3/12 21:46
# @Author : Monster
# @Email : 945534456@qq.com
# @File : class8_if.py
#【8】 控制语句 分支分流 循环语句 for while
#判断语句 if..elif ..else 关键字
#(1)if 条件语句: 1:(比较 逻辑 成员 均可)
# 2:空数据==False 非空数据==True
#3:直接用布尔值控制(鸡肋)
# s=''
# s='hello'
# if 'o' in s: #当if后面的语句 满足条件 运算结果是True 那就会执行他的子语句
# print("恭喜,成年!")
#(2):一个条件语句里面 只能有一个if和一个else (else后面不能添加条件语句)
# if 条件语句:
#子语句
#else:
# 子语句
'''
age=20
if age>18:
print("恭喜,成年!2")
else:
print("加油长大,小屁孩")
'''
#(3):if 和elif后面可以加条件语句
# if 条件语句:
#子语句
# elif 条件语句:
#子语句
#else:
# 子语句
'''
#input()函数 从控制台获取一个数据 获取的数据都是字符串类型
age=int(input("请输入你的年龄:")) #如果输入为字符串等非数字,报错
#自己解决:isdigit()
# Python isdigit() 方法检测字符串是否只由数字组成。
# age.isdigit()
# age=16
if age>18:
print("恭喜,成年!3")
elif 18>age>0:
print("加油长大,小屁孩")
else:
print("你的年龄输入有误,不能为负数!")
'''
#拓展:
# isdigit()方法检测字符串是否只由数字组成。
# 三个函数的区别和注意点:#https://www.cnblogs.com/chenglei0520/p/9431353.html
# isdigit() #纯数字、 S1 = '12345'、S2 = '①②'
# isalpha() #汉字+字母、S1 = 'abc汉字'
# isalnum() #字母+汉字+数字 S1 = 'abc汉字1'
|
9f51e3c275d5c57bef9b30cc59a9c8e23ef2db98 | xu1718191411/AT_CODE_BEGINNER_SELECTION | /CONTEXT_131/megalomania.py | 372 | 3.640625 | 4 | def calculate(list):
current = 0
for item in list:
current += item[0]
if current > item[1]:
return False
return True
N = int(input())
arr = []
for i in range(N):
arr.append([int(s) for s in input().split(" ")])
arr2 = sorted(arr,key=lambda x:x[1])
result = calculate(arr2)
if result:
print("Yes")
else:
print("No") |
d6c2a49e415f8b83b83f5dcf1e0486973d9ef404 | gauravshremayee/IoTCode | /led_bcm.py | 489 | 3.921875 | 4 |
import RPi.GPIO as GPIO
import time
#We can use other SPIO pin also
#Put one pin in pin 12 ( i.e BCM PIN 12) and other in GND ,when the program stops LED should be off
#If the led is connected to 5v and GND pin then it will be switch on without program also.
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
print( "LED on")
GPIO.output(18,GPIO.HIGH)
time.sleep(1)
print( "LED off")
GPIO.output(18,GPIO.LOW)
print("LED ON")
GPIO.output(18,GPIO.HIGH) |
36ddb7bdea2a1bba1fa4840ce5376e580a562523 | rvcjavaboy/eitra | /MIT python course/Assignment_2_1/rand_divis_3.py | 251 | 4.0625 | 4 | import math
import random
def rand_divis_3():
a=random.randint(0,100)
print("Random number generated is:",a)
if a%3==0:
print("It is divisible by 3")
else:
print("It is not divisible by 3")
rand_divis_3()
|
0b84f386e15560beb031f4955d240a43a9f9eb6d | lonely7yk/LeetCode_py | /LeetCode1000/LeetCode1404NumberofStepstoReduceaNumberinBinaryRepresentationtoOne.py | 1,621 | 3.84375 | 4 | """
Given a number s in their binary representation. Return the number of steps to reduce it to 1 under the following rules:
If the current number is even, you have to divide it by 2.
If the current number is odd, you have to add 1 to it.
It's guaranteed that you can always reach to one for all testcases.
Example 1:
Input: s = "1101"
Output: 6
Explanation: "1101" corressponds to number 13 in their decimal representation.
Step 1) 13 is odd, add 1 and obtain 14.
Step 2) 14 is even, divide by 2 and obtain 7.
Step 3) 7 is odd, add 1 and obtain 8.
Step 4) 8 is even, divide by 2 and obtain 4.
Step 5) 4 is even, divide by 2 and obtain 2.
Step 6) 2 is even, divide by 2 and obtain 1.
Example 2:
Input: s = "10"
Output: 1
Explanation: "10" corressponds to number 2 in their decimal representation.
Step 1) 2 is even, divide by 2 and obtain 1.
Example 3:
Input: s = "1"
Output: 0
Constraints:
1 <= s.length <= 500
s consists of characters '0' or '1'
s[0] == '1'
"""
class Solution:
def numSteps(self, s: str) -> int:
def plusOne(s):
res = ""
flag = 1
for i in range(len(s) - 1, -1, -1):
curr = (int(s[i]) + flag) % 2
flag = (int(s[i]) + flag) // 2
res = str(curr) + res
if flag:
res = str(flag) + res
return res
res = 0
while s != "1":
last = s[-1]
if last == "0":
s = s[:-1]
else:
s = plusOne(s)
res += 1
return res
s = "111"
res = Solution().numSteps(s)
print(res) |
e734f08962b8a776579ed3fc336a526960e6552d | YauheSh/bh_5_tasks-master | /easy/generators/factorial.py | 624 | 4.125 | 4 | """
Написать генератор factorial, который возвращает подряд числа факториала
Например:
factorial_gen = factorial()
next(factorial_gen) -> 1
next(factorial_gen) -> 2
next(factorial_gen) -> 6
next(factorial_gen) -> 24
"""
def factorial(n):
fact = 1
if n == 0:
return fact
else:
for i in range(n):
if i == 0:
continue
else:
fact *= i
yield fact
factorial_gen = factorial(10)
next(factorial_gen)
next(factorial_gen)
next(factorial_gen)
next(factorial_gen)
|
274d049f3021b61e56ec4cad32aee65fadbec645 | loggar/py | /py-core/dictionary/dictionary-keys.py | 329 | 3.859375 | 4 | # When duplicate keys are encountered during assignment, the last assignment wins
dict_1 = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print("dict_1['Name']: ", dict_1['Name'])
# Keys must be immutable
dict_2 = {['Name']: 'Zara', 'Age': 7}
# print("dict_2['Name']: ", dict_2['Name'])
# TypeError: list objects are unhashable
|
c64e63f28036b0cde070b398f2882a67207eed4f | BartekPodgorski/Python | /Python_Syntax_training/stare/Dodawanie.py | 1,265 | 3.78125 | 4 | #mierzenie wydajnosci kodu
import time
#Dodawanie za pomoca petli
def sumuj_do(liczba):
suma = 0
for liczba in range (liczba+1):
suma = suma + liczba
return (suma)
#dodawanie za pomoca wyrazenia generujacego
def sumuj_do2(liczba):
return sum((liczba for liczba in range(liczba+1)))
#dodawanie za pomoca wyrazenia slownikowego
def sumuj_do3(liczba):
return sum({liczba for liczba in range(liczba+1)})
#dodawanie za pomoca wyrazenia listowego
def sumuj_do4(liczba):
return sum([liczba for liczba in range(liczba+1)])
#dodawanie za pomoca wlsnego liczeni
def sumuj_do5(liczba):
return((1+liczba)/2*liczba)
def function_performance(func, arg, how_many_times = 1):
suma = 0
for i in range(0, how_many_times):
start=time.perf_counter()
func(arg)
end=time.perf_counter()
suma = suma + (end-start)
return suma/how_many_times
print(function_performance(sumuj_do,10000000))
print(function_performance(sumuj_do,10000000,6))
"""
print(function_performance(sumuj_do2,10000000))
print(function_performance(sumuj_do3,10000000))
print(function_performance(sumuj_do4,10000000))
print(function_performance(sumuj_do5,10000000))
"""
|
097f5c18bca4a4192883810670925de4a9bdaf7f | 1040979575/baseDataStructureAndAlgorithm | /leecode/longestPalindromicSubstring.py | 297 | 3.96875 | 4 |
def get_longest_str(s):
dt = {}
dt.__contains__()
pass
def is_palindromic(s):
size = len(s)
for i in range(int(size/2)):
if s[i] != s[size-i-1]:
return False
return True
if __name__ == '__main__':
if is_palindromic("abba"):
print("yes") |
f0b38751afe36ac2a16003db7097fbe694cd0507 | ayahito-saji/SummerVacation | /19.py | 619 | 3.78125 | 4 | #usr/bin/env python3
print("19. 複雑な割引")
items = [["apple", 200, 38],
["kiwi", 130, 40],
["orange", 90, 20],
["grape", 380, 30],
["peach", 400, 10],
["cherry", 300, 5],
["banana", 80, 36],
["lemon", 150, 20] ]
sales = {}
for i in range(0, len(items)):
sales[items[i][0]] = (items[i][1], items[i][2])
for each_key in sales.keys():
price = sales[each_key][0] * sales[each_key][1]
if sales[each_key][1]>= 30:
price *= 0.9
if sales[each_key][1]>= 10 and (each_key == "peach" or each_key == "cherry"):
price *= 0.9
price *= 1.08
print(each_key.ljust(8)+" "+"{0:5d}".format(int(price))) |
855c9a7e793d2940c7f61826e10db88339094680 | yashcholera3074/python-practical | /exp11.py | 671 | 4.21875 | 4 | import random
number = random.randint(1, 10)
guess=0
count=0
while guess!= number and guess!= "exit":
guess=input("Please guess a number between 1 and 9 and When you want to end the game type 'exit': ")
if guess=="exit":
print("Game End")
break
guess=int(guess)
count+=1
if guess not in range(1, 10):
print("guess a number between 1 and 9!")
elif guess < number:
print("You have guessed too low!")
elif guess > number:
print("You have guessed too high!")
else:
print("you have guess exactly right")
print("You guess exact number in {} tries".format(count))
|
303036a9696ef0bf3177527d3542ef7f7d1b9fcc | mananiac/Codeforces | /cAPS LOCK.py | 329 | 3.84375 | 4 | num=input()
num2=num
num2=list(num)
j=num2.pop(0)
num3=""
for i in num2:
num3=num3+i
#print(num2)
if num.isupper() :
print(num.lower())
elif(len(num)==1) :
if num.isupper():
print(num)
else:
print(num.upper())
elif(num3.isupper() and j.islower() ):
print(num.title())
else:
print(num)
|
78c8d9189defec033c9c53bdb4bf5437bcc35374 | NikitaSikalov/BioinformaticsAlgorithms | /tasks/task26/progma26.py | 1,766 | 3.6875 | 4 | #! /usr/bin/env python3
from typing import List
import re
import pyperclip
def permutation_to_str(arr: List[int]):
return "(" + ' '.join(["+" + str(x) if x > 0 else str(x) for x in arr]) + ")"
def gridy_reversal_permutation(arr: List[int]):
pointer = 0
n = len(arr)
permuations = []
tmp = arr.copy()
while pointer != n:
if tmp[pointer] != pointer + 1:
j = pointer
while abs(tmp[j]) != pointer + 1:
j += 1
tmp = tmp[:pointer] + [-x for x in reversed(tmp[pointer:j + 1])] + (tmp[j + 1:] if j + 1 < n else [])
permuations.append(tmp)
else:
pointer += 1
for i in range(n):
assert(permuations[-1][i] == i + 1)
ans = "\n".join([permutation_to_str(permutation) for permutation in permuations])
print(ans)
return ans
def prepare_arr(s: str):
patterns = re.split(r'[()\s]', s)
patterns = filter(lambda x: bool(x), patterns)
return [int(x) for x in patterns]
def main(s: str):
arr = prepare_arr(s)
return gridy_reversal_permutation(arr)
# Example test ----------------------------------------------
# sample = '(-3 +4 +1 +5 -2)'
# ans = main(sample)
# true_ans = "(-1 -4 +3 +5 -2)\n(+1 -4 +3 +5 -2)\n(+1 +2 -5 -3 +4)\n(+1 +2 +3 +5 +4)\n(+1 +2 +3 -4 -5)\n(+1 +2 +3 +4 -5)\n(+1 +2 +3 +4 +5)"
# assert(ans == true_ans)
# Debug test ----------------------------------------------
# f = open('./debug.txt')
# data = f.read().split("\n")
# f.close()
# ans = main(data[1])
# true_ans = "\n".join(data[3:]).strip()
# assert(ans == true_ans)
# Final test ----------------------------------------------
f = open('./test.txt')
data = f.read().split("\n")
f.close()
ans = main(data[0])
pyperclip.copy(ans)
|
f16826eb8d12badaf9134dc8401e16e0c807c1fe | billfromsep/DSSVue-Example-Scripts | /src/BasicExamples/Example9-iterative-looping.py | 344 | 4.125 | 4 | # print the first 10 characters
string_1 = "this is a test string"
for i in range(10) :
print string_1[i]
# print all the characters
string_1 = "this is a test string"
for i in range(len(string_1)) :
print string_1[i]
# print all the characters (more Python-y)
string_1 = "this is a test string"
for c in string_1 :
print c
|
18116572594a72d098e3acf420127dcbafba4428 | wangshanmin/leetcode | /021. Merge Two Sorted Lists/Merge Two Sorted Lists.py | 900 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 28 20:05:37 2018
@author: wangshanmin
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, self.next)
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 and l2:
if l1.val > l2.val:
l1, l2 = l2, l1
print(l1)
print(l2)
l1.next = self.mergeTwoLists(l1.next,l2)
print(l1)
# return l1 or l2
if __name__ == "__main__":
l1 = ListNode(1)
l1.next = ListNode(4)
l2 = ListNode (2)
l2.next = ListNode(3)
Solution().mergeTwoLists(l1, l2) |
7f229f3ba89c9b6b226ba3ec4c79b861a30bea3b | NolanNicholson/TurtleFinch | /turtleFinch.py | 1,309 | 3.84375 | 4 | from PIL import Image
import turtle
img = Image.open("finch.jpg")
width, _ = img.size
for i, px in enumerate(img.getdata()):
if sum(px[:3]) > 128 * 3:
newColor = (255, 255, 255, 255)
else:
newColor = (0, 0, 0, 255)
y = i // width
x = i % width
img.putpixel((x, y), newColor)
# img.show()
def turtleSpiral(speed=3, spacing = 5):
print(turtle.pos())
radius = 1
while True:
turtle.forward(speed)
turtle.left(speed * 360 / 2 / 3.14159 / radius)
radius += spacing * speed / 2 / 3.14159 / radius
def turtleImgSpiral(img, speed=0.5, spacing = 2):
radius = 1
width, height = img.size
x0, y0 = (width//2, height//2)
while True:
# Read the turtle's position and get it in the image
pos = turtle.position()
x, y = (int(pos[0]), -int(pos[1]))
try:
r, g, b = img.getpixel((x + x0, y + y0))
if r > 0:
turtle.penup()
else:
turtle.pendown()
except IndexError:
turtle.penup()
# Move turtle in spiral
spd = speed * radius**0.5
turtle.forward(spd)
turtle.left(spd * 360 / 2 / 3.14159 / radius)
radius += spacing * spd / 2 / 3.14159 / radius
turtleImgSpiral(img)
input()
|
b4ccfbd4c56e70ec17c15878cc114c2f1461b0a1 | chiehli/LeetCode | /LongestSubstringNoRepeatingChar.py | 4,057 | 3.84375 | 4 | """
LeetCode 3. Longest Substring without Repeating Characters
Given a string, find the length of the longest substring without repeating
characters
Example 1:
Input: "abcabcbb"
Output: 3 ("abc")
Example 2:
Input: "pwwkew"
Output: 3 ("wke")
"""
class LongestSubstring(object):
def get_length(self, s):
# type s: str
# rtype: int
#ans_str = []
#ans_str.append('')
#max_sub_length = self.recur_get_len_helper(s, ans_str)
#print(ans_str[0])
max_sub_length = self.sliding_window_optimized(s)
return max_sub_length
def sliding_window_helper(self, s):
"""
substr_ij indicates the substring without repeat letters from index i to index j
check if the letter at index j+1 has repeated letter
if yes, compare length of current substring with the max_length and update as needed
else, continuing sliding the window -> j += 1
Time complexity: O(n)
"""
dict = {}
substr = ''
max_length = 0
max_str = ''
i = 0
j = i
while i < len(s) and j < len(s):
if s[j] not in dict:
dict[s[j]] = j
substr += s[j]
j += 1
else:
if len(substr) > max_length:
max_length = len(substr)
max_str = substr
substr = ''
i += 1
j = i
dict = {}
if len(substr) > max_length:
max_length = len(substr)
max_str = substr
print("max_substr = {0}".format(max_str))
return max_length
def sliding_window_optimized(self, s):
"""
substr_ij indicates the substring without repeat letters from
index i to index j
check if the letter at index j+1 has repeated letter
if yes, compare length of current substring with the max_length
and update as needed
next, update substr_ij as substr_idx+1_j where idx is the index the
repeated character appears
else, continuing sliding the window -> j += 1
Time complexity: O(n)
"""
dict = {}
max_length = 0
i = 0 # start from the beginning
j = i
N = len(s)
while i < N and j < N:
if s[j] not in dict:
# no repeat, continue adding j
dict[s[j]] = j
j += 1
else:
if len(dict) > max_length:
# check if current substring has longer length
max_length = len(dict)
idx = dict[s[j]]
for k in range(i, idx):
# update dictionary
# remove the character from s[i] to s[idx - 1]
# because we are going to look at a new substring
if s[k] in dict:
del dict[s[k]]
dict[s[j]] = j # update the index where s[j] appears
i = idx + 1
j += 1
dict_length = len(dict)
if dict_length > max_length:
max_length = dict_length
return max_length
def recur_get_len_helper(self, s, ans):
# Time complexity: O(n^3)
dict = {}
for i, char in enumerate(s):
if char not in dict:
dict[char] = i
else:
index = dict[char]
return max(self.recur_get_len_helper(s[0 : i], ans),
self.recur_get_len_helper(s[index + 1 : len(str)], ans))
if len(s) > len(ans[0]):
ans[0] = s
return len(ans[0])
def main():
strs = ["aabaab!bb", "bb", "abcabcbb", "pwwkew"]#["abcabcbb", "pwwkew"]
obj = LongestSubstring()
for str in strs:
print('string = {0}'.format(str))
longest_length = obj.get_length(str)
print('longest substring length: {0}'.format(longest_length))
if __name__ == '__main__':
main()
|
41d1319dfefa305a65001fe8364f8707d54b65f0 | kerbylane/python | /multi_dict/src/multi_dict.py | 5,528 | 4.09375 | 4 | """A multi-dimensional dict."""
from collections import defaultdict
class IncorrectNumberOfKeys(Exception):
pass
class MultiDict(object):
"""A multi-dimensional default dict.
This provides functions to simplify interactions with a nested defaultdict structure.
It is assumed that 'values' are only at the lowest level of the structure. Hence get()
requires an array as long as the 'levels' argument used in the constructor.
"""
# The methods that make it possible to use the [] notation, such as __setitem__,
# include tests for key length. But they call internal methods that no longer
# test the arguments for faster performance.
def __init__(self, levels, default):
"""An instance whose number of keys is 'levels' and whose values are created by the
constructor 'default'.
"""
if levels < 2:
raise Exception(u'MultiDict can only be constructed for 2 or more dimensions')
self._levels = levels
if self._levels == 2:
self._data = defaultdict(lambda: InnerMultiDict(default))
else:
self._data = defaultdict(lambda: MultiDict(self._levels - 1, default))
def __setitem__(self, *args):
# print 'md.__setitems__ args is %s' % str(args)
# keys = self._getKeys(args[0])
self._checkLength(args[0])
self._set(args[0], args[1])
def __getitem__(self, *keys):
# print 'md.__getitem__ keys is %s' % str(keys)
self._checkLength(keys[0])
return self._get(keys[0])
def __delitem__(self, keys):
if isinstance(keys, tuple):
del self._data[keys[0]][ keys[1:] ]
# If the sub-dict is empty dump it
if len(self._data[keys[0]]) == 0:
self._data.__delitem__(keys[0])
else:
del self._data[keys]
def __str__(self):
# This is really complicated. What are we doing?
# Use iteritems() to get all of the items
# call str() for each entry in the items
# join all of the strings for the item with ':'
# join all of the items' strings with ', '
# surround the whole thing in {}.
return u'{%s}' % u', '.join([u'%s:%s' % (str(k), str(v)) for k,v in self._data.iteritems()])
def __repr__(self):
return self.__str__()
def __len__(self):
"""Returns a count of all 'leaves' in the structure."""
return sum(v.__len__() for v in self._data.values())
def iteritems(self):
"""Return items from this object."""
for k, v in self._data.iteritems():
for v_items in v.iteritems():
yield [k] + v_items
def get(self, *keys):
"""Returns subdict sharing keys prefix."""
if len(keys) > self._levels:
raise IncorrectNumberOfKeys("Too many keys submitted, got %d, max is %d" % (len(keys), self._levels))
return self._get(keys)
def keys(self):
for entry in self.iteritems():
yield entry[:-1]
def values(self):
for entry in self.iteritems():
yield entry[-1]
##################################################
#
# The following are internal only functions. Some are intended to avoid tests that
# only need to be performed at the top API level.
#
##################################################
def _checkLength(self, args):
"""Confirm the number of keys submitted matches the number of _levels."""
if not (isinstance(args, tuple) and len(args) == self._levels):
raise IncorrectNumberOfKeys('Got key argument %d, length should be %d' % (args, self._levels))
def _set(self, keys, value):
"""Internal version of set() which doesn't check dims to speed insertion of long items."""
print 'md._set (%d) %s %s' % (self._levels, str(keys), str(value))
self._data.__getitem__(keys[0])._set(keys[1:], value)
def _get(self, keys):
print 'md._get %s' % str(keys)
if len(keys) == 1:
return self._data.__getitem__(keys[0])
else:
return self._data.__getitem__(keys[0])._get(keys[1:])
class InnerMultiDict(MultiDict):
"""Implementation of MultiDict for only 2 dimensions.
This is just a wrapper around defaultdict which supports the same API as MultiDict."""
# Note that the key arguments passed are all arrays with 1 entry. This makes the
# code in MultiDict cleaner.
def __init__(self, default):
self._data = defaultdict(default)
def __setitem__(self, *args):
# print 'id.__setitem__ args: %s' % str(args)
self._data.__setitem__(args[0][0], args[1])
def __getitem__(self, key):
# print 'id.__getitem__ key is %s' % str(key)
return self._data.__getitem__(key[0])
def __delitem__(self, key):
self._data.__delitem__(key[0])
def __str__(self):
return str(dict(self._data))
def __len__(self):
return self._data.__len__()
def _set(self, key, value):
# print 'id._set %s %s' % (str(key[0]), str(value))
self._data.__setitem__(key[0], value)
def _get(self, key):
# print 'id._get %s' % str(key[0])
return self._data[key[0]]
def iteritems(self):
for (k, v) in self._data.iteritems():
yield [k, v]
|
dae39b8e6af424a4c21b1a3673625e67ef427df9 | cae018/csci204project1 | /csci204project/csci204Project-master/src/skTree.py | 2,064 | 3.578125 | 4 | """
Will be used to make a decision tree using sklearn
More details will be added to this later
"""
import math
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_graphviz
#from sklearn.tree import predict
class SKTree:
def __init__(self):
"""
More information will be given about this later
"""
self.tree = None
def train(self, xData, yData, maxDepth):
"""
Pre: xData is a 2D list containing mapped parameters from given documents
yData is the 1D list containing the mapped from info
Post: makes decision tree and .dot document that contains tree
graphic information
"""
#Make tree
tree = DecisionTreeClassifier(criterion="entropy", max_depth=maxDepth, random_state=0)
#Fit to parameters
tree = tree.fit(xData, yData)
#Create a graphviz visualization of tree
dot_data = export_graphviz(tree, out_file='traintree.dot', \
feature_names=['Date', 'toInfo', 'Forward', 'Reply','Top10','Bott10'])
#Set the tree attribute to the created tree
self.tree = tree
def eval(self, xData):
"""
Pre: xData is the known data from the eval folder, a 2D list of mapped parameters
Post: Returns a list containing the predicted sender of the email for
each doument in the eval folder
"""
#Use skTree's predict function to make a prediction based on trained tree
pred = self.tree.predict(xData)
#Return the prediction
return pred
def testSKTree():
"""
Used to test my SKTree
Predicts some random list of parameters
"""
s = SKTree()
knownX = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]]
knownY = [1,2,3,4]
unknownX = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]]
s.train(knownX, knownY, 5)
prediction = s.eval(unknownX)
print(prediction)
if __name__ == "__main__":
testSKTree()
|
f6815414dfd1ba7116f3d6448eac8bad96bb7790 | nal3x/IIPPython | /Rock-paper-scissors-lizard-Spock.py | 2,074 | 4.34375 | 4 | import random
def name_to_number(name):
"""
Helper function to convert number to string
"""
if name == "rock":
return 0
elif name == "Spock":
return 1
elif name == "paper":
return 2
elif name == "lizard":
return 3
elif name == "scissors":
return 4
else:
print "name to number ERROR"
def number_to_name(number):
"""
Helper function to convert string to number
"""
if number == 0:
return "rock"
elif number == 1:
return "Spock"
elif number == 2:
return "paper"
elif number == 3:
return "lizard"
elif number == 4:
return "scissors"
else:
print "number to name ERROR"
def rpsls(player_choice):
"""
This is the main function of the game.
It takes the player's choice as input and randomly makes a choice for the computer.
Finally it computes and prints the winner of the game.
"""
#prints a blank line
print
#prints player's choice and assigns a number to it
print "Player chooses", player_choice
player_number = name_to_number(player_choice)
#computes a number for the computer, converts it to a choice and prints it
comp_number = random.randrange(0,5)
comp_choice = number_to_name(comp_number)
print "Computer chooses", comp_choice
#computes the difference of the choices mod five
#this choice determines the winner
difference = (comp_number - player_number) % 5
#if the difference is 1 or 2, the first item wins
#if the difference is 3 or 4, the first item wins
if (difference == 1) or (difference == 2):
print "Computer wins!"
elif (difference == 3) or (difference == 4):
print "Player wins!"
elif (difference == 0):
print "Player and computer tie!"
else:
print "rpsls ERROR"
# test calls
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
|
8255f12f67b6703dc05b5f8d744aeb11070731cc | SuriyaaMurali/Practicals | /Prac 10/wiki.py | 313 | 3.9375 | 4 | import wikipedia
def wiki_search():
page_or_phrase = input('Type page name or phrase here:')
while page_or_phrase != '':
page_or_phrase = input('Type page name or phrase here:')
search_page = wikipedia.search(page_or_phrase)
print(wikipedia.summary(search_page))
wiki_search()
|
13e7a4992eff79908c94954b9039af1896bb7718 | leahmartin160/Pie-Chart | /Calculation.py | 736 | 3.515625 | 4 | from functools import reduce
cals = .038
examplearrayOfTweets = [
{
"tweet" : "tweet",
},
{
"tweet" : "tweet2",
},
{
"tweet" : "tweet3",
}
]
def hashtagCals(hashtag):
tweetAmt = len(hashtag)
totalCals = tweetAmt * cals
return totalCals
def add_cals_to_tweet(tweet):
calsForTweet = hashtagCals(tweet["tweet"])
return {
"calories": calsForTweet,
"tweet": tweet["tweet"]
}
def tweetToCals(tweet):
calsForTweet = hashtagCals(tweet["tweet"])
return calsForTweet
tweetsWithCalories = map(add_cals_to_tweet, examplearrayOfTweets)
calories = map(tweetToCals, examplearrayOfTweets)
sum = reduce((lambda x, y: x + y), calories)
print(sum)
|
05ab744bc4584cf52397deb41fcaf41a8aa3abde | bellos711/python_practice | /python/OOP/user_bank_accounts.py | 2,876 | 3.921875 | 4 |
class BankAccount:
def __init__(self, int_rate=0.01, balance=0):
self.account_balance = balance
self.interest_rate = int_rate
def deposit(self, amount):
self.account_balance += amount
return self
def withdraw(self, amount):
self.account_balance -= amount
return self
def display_user_balance(self):
print(f"Your Balance is: ${self.account_balance}")
def yield_interest(self):
while self.account_balance>0:
self.account_balance += self.account_balance*self.interest_rate
return self
return self
class User:
def __init__(self, name, email, account_count=0):
self.name = name
self.email = email
self.account_count = account_count
if self.account_count == 0:
self.account = BankAccount(int_rate=0.02, balance=0)
else:
self.account=[]
for i in range(0, self.account_count, 1):
self.account.append(BankAccount(int_rate=0.02, balance=0)) #= BankAccount(int_rate=0.02, balance=0)
def make_deposit(self, amount, account_index=0):
#self.account_balance += amount
if self.account_count == 0:
self.account.deposit(amount)
return self
else:
self.account[account_index].deposit(amount)
return self
def make_withdraw(self, amount, account_index=0):
#self.account_balance -= amount
if self.account_count == 0:
self.account.withdraw(amount)
return self
else:
self.account[account_index].withdraw(amount)
return self
def display_user_balance(self, account_index=0):
if self.account_count==0:
print(f"User: {self.name}, Balance: {self.account.account_balance}")
else:
print(f"User: {self.name}, User Account Number: {account_index}, Balance: {self.account[account_index].account_balance}")
# EXTRA METHOD
# def transfer_money(self, other_user, amount):
# self.make_withdraw(amount)
# other_user.make_deposit(amount)
# print(f"you transferred {amount} to {other_user.name}.")
# return self
kahlil = User('Kahlil', 'kb@sample.com')
print("USER WITH BANK ACCOUNTS version:")
kahlil.make_deposit(1000).make_deposit(2500).make_deposit(200).make_withdraw(1900).display_user_balance()
print("\n###########################################################")
print("USER WITH MULTIPLE BANK ACCOUNTS ACCESSED THROUGH ARRAY OF OBJECTS")
holmes = User('Holmes', 'hd@sample.com', 2)
print("USER WITH BANK ACCOUNTS version:")
holmes.make_deposit(1000, 1)
holmes.make_withdraw(200, 1)
holmes.display_user_balance(1)
print(f"SAME USER {holmes.name} WITH DIFF ACCOUNT")
holmes.make_deposit(2000, 0)
holmes.make_withdraw(500, 0)
holmes.display_user_balance(0)
|
9adbedcd5b4d825e8ad98de91df02878d917241d | hakancelebi/coding-exercises | /if-elif-else_enbüyüksayı.py | 444 | 4.09375 | 4 |
Sayı1 = int(input("Lütfen Birinci Sayıyı Giriniz: "))
Sayı2 = int(input("Lütfen İkinci Sayıyı Giriniz: "))
Sayı3 = int(input("Lütfen Üçüncü Sayıyı Giriniz: "))
if (Sayı1 >= Sayı2 and Sayı1 >= Sayı3):
print("En Büyük Sayı: ", Sayı1)
elif (Sayı2 >= Sayı1 and Sayı2 >= Sayı3):
print("En Büyük Sayı: ", Sayı2)
elif (Sayı3 >= Sayı1 and Sayı3 >= Sayı2):
print("En Büyük Sayı: ", Sayı3) |
f72f897b15889f9b6e2fbedfac37f32e585e6f3d | wobushimotou/Daily | /python/day2.py | 617 | 3.765625 | 4 | #!/usr/bin/env python
# coding=utf-8
def main():
#将华氏温度转化为摄氏温度
f = float(input('输入华氏温度:'));
print('%.1f华氏温度=%.1f摄氏温度'%(f,(f-32)/1.8))
#输入圆的半径计算周长和面积
import math
redius = float(input('输入半径:'))
print('半径为%.1f的圆的面积为:%.1f'%(redius,math.pi*redius**2))
print('半径为%.1f的圆的周长为:%.1f'%(redius,math.pi*redius*2))
#输入年份判断是不是闰年
def IsLeapYear(year):
return (year%100 != 0) and (year%4 == 0) or (year%400 == 0)
if __name__ == "__main__":
main()
|
5fba9373c8237a99367fb7640b3b141cbe637f79 | bitterengsci/algorithm | /九章算法/基础班LintCode/3.11.Search Range in Binary Search Tree.py | 1,844 | 3.8125 | 4 | #-*-coding:utf-8-*-
'''
Description
Given a binary search tree and a range [k1, k2], return node values within a given range in ascending order.
'''
# Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
"""
@param root: param root: The root of the binary search tree
@param k1: An integer
@param k2: An integer
@return: return: Return all keys that k1<=key<=k2 in ascending order
"""
def searchRange(self, root, k1, k2):
if not root:
return []
left = self.searchRange(root.left, k1, k2)
right = self.searchRange(root.right, k1, k2)
if root.val > k2:
return left
if root.val < k1:
return right
return left + [root.val] + right
'''
考点:
二叉查找树 :
二叉排序树或者是一棵空树,或者是具有下列性质的二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
题解:从给定的BST的根节点开始查找,如果位于[k1,k2],存入结果,向左右子树分别搜索。
'''
class Solution2:
def searchRange2(self, root, k1, k2):
ans = []
if root is None:
return ans
queue = [root]
index = 0
while index < len(queue):
if queue[index] is not None:
if k2 >= queue[index].val >= k1:
ans.append(queue[index].val)
queue.append(queue[index].left)
queue.append(queue[index].right)
index += 1
return sorted(ans)
|
1bdc19d8de69d8e070479f3029955ed1d786a36e | julietrubin/interview_cake | /2nd_largest_in_binary_tree.py | 456 | 3.8125 | 4 |
def get_largest_and_parent(root):
parent_node = root
largest_node = root.right
while(largest_node.right ! = None){
parent_node = current_node
largest_node = partent_node.right
}
return largest_node, parent_node
def get_second_largest(root):
largest_node, parent_node = get_largest_and_parent(root)
if largest_node.left == None:
return parent_node
largest_node, parent = get_largest_and_parent(current_node.left)
return largest_node |
f8199201bfcd287f4f4de7ba831cf638457ecab3 | summer-vacation/AlgoExec | /top1_interview/contains_duplicate.py | 499 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
File Name: contains_duplicate
Author : jing
Date: 2019-12-08
https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/578/
"""
class Solution:
def containsDuplicate(self, nums) -> bool:
nondup = set(nums)
if len(nondup) == len(nums):
return False
else:
return True
if __name__ == '__main__':
print(Solution().containsDuplicate([1,1,1,3,3,4,3,2,4,2]))
|
0184ec457da3090ec22089a151424caf1b1c352f | BRN33/RaspberryPi_HTTP_LED | /led.py | 798 | 3.5 | 4 | #!/usr/bin/env python3
import RPi.GPIO as GPIO
import os
def setupGPIO():
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18, GPIO.OUT)
def printTemperature():
temp = os.popen("/opt/vc/bin/vcgencmd measure_temp").read()
print("GPU temperature is {}".format(temp[5:]))
def controlLED():
try:
while True:
user_input = input(
"Turn LED On or Off with 1 or 0 (Ctrl-C to exit): ")
if user_input is "1":
GPIO.output(18, GPIO.HIGH)
print("LED is on")
elif user_input is "0":
GPIO.output(18, GPIO.LOW)
print("LED is off")
except KeyboardInterrupt:
GPIO.cleanup()
print("")
setupGPIO()
printTemperature()
controlLED()
|
38696cbed8b6a3491ef63b35e15a463309d1b2ba | lcongdon/tiny_python_projects | /14_rhymer/pig_latin.py | 1,894 | 3.96875 | 4 | #!/usr/bin/env python3
"""
Author : Lee A. Congdon <lee@lcongdon.com>
Date : 2021-09-01
Purpose: Tiny Python Projects pig latin exercise
"""
import sys
import os
import argparse
import re
import string
def get_args():
"""Parse arguments"""
parser = argparse.ArgumentParser(
description="Translate words to pig latin",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"text",
type=str,
help="Input text or file",
metavar="text",
)
return parser.parse_args()
def stemmer(word):
"""Return leading consonants (if any), and 'stem' of word"""
VOWELS = "aeiou"
CONSONANTS = "".join(
[char for char in string.ascii_lowercase if char not in VOWELS])
pattern = f"([{CONSONANTS}]+)?([{VOWELS}])(.*)"
word = word.lower()
match = re.match(pattern, word)
if match:
part1 = match.group(1) or ""
part2 = match.group(2) or ""
part3 = match.group(3) or ""
return (part1, part2 + part3)
else:
return (word, "")
def test_stemmer():
"""Test stemmer"""
assert stemmer("") == ("", "")
assert stemmer("pig") == ("p", "ig")
assert stemmer("cake") == ("c", "ake")
assert stemmer("smile") == ("sm", "ile")
assert stemmer("chair") == ("ch", "air")
assert stemmer("APPLE") == ("", "apple")
assert stemmer("RDZNL") == ("rdznl", "")
assert stemmer("123") == ("123", "")
def main():
"""Main program"""
exit_code = 0
args = get_args()
word = args.text
first_part, second_part = stemmer(word)
if second_part:
if first_part:
print(second_part + first_part + "ay")
else:
print(second_part + "yay")
else:
sys.stderr.write(f'Cannot translate "{word}"\n')
exit_code = 1
sys.exit(exit_code)
if __name__ == "__main__":
main()
|
117f21e46f8eac01d1819b7ee868589550c92e47 | chriscross00/cci | /str_permutations.py | 311 | 3.765625 | 4 | def permutations(word):
if len(word) == 1:
return word
perms = permutations(word[1:])
char = word[0]
result = []
for i in perms:
for j in range(len(i)+1):
result.append(perms[:j] + char + perms[j:])
return result
test = 'lse'
print(permutations(test))
|
3a19e3fa6d1fc2cf4562889dc3d0372b88ba054e | Pineappluh/AoC-2020 | /16/16-2.py | 2,154 | 3.5625 | 4 | import fileinput
def check_valid(ticket, valid_ranges):
for field in ticket.split(","):
field = int(field)
for range_1, range_2 in valid_ranges.values():
if range_1[0] <= field <= range_1[1] or range_2[0] <= field <= range_2[1]:
break
else:
return False
return True
def fits_range(ticket, valid_ranges):
fits = []
for field in ticket.split(","):
field = int(field)
fits.append(set())
for name, (range_1, range_2) in valid_ranges.items():
if range_1[0] <= field <= range_1[1] or range_2[0] <= field <= range_2[1]:
fits[-1].add(name)
return fits
data = [[], [], []]
index = 0
for line in fileinput.input():
if line == "\n":
index += 1
else:
data[index].append(line.strip())
field_ranges = data[0]
my_ticket = [int(x) for x in data[1][1].split(",")]
tickets = data[2][1:]
valid_ranges = dict()
for row in field_ranges:
info = row.split(":")
name = info[0]
range_info = info[1].strip().split(" ")
range_1_info = range_info[0].split("-")
range_1 = int(range_1_info[0]), int(range_1_info[1])
range_2_info = range_info[2].split("-")
range_2 = int(range_2_info[0]), int(range_2_info[1])
valid_ranges[name] = (range_1, range_2)
valid_tickets = []
for ticket in tickets:
if check_valid(ticket, valid_ranges):
valid_tickets.append(ticket)
possible_fields = []
for ticket in valid_tickets:
possible_fields.append(fits_range(ticket, valid_ranges))
field_names = ['UNKNOWN'] * len(valid_ranges.keys())
solved = set()
while 'UNKNOWN' in field_names:
for i, name in enumerate(field_names):
if name == 'UNKNOWN':
common_fields = set.intersection(*[x[i] for x in possible_fields]) - solved
if len(common_fields) == 1:
solved_field = list(common_fields)[0]
field_names[i] = solved_field
solved.add(solved_field)
solution = 1
for i, field_name in enumerate(field_names):
if field_name.startswith("departure"):
solution *= my_ticket[i]
print(solution)
|
7ed2c3d956df5406bacd37bed1cf26dee0954279 | aagolovchenko/Healthy-Lifestyle-App | /account.py | 557 | 3.703125 | 4 | def registration():
print("\n", "Welcome to the Healthy Lifestyle app", "\n", "Please, fill in the registration form:")
name = input("Name: ")
age = int(input("Full age: "))
weight = int(input("Weight in kilos: "))
hight = int(input("Hight in santimetres: "))
type_of_lifestyle = input("Type of lifestyle (active/not active): ")
def start_of_program():
print("\n", "Would you like to:", "\n", "a) Lose weight", "\n", "b)Gain weight", "\n", "c)Stay the same")
wish = input("Chose a-c: ")
registration()
start_of_program()
|
168eb5311f9cca4fc18ca4556e630d0f433e3fb1 | fmorenovr/ComputerScience_UNI | /CM334-Analisis_Numerico_I/computerAritm/computerAritmMain.py | 2,208 | 3.921875 | 4 | #!/usr/bin/python
# -*- encoding: utf-8 -*-
# x es el numero a methTruncar
# t es el numero de cifras a methTruncar
import math
from auxFuncBinary import *
def main():
'''
parte 1: redondeo truncamiento
'''
for i in range(15):
print str(methTrunc(0.0,i))+"\t"+str(i)
print
for i in range(15):
print str(methRedond(12.43543,i))+"\t"+str(i)
print str(methTrunc(0.0,-1))
print str(methRedond(0.0,-1))
'''
parte 2: binario a decimal
'''
binario = raw_input('Introduce el número binario a convertir a decimal: ')
binario = quitarZeros(binario)
correcto = verificarBinario(binario)
if correcto == 0:
print("Error al ingresar, solo ingrese numero binarios\n\n")
exit()
print("Su resultado en decimal es: " + str(binToInteger(binario)))
'''
parte 3: cambio de base
'''
numero = int(input('Introduce el número a cambiar de base: '))
base = int(input('Introduce la base: '))
print(cambio_base(numero, base))
'''
parte 4: int a binario
'''
decimal = int(input('Introduce el número entero a convertir a binario: '))
print(intToBinary(decimal))
'''
parte 5: decimal a decimal
'''
# entero = int(input('Introduce el número entero a convertir a decimal: '))
# a,b = intToDec(entero)
decimal = float(input('Introduce el número decimal 0<y<1 a convertir a decimal: '))
c,d = decToDec(decimal)
decimal1 = float(input('Introduce el número decimal >1 a convertir a decimal: '))
e,f = decToDec(decimal1)
# print(str(a)+"x10^"+str(b))
print(str(c)+"x10^"+str(d))
print(str(e)+"x10^"+str(f))
'''
parte 6: real a binario
'''
real = float(input('Introduce el número real a convertir a binario: '))
cifras = int(input('Introduce el número de cifras a mostrar en la fraccion: '))
entero = int(real)
fraccion=real-entero
enteraString = intToBinary(entero)
fraccionString = floatToBinary(fraccion,cifras)
if entero==0:
print('0.' + fraccionString)
else:
print(enteraString + '.' + fraccionString)
'''
parte 7: invertir cadena
'''
name = str(raw_input('Introduce el string a invertir: '))
print(reverseString(name))
if __name__=="__main__":
main()
|
1f304976f4e8c0d162d941ebcc8d7b0a66ace38a | lalitsharma16/python | /delrecurr.py | 314 | 3.78125 | 4 | #!/usr/bin/python
import set
def deleteReoccurringCharacters(string):
seenCharacters = set()
outputString = ''
for char in string:
if char not in seenCharacters:
seenCharacters.add(char)
outputString += char
return outputString
deleteReoccurringCharacters(aabbcc)
|
7b843ac78096b582369aab1d6d6b99e7ffb35397 | ketkimatkar/Minor-Project | /Jumble Word/game.py | 1,520 | 3.796875 | 4 | import tkinter as tk
import random
from tkinter.messagebox import showinfo
x=0
def game():
global x
if x==0:
start.destroy()
x=x+1
def check():
if entry1.get() == str:
showinfo("Congratulations", "You have guessed the word correctly")
else:
showinfo("Sorry", "Please Try again")
def resume():
win.destroy()
game()
words = ["coding", "stop", "start", "icecream", "google", "yahoo", "instagram", "facebook", "add", "car", "project","woman", "user", "race", "balloon", "apple", "banana", "pink", "black", "audi", "truck", "random","window", "help", "orange"]
word = random.randint(0, (len(words) - 1))
str = words[word]
s = ''.join(random.sample(str, len(str)))
win = tk.Tk()
win.title("Jumble Word Game")
label1 = tk.Label(win, text=s)
label1.grid(row=0, column=2, padx=8, pady=8)
entry1 = tk.Entry(win)
entry1.grid(row=1, column=2,padx=8,pady=8)
button1 = tk.Button(win, text="Submit", command=check, bg="gray")
button1.grid(row=3, column=0, padx=8, pady=8)
button2 = tk.Button(win, text="Try again", command=resume, bg="gray")
button2.grid(row=3, column=3, padx=8, pady=8)
win.mainloop()
start=tk.Tk()
start.title("Welcome To Game")
label=tk.Label(start,text="Let's start the game. Click on Play button")
label.grid(row=0,column=0,padx=8,pady=8)
button=tk.Button(start,text="PLAY",command=game,bg="gray")
button.grid(row=2,column=2,padx=8,pady=8)
start.mainloop()
|
0642986e74b9c564959141eca06c8a4867294e3b | chigginss/Coding-Challenges | /building_binary_tree.py | 1,793 | 4.21875 | 4 |
"""Binary Tree"""
class Node:
def __init__(self, val):
self.left = None
self.right = None
self.val = val
class Tree:
def __init__(self):
self.root = None
def getRoot(self):
return self.root
def add_node(self, val):
if(self.root == None):
self.root = Node(val)
else:
self.add_node(val, self.root)
def add_node_in_tree(self, val, node):
if(val < node.value):
if(node.left is not None):
self.add_node(val, node.left)
else:
node.left = Node(val)
else:
if(node.right is not None):
self.add_node_in_tree(val, node.right)
else:
node.right = Node(val)
def find(self, val):
if(self.root is not None):
return self.find_value(val, self.root)
else:
return None
def find(self, val, node):
if(val == node.value):
return node
elif(val < node.value and node.left is not None):
self.find_value(val, node.left)
elif(val > node.value and node.right is not None):
self.find_value(val, node.right)
def deleteTree(self):
# garbage collector will do this for us.
self.root = None
def printTree(self):
if(self.root != None):
self.printTree(self.root)
def printTree(self, node):
if(node != None):
self.printTree(node.left)
print str(node.value) + ' '
self.printTree(node.right)
# 3
# 0 4
# 2 8
tree = Tree()
tree.add(3)
tree.add(4)
tree.add(0)
tree.add(8)
tree.add(2)
tree.printTree()
print (tree.find(3)).v
print tree.find(10)
tree.deleteTree()
tree.printTree() |
5c228af1e8cbfbb941eaa94671cdb03d77e13f26 | dntai/dntai_python_machine_learning_tutorial | /Data Preprocessing Template/dntai_data_preprocessing_template.py | 1,353 | 3.546875 | 4 | # Data preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Data.csv');
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
# Taking care of missing data
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values='NaN', strategy='mean', axis=0)
imputer.fit(X[:,1:3]);
X[:,1:3] = imputer.transform(X[:,1:3]);
# Update and Save dataset
dataset.iloc[:, :-1] = X
dataset.to_csv('Data_out.csv');
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder();
X[:, 0] = labelencoder_X.fit_transform(X[:, 0]);
onehotendcoder = OneHotEncoder(categorical_features=[0]);
X = onehotendcoder.fit_transform(X).toarray();
labelencoder_Y = LabelEncoder();
y = labelencoder_Y.fit_transform(y);
float_formatter = lambda x: "%.2f" % x
np.set_printoptions(formatter={'float_kind':float_formatter});
X
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0);
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler();
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
|
f07f23672f39cbcf5593c1481ea84e46ce4ebc53 | Aasthaengg/IBMdataset | /Python_codes/p03197/s464093269.py | 150 | 3.9375 | 4 | N=int(input())
odd=False
for i in range(N):
a=int(input())
if a%2==1:
odd=True
if odd:
print("first")
else:
print("second")
|
0144748d40f02cfa322b76b65d8a0adc53e882d6 | Irish-Life/Coding-Challenges | /Week4/Sam/solution.py | 933 | 4.1875 | 4 | """
An ISBN number is legal if it consists of 10 digits and
d_1 + 2*d_2 + 3*d_3 + ... + 10*d_10 is a multiple of 11.
The ISBN number 0-201-31452-5 is valid.
1*5 + 2*2 + 3*5 + 4*4 + 5*1 + 6*3 + 7*1 + 8*0 + 9*2 + 10*0 = 88
and 88 is a multiple of 11.
Write a program which validates whether an ISBN number.
For Ex:
1) if user inputs 8535902775 then it should print "Valid"
2) if user inputs 1843369283 then it should print "Not Valid"
"""
# the nicely laid out one
def is_valid(isbn):
if len(isbn) != 10:
return False
isbn = reversed(isbn)
coefficients = [(ord(c) - 48) * (i+1) for i, c in enumerate(isbn)]
return sum(coefficients) % 11 == 0
print(is_valid("0201314525"))
print(is_valid("1843369283"))
# the one liner
def one_line(isbn):
return sum([(ord(c) - 48) * (i+1) for i, c in enumerate(reversed(isbn))]) % 11 == 0 and len(isbn) == 10
print(one_line("0201314525"))
print(one_line("1843369283"))
|
b347763391f163cf94e84cd74ed1b519f35a6764 | bite7523aszx/Python-Work | /temp05.py | 160 | 3.65625 | 4 | bb = 6
for ii in range(0,30,1) :
print(ii+1," ==> ",end=" ")
col = ii // bb # 求整數
row = ii % bb # 求餘數
print("(",col+1,",",row+1,")") |
750a41bfd33412623cc5f40d26f42dfb38277d43 | wartrax13/exerciciospython | /Livro Nilo Ney - Programação Python/Exercicios/Exercicio_5.24.py | 475 | 3.96875 | 4 |
n = int(input("Digite um número:"))
if n < 0:
print("Número inválido. Digite apenas valores positivos")
else:
if n >= 1:
print("2")
p = 1
y = 3
while p<n:
x = 3
while(x < y):
if y % x == 0:
break
x = x + 2
if x == y:
print(x)
p = p + 1
y = y + 2
else:
print('Não é primo.') |
06205ba98ce92a63cbd7ef672170bd64a8192798 | DivyaReddyNaredla/python_programs_practice | /class_bank_example.py | 654 | 3.640625 | 4 | class bankaccount:
def __init__(self):#constructor
self.balance=4000
def withdraw(self,amount):
self.balance-=amount
return self.balance
def deposit(self,amount):
self.balance+=amount
return self.balance
class sbi(bankaccount):
def __init__(self,min_balance):
bankaccount.__init__(self)
self.min_balance=min_balance
def withdraw(self,amount):
if self.balance - amount < self.min_balance:
print("Sorry, minimum balance must be maintained")
else:
print(bankaccount.withdraw(self,amounnt))
a=sbi(2000)
a.withdraw(1000)
|
ed51a3ec4507cf3b46ba396c5b4e7989d54b86f1 | codinglq/first_coding_python | /client_fun.py | 1,767 | 3.515625 | 4 | #!/usr/bin/env python
# coding=utf-8
import thread
import server_fun
import socket
import os
#我们自己指定ip和端口
server_ip='127.0.0.1'
server_port=8080
#应该添加上字符串太长的问题
msg_len=210
max_name_len=10
max_msg_str=100
def thread_client(client_sock):
while True:
msg_buf_recv=client_sock.recv(msg_len)
if not msg_buf_recv:
print '数据接收失败,可能是服务器关闭了,或者网络重名'
os._exit(0)
else:
print '%s:\n内容:%s\n来自:%s' %server_fun.unpack_msg(msg_buf_recv)
#这里应该添加上接受失败的处理
def client_server():
print '客户端主线程'
#准备握手包
while True:
client_name=raw_input('请输入昵称:')
if len(client_name)>10:
print '输入的昵称过长 请小于是个字符'
else:
break
str_buf=' hello server'#服务器欢迎语
msg_buf=server_fun.pack_msg(server_fun.get_time_str(),str_buf,client_name)
#准备socket通信
client_sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client_sock.connect((server_ip,server_port))#改写成更灵活的形式
client_sock.send(msg_buf)#发送握手包
#下面要启动线程用来接收消息
thread.start_new_thread(thread_client,(client_sock,))
while True:
while True:
send_str_buf=raw_input('请输入要发送的消息:\n')
if len(send_str_buf)>100:
print '你说的话太长了'
else:
break
msg_buf=server_fun.pack_msg(server_fun.get_time_str(),send_str_buf,client_name)
client_sock.send(msg_buf)
#测试客户端
if __name__=='__main__':
client_server()
|
b86d2315a5172547e381fa8853444962334bc39b | susanahidalgo/python_class | /10-Lists-Iteration/the-range-function.py | 159 | 3.953125 | 4 | #for number in range(5):
#print(number)
for number in range(10, 101, 10):
print(number)
print()
for number in range(99, -1, -11):
print(number) |
84f2d01d6bc2ee1350b57969150c8296deee7964 | SunShine5152/python | /29/task/2.py | 403 | 3.765625 | 4 | # -*- coding: utf-8 -*-
def file_write(file_name):
f = open(file_name, 'w')
print('请输入内容【单独输入\':q\'保存退出】:')
while True:
file_content = input()
if file_content != ':q':
f.write('%s\n' % file_content)
else:
break
f.close()
file_name = input('请输入文件名:')
file_write(file_name)
|
312ed40950c45f0e835cdf12c64e685760881c03 | liuluyang/mk | /作业练习题/早自习练习题/练习题05.py | 4,322 | 3.609375 | 4 |
from typing import Iterable, Iterator, Generator
def check(obj):
print(isinstance(obj, Generator), isinstance(obj, Iterable), isinstance(obj, Iterator))
"""
实现:
range()
int()
enumerate()
zip()等函数
"""
############################################ range()实现
def range_new_01(end):
if not isinstance(end, int):
raise TypeError('参数必须是整数')
start = 0
while start < end:
yield start
start += 1
# print(list(range(10)))
# print(list(range_new_01(10)))
def range_new_02(start, end):
if not isinstance(start, int) or not isinstance(end, int):
raise TypeError('参数必须是整数')
start = start
while start < end:
yield start
start += 1
# print(list(range(2, 11)))
# print(list(range_new_02(2, 11)))
def range_new_03(start, end, step):
if not isinstance(start, int) or not isinstance(end, int) or not isinstance(step, int):
raise TypeError('参数必须是整数')
if step == 0:
raise ValueError('步长不能为0')
start = start
while start < end:
yield start
start += step
# for i in range(2, 11, 2):
# print(i)
# for i in (range_new_03(2, 11, 2)):
# print(i)
def range_new_04(start, end, step):
if not isinstance(start, int) or not isinstance(end, int) or not isinstance(step, int):
raise TypeError('参数必须是整数')
if step == 0:
raise ValueError('步长不能为0')
start = start
while start > end:
yield start
start += step
# print(list(range(22, 11, -2)))
# for i in range_new_04(22, 11, -2):
# print(i)
def range_new_05(*args):
"""
range()函数完整实现
:param args:
:return:
"""
start, end, step = 0, None, 1
if len(args) == 1:
end = args[0]
elif len(args) == 2:
start, end = args[0], args[1]
elif len(args) == 3:
start, end, step = args[0], args[1], args[2]
else:
raise TypeError('参数错误')
if not isinstance(start, int) or not isinstance(end, int) or not isinstance(step, int):
raise TypeError('参数必须是整数')
if step == 0:
raise ValueError('步长不能为0')
tag = '<' if step > 0 else '>'
s = '%s %s %s' % (start, tag, end)
while eval(s):
yield start
start += step
s = '%s %s %s' % (start, tag, end)
# print(list(range(2)))
# print(list(range_new_05(2)))
######################################################int()函数实现
def int_new(obj, base=10):
"""
int()
:param obj:
:param base:
:return:
"""
tag = 1
if isinstance(obj, int):
return obj
elif isinstance(obj, float):
# obj = str(obj // 1)[:-2]
obj = str(obj).split('.')[0]
if not isinstance(obj, str):
raise TypeError
obj = obj.strip()
if obj.startswith('-'):
tag = -1
obj = obj[1:]
elif obj.startswith('+'):
obj = obj[1:]
b_10 = {str(i): i for i in range(10)}
b_02 = {str(i): i for i in range(2)}
b_16 = {'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15}
b_16.update(b_10)
data_match = {2: b_02, 16: b_16, 10: b_10}
num = 0
for index, per in enumerate(obj[::-1]):
num += data_match[base][per] * base ** index
return num * tag
############################################# 练习题答案02
"""
1.实现enumerate()函数
"""
def enum_new(obj, num=0):
for i in obj:
yield (num, i)
num += 1
"""
2.实现zip()函数
"""
def zip_new(*args):
args = [iter(a) for a in args]
while True:
lst = []
try:
for a in args:
lst.append(next(a))
except StopIteration:
break
yield tuple(lst)
############################################## 思路
"""
3. 实现int()函数
转换方法
'123'
1 * 10**2 + 2 * 10**1 + 3 * 10**0
"""
def test():
s = '1a'
b_10 = {str(i):i for i in range(10)} # 十进制
b_02 = {str(i):i for i in range(2)} # 二进制
b_16 = {'a':10, 'b':11, 'c':12, 'd':13, 'e':14, 'f':15} #十六进制
b_16.update(b_10)
num = 0
for index, per in enumerate(s[::-1]):
print(index, per)
num += b_16[per] * 16 ** index
print(num, type(num))
|
2f56d13986603730cd392c942cb771b4075e0528 | anju-netty/pylearning | /stack_linkedlist_test.py | 1,376 | 3.5 | 4 | import unittest
import stack_linkedlist
class TestStackLinkedList(unittest.TestCase):
def test_push_to_sack(self):
stack = stack_linkedlist.Stack()
stack.push(10)
stack.push(20)
stack.push(50)
stack.push(50)
stack.push(50)
stack.push(50)
stack.push(50)
stack.push(50)
result = stack.view_stack()
print(result)
expected = [50,50,50,20,10]
self.assertEqual(result,expected)
def test_peek_sack(self):
stack = stack_linkedlist.Stack()
stack.push(5)
stack.push(1)
result = stack.peek()
expected = 1
self.assertEqual(result,expected)
def test_pop(self):
stack = stack_linkedlist.Stack()
stack.push(5)
stack.push(4)
stack.push(1)
stack.pop()
result = stack.view_stack()
print(result)
expected = [4,5]
self.assertEqual(result,expected)
def test_pop_empty(self):
stack = stack_linkedlist.Stack()
stack.push(5)
stack.push(4)
stack.push(1)
stack.pop()
stack.pop()
stack.pop()
stack.pop()
stack.pop()
stack.pop()
result = stack.view_stack()
print(result)
expected = []
self.assertEqual(result,expected)
|
2ebbffc011c7293c6af4ed64bc4c3d3b1b97bd15 | Ramtecs/SelftaughtPythonCourse | /forloops.py | 1,213 | 3.953125 | 4 | _author_ = 'Ramses Murillo'
'''/import datetime library
import datetime
Print("Creation date is: ", datetime.datetime.now())
'''
import datetime
todaysdate = datetime.datetime.now()
print("File run", todaysdate)
name = "ramses"
for letter in name:
print(letter)
'''
1. Print each item in the following list: ["The Walking Dead", "Entourage", "The Sopranos", "The Vampire Diaries"].
2. Print all the numbers from 25 to 50.
3. Print each item in the list from the first challenge and their indexes.
'''
#1
list = ["The Walking Dead", "Entourage", "The Sopranos", "The Vampire Diaries"]
for item in list:
print(item)
#2
for x in range(25,51):
print(x)
#3
list = ["The Walking Dead", "Entourage", "The Sopranos", "The Vampire Diaries"]
for item in list:
x = list.index(item)
print("index for: " +"'"+ item+"'",x)
'''
output:
File run 2019-08-02 23:26:36.628918
r
a
m
s
e
s
The Walking Dead
Entourage
The Sopranos
The Vampire Diaries
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
index for: 'The Walking Dead' 0
index for: 'Entourage' 1
index for: 'The Sopranos' 2
index for: 'The Vampire Diaries' 3
Process finished with exit code 0
'''
|
0f119bd6ae74ef5b398d515bcf341c33f1c85c5b | guilhermelopeseng/maquinas-eletricas | /ex05.py | 965 | 3.5625 | 4 | # Programa para o calculo das correntes no estator, de magnetização e no rotor
import numpy as np
import matplotlib.pyplot as plt
import math
Vo = float(input('Informe a tensão de fase em volts: '))
print('\nInformações necessários do circuito equivalente por fase de um motor de indução.')
r1 = float(input('Informe a resistência do estator R1 em ohms: '))
x1 = float(input('Informe a reatância do estator jX1 em ohms: '))
xm = float(input('Informe o paralelo da resistência com a reatância de magnetização em ohms: '))
x2 = float(input('Informe a reatância refletida para o primário do rotor jX2 em ohms: '))
r2 = float(input('Informe a resistência refletida para o primpario do rotor R2 em ohms: '))
Vth = Vo*(xm/(x1+xm))
Rth = r1*(xm/(x1+xm))**2
Xth = x1
Nmec = np.linspace(0,1800,6000)
s = np.linspace(1,0,6000)
Tind = ((3*(Vth**2)*r2/s)/((2*math.pi*Nmec/(60*(1-s)))*((Rth + r2/s)**2 + (Xth + x2)**2)))
plt.plot(Nmec, Tind)
plt.show()
|
626d73b6641e78e83a066ea5316ca5f043792954 | skini/Programming-Style-Examples | /HW1/census.py | 523 | 3.8125 | 4 | #Shloka Kini
#This is the module for the Intermediate Assignment
#It contains one function, which returns the list of Pop12 values and their corresponding
#state names, in a tuple list
class Census:
def __init__(self):
self.filename = 'NST_EST2012_ALLDATA.csv'
self.file = open(self.filename, 'r')
self.all_lines = self.file.readlines()
def popestimate(self):
all_vals = []
for line in self.all_lines:
columns = line.split(',')
all_vals.append((columns[4],columns[9]))
return all_vals
|
93692b089f7087b6e8ca50f460abb69fde727dda | aryan-shrivastava09/100DaysofCode | /day17-Start/main.py | 711 | 4.125 | 4 | class User:
def __init__(self, id, username):
print("New user being created....")
self.id = id
self.username = username
self.followers = 0
self.following = 0
def follow(self, user):
self.following += 1
user.followers += 1
user_1 = User("007", "James Bond")
print(user_1.id)
#user_1.username = "James Bond" same as passing the value of attribute while creating an object
print(user_1.username)
#print(user_1.followers)
user_2 = User("001", "Aryan Srivastava")
print(user_2.id)
print(user_2.username)
user_2.follow(user_1)
print("user 2 is following user 1")
print(f"Followers of user 1 = {user_1.followers}")
print(f"Following of user 2 = {user_2.following}") |
dff5910922636e6324d45bc32d399bb903d376ca | Zephyrhou/Projet-Progra | /available-attack.py | 2,841 | 3.6875 | 4 | def available_attack(name_attack, player, hero):
"""Checks whether the hero can or not use a special capacity
Parameters:
-----------
name_attack: Name of the special capacity the hero wants to use (str)
player: Level, number of point, etc. of heroes of the player (dict)
hero: Name of the hero using a special capacity (str)
Return:
-------
availability: Whether the hero can use the special capacity or not (bool)
Notes:
------
availability is true if the hero can use the special capacity and false otherwise.
Version:
--------
specification: Manon Michaux (v.2 26/04/19)
implementation: Manon Michaux (v.3 01/05/19)
"""
# If player is on level 1 he can't use a special capacity yet
if player[hero]['level'] < 2:
return False
# Checks whether the cool down is at 0 or not
if player[hero]['cooldown'] != 0:
return False
# Checks whether the hero has a level high enough in order to use a special capacity
if player[hero]['class'] == 'barbarian':
if name_attack == 'energise':
if player[hero]['level'] >= 2:
return True
elif name_attack == 'stun':
if player[hero]['level'] >= 3:
return True
else:
return False
elif player[hero]['class'] == 'healer':
if name_attack == 'invigorate':
if player[hero]['level'] >= 2:
return True
elif name_attack == 'immunise':
if player[hero]['level'] >= 3:
return True
else:
return False
elif player[hero]['class'] == 'mage':
if name_attack == 'fulgura':
if player[hero]['level'] >= 2:
return True
elif name_attack == 'ovibus':
if player[hero]['level'] >= 3:
return True
else:
return False
elif player[hero]['class'] == 'rogue':
if name_attack == 'reach':
if player[hero]['level'] >= 2:
return True
elif name_attack == 'burst':
if player[hero]['level'] >= 3:
return True
else:
return False
player1 = {'Baz': {'class': 'barbarian', 'level': 4, 'life_points': 10, 'victory_points': 0, 'damage_points': 2,
'cooldown': 0},
'Lee': {'class': 'healer', 'level': 1, 'life_points': 10, 'victory_points': 0, 'damage_points': 2,
'cooldown': 0},
'May': {'class': 'mage', 'level': 1, 'life_points': 10, 'victory_points': 0, 'damage_points': 2,
'cooldown': 0},
'Rob': {'class': 'rogue', 'level': 1, 'life_points': 10, 'victory_points': 0, 'damage_points': 2,
'cooldown': 0}}
print(available_attack('energise', player1, 'Baz'))
|
de47eaee3c73d1089e81a09154b607fba73b72a2 | vimleshtech/python_jan | /2.Code2_ConditionEx.py | 1,084 | 3.9375 | 4 | sales = int(input('enter sale amount :'))
#if condition
tax =0
if sales>1000:
tax = sales*.18
total = sales+tax
print(total)
#if else condition
tax =0
if sales>1000:
tax = sales*.18
else:
tax = sales*.05
total = sales+tax
print(total)
##if elif ...
tax =0
if sales>100000:
tax = sales*.18
elif sales>10000:
tax = sales*.12
elif sales>1000:
tax = sales*.05
else:
tax = 0
total = sales+tax
print(total)
##show greater number from three inputs
a = int(input('enter data :'))
b = int(input('enter data :'))
c = int(input('enter data :'))
if a>b and a>c:
print('a is gt')
elif b>a and b>c:
print('b is gt')
else:
print('c is gt')
#nested condition
if a>b:
if a>c:
print('a is gt')
else:
print('c is gt')
else:
if b>c:
print('b is gt')
else:
print('c is gt')
|
5f4dde669d528466a6d6699b229bb5cff1aa62e3 | nbvc1003/python | /ch05_4/range3.py | 136 | 3.78125 | 4 |
#1부터 10까지 중에서 홀수만 숫자 사이에 ',' 를 출력
for i in range(1,11):
if i%2==1:
print(i, end=',')
|
499cbe00f8e71bd7c5e46aace25907efe6a88a0d | santanu5670/Python | /coding/11/multi_level.py | 895 | 3.96875 | 4 | class A:
def __init__(self,c,d):
self.a1=c
self.b1=d
def add(self):
self.c=self.a1+self.b1
print("The addition is",self.c)
class B(A):
def __init__(self, c, d):
super().__init__(c,d)
self.a2=c
self.b2=d
def sub(self):
self.d=self.a2-self.b2
print("The difference is=",self.d)
class C(B):
def __init__(self, c, d):
super().__init__(c, d)
self.a3=c
self.b3=d
def mul(self):
self.e=self.a3*self.b3
print("The multiplication is",self.e)
class D(C):
def __init__(self, c, d):
super().__init__(c, d)
self.a4=c
self.b4=d
def dev(self):
self.f=self.a4//self.b4
print("The Division is",self.f)
a=int(input("Enter First Number="))
b=int(input("Enter Second Number="))
obj=D(a,b)
obj.add()
obj.sub()
obj.mul()
obj.dev() |
cb222623d9b1f60cb01fc486b4fb61a60df05393 | daniel-reich/turbo-robot | /APNhiaMCuRSwALN63_11.py | 1,254 | 4.40625 | 4 | """
A string is an **almost-palindrome** if, by changing **only one character** ,
you can make it a palindrome. Create a function that returns `True` if a
string is an **almost-palindrome** and `False` otherwise.
### Examples
almost_palindrome("abcdcbg") ➞ True
# Transformed to "abcdcba" by changing "g" to "a".
almost_palindrome("abccia") ➞ True
# Transformed to "abccba" by changing "i" to "b".
almost_palindrome("abcdaaa") ➞ False
# Can't be transformed to a palindrome in exactly 1 turn.
almost_palindrome("1234312") ➞ False
### Notes
Return `False` if the string is already a palindrome.
"""
def almost_palindrome(txt):
backwardIndex = -1
invalidIndexes = []
almostPalindrome = False
# Obtain the indexes where the characters are not the same
for i in range(0, len(txt) // 2):
if txt[i] != txt[backwardIndex]:
invalidIndexes.append((i, backwardIndex))
backwardIndex -= 1
# Swap the characters where the characters are not the same
for (startingIndex, backwardIndex) in invalidIndexes:
chars = list(txt)
chars[backwardIndex] = chars[startingIndex]
string = "".join(chars)
if string == string[::-1]:
return True
return almostPalindrome
|
d9bf6e95706902329184fc07f7634a9a87657b77 | bc24/cbm | /Python 3.8/Tag2 21.11.2019/email2.py | 361 | 3.546875 | 4 | while True:
email = input("Bitte E-Mail Adresse eingeben: ")
if email.count("@") == 1:
email_parts = email.split("@")
if email_parts[1].count(".") > 0:
if len( email_parts[0] ) > 0 :
print(f"E-Mail-Adresse: {email}")
break
print("Fehlerhafte E-Mail-Adresse [0xc12344]")
|
23274ee46e6a480ece5c8a86c393c94ee9c5f09e | JoseAntonioVazquezGabian/Tarea-02 | /porcentajes.py | 469 | 3.96875 | 4 | #encoding: UTF-8
# Autor: Jose Antonio Vazquez Gabian, A01746585
# Descripcion: programa que calcula el porcentaje de hombres y mujeres inscritos en una clase
# A partir de aquí escribe tu programa
hombres= int(input("Numero de hombres inscritos: "))
mujeres= int(input("Numero de mujeres inscritas: "))
total= hombres + mujeres
h=(hombres*100)/total
m=(mujeres*100)/total
print("Total inscritos: ",total)
print("Porcentaje de Hombres", h, "%")
print("Porcentaje de mujeres", m, "%")
|
ac4cbc40dedeaa48677ffc56877e9744aab8faeb | Divya5504/PYTHON | /PythonSets.py | 767 | 4.375 | 4 | new_list = ['a', 'a', 'b', 'b', 'c', 'c', 'divya', 'tulasi', 'hyd', 20]
print("list :-", new_list)
# list as a set
new_set = set(new_list)
print("set:-", new_set) # no data retadancy
print(type(new_set)) # to check the the type of class
# intersection union amd difference operation in set
list1 = ['a', 'a', 'b', 'd', 'f', 'g', 'r', 's', 'z']
set1 = set(list1)
print(set1)
list2 = ['b', 'h', 'j', 'e', 'a', 'z', 's', 'm', 'f']
set2 = set(list2)
print(set2)
print(set1.intersection(set2)) # shows the common elements
print(set1.union(set2)) # combination with no duplicate
print(set1.difference(set2)) # remove common
print(set1.symmetric_difference(set2)) # show the symmetric difference
# we also use ^ operator as a symmetric_difference
print(set1 ^ set2)
|
f95247711d5d3508e7b8af17ff3bede7c7f1b261 | knightrohit/monthly_challenges | /leetcode_nov_2020/05_min_cost_to_move_chips.py | 327 | 3.921875 | 4 | """
Time Complexity = O(N)
Space Complexity = O(1)
"""
class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
even = odd = 0
for i in position:
if i%2 == 0:
even += 1
else:
odd += 1
return min(odd, even) |
1da3d971a15cc85c6777a16ec01073993a50f184 | patrickhu1/python-100-practices | /14.py | 593 | 3.953125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/7/28 17:18
# @Author : Patrick.hu
# @Site :
# @File : 14.py
# @Software: PyCharm
# 题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
list1 = []
def divide_num(n):
m = n
for i in range(2, n):
while n % i == 0:
list1.append(i)
n = n // i
if list1:
print(str(m) + '=' + '*'.join([str(x) for x in list1]))
else:
print("输入的数不可分解")
if __name__ == '__main__':
divide_num(1000)
|
5401175b3382540fb21d7f03c312286b24d4db8f | vergiliu/python | /ProjectEuler/1.py | 475 | 3.828125 | 4 | class IsMultipliedClass():
def by3(self, number):
if 0 == number % 3:
return True
else:
return False
def by5(self, number):
if 0 == number % 5:
return True
else:
return False
if __name__ == "__main__":
theSum = 0
myClass = IsMultipliedClass()
for number in range(1, 100000):
if myClass.by3(number) or myClass.by5(number):
theSum += number
print "theSum for 1000 = " + str(theSum)
|
6981f907c21bd4cfb868ee1e15da915a1b8226f4 | ashokjain001/Python | /anagram2.py | 184 | 3.875 | 4 | def anagram2(s1,s2):
s1 = list(s1)
s2 = list(s2)
s1.sort()
s2.sort()
if s1 == s2:
return True
else:
return False
print anagram2('abcd','dcba') |
acf5f4c33eac03f4a93e5aceafcf89d44be08a40 | dimkary/Python-tests | /Kattis/carrots.py | 263 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 20 09:49:20 2018
@author: karips
Solves the "Solving for Carrots" Kattis problem
"""
x = input().split(' ')
nums = [int(i) for i in x]
for i in range(nums[0]):
input()
print((nums[-1]))
|
a89131363258eb4a3a747368db0e524fdc3c3564 | lyiris22/mini_tidy_python | /tests/test_my_dropna.py | 1,043 | 3.59375 | 4 |
# Feb 2019
# This script contains tests for the my_dropna function
# The function creates a new dataframe by removing the rows with "NaN" values in the original dataframe
# input: dataframe
# output: dataframe
#------------------------------------
# Required packages
import pandas as pd
import pytest
#------------------------------------
# create dataframes for testing
# test input
s1 = pd.DataFrame({"A":[25,15,None,30], "y": [0,1,0, None], "z": ["Yes", "No", "Yes", "No"]})
# test output
s2 = pd.DataFrame({"A":[25,15], "y": [0,1], "z": ["Yes", "No"]})
# Testing methods
def test_my_dropna_normal():
'''Test normal dataframe'''
d1_test = my_dropna(input_df)
assert d1_test.equals(output_df), "normal dataframe, rows with NAs removed"
def test_my_dropna_wrong_input():
'''When the input data is not a dataframe, return error message'''
# input is not a dataframe, should return None and display error message
d7_test = my_dropna([1,2,3])
assert d7_test is None, "Error: Expect input to be a dataframe"
|
5a16872a0a29492826468f66deec99c4293513f8 | brendansailer/Advent-Of-Code-2020 | /day13/program1.py | 550 | 3.796875 | 4 | #!/usr/bin/env python3
import sys
import math
def calculate_time():
time = int(sys.stdin.readline())
busses = [int(bus) for bus in sys.stdin.readline().split(',') if bus != 'x']
closest_bus_id = 0
time_waiting = float('inf')
for bus in busses:
departure = math.ceil(time/bus)*bus
if departure-time < time_waiting:
time_waiting = departure-time
closest_bus_id = bus
return closest_bus_id * time_waiting
def main():
print(calculate_time())
if __name__ == '__main__':
main()
|
4d1f03be7ff994316da56188bcb61c584e114a96 | Jackyzzk/Cracking-the-Coding-Interview-6 | /py-程序员面试金典-面试题 05.07. 配对交换.py | 814 | 3.859375 | 4 | class Solution(object):
"""
配对交换。编写程序,交换某个整数的奇数位和偶数位,尽量使用较少的指令
(也就是说,位0与位1交换,位2与位3交换,以此类推)。
输入:num = 2(或者0b10)
输出 1 (或者 0b01)
输入:num = 3
输出:3
num的范围在[0, 2^30 - 1]之间,不会发生整数溢出。
链接:https://leetcode-cn.com/problems/exchange-lcci
"""
def exchangeBits(self, num):
"""
:type num: int
:rtype: int
"""
odd = 0x55555555
even = 0xaaaaaaaa
a = num & odd
b = num & even
ret = (a << 1) | (b >> 1)
return ret
def main():
num = 3
test = Solution()
ret = test.exchangeBits(num)
print(ret)
if __name__ == '__main__':
main()
|
f45a33ef18f8deef6234f35b27f3780a81f35a99 | eslemcataler/python_final | /07_try_except.py | 274 | 3.734375 | 4 | sayi1=input("Sayı 1:")
sayi2=input("Sayı 2:")
try:
sayi1=int(sayi1)
sayi2=int(sayi2)
print(sayi1/sayi2)
except ZeroDivisionError:
print("Bir sayı 0'a bölünemez")
except ValueError:
print("Lütfen 10'luk tabanlı bir sayı giriniz.")
|
36223dfc1c445e5b01eb463deb4c65b3d4ce681d | impiyush83/code | /CSCI-B505/exam/Submission Material/knapsack.py | 3,042 | 3.59375 | 4 | import numpy as np
def knapsack_dynamic(items, weight, number_items, curr_item):
"""
Builds a DP table by top down approach
:param items: list
:param weight: int
:param number_items: int
:param curr_item: int
:return: list
"""
x = number_items - curr_item - 1
y = weight
if curr_item >= number_items or weight <= 0:
return 0
if dp[x][y] != 0:
return dp[x][y]
if weight < items[curr_item]:
dp[x][y] = knapsack_dynamic(
items,
weight,
number_items,
curr_item + 1
)
else:
dp[x][y] = max(
items[curr_item] +
knapsack_dynamic(
items,
weight - items[curr_item],
number_items,
curr_item + 1
),
knapsack_dynamic(
items,
weight,
number_items,
curr_item + 1
)
)
return dp[x][y]
def backtrack(max_value_obtained, knapsack_size, items, number_items):
"""
Backtracks through DP table to find the items of the subset that sums
closest to knapsack_size
:param max_value_obtained: int
:param knapsack_size: int
:param items: list
:param number_items: int
:return: None
"""
print("Subset of weights which sum up to {} are:".format(knapsack_size))
ans = []
for i in range(number_items - 1, 0, -1):
if max_value_obtained <= 0:
break
if max_value_obtained - items[number_items - i - 1] \
== dp[i - 1][knapsack_size - items[number_items - i - 1]]:
ans.append(items[number_items - i - 1])
index = number_items - i
max_value_obtained -= items[number_items - i - 1]
knapsack_size -= items[number_items - i - 1]
if knapsack_size > 0:
temp = items[index:]
if knapsack_size > min(temp):
temp2 = np.array([knapsack_size] * len(temp)) - np.array(temp)
for i in range(len(temp2)):
if temp2[i] < 0:
temp2[i] = 10000
ans.append(items[list(temp2).index(min(temp2)) + index])
print(ans)
if __name__ == "__main__":
items = [5, 23, 27, 37, 48, 51, 63, 67, 71, 75, 70, 83, 889, 91, 101, 112,
121, 132, 137, 141, 143, 147, 153, 159, 171, 181, 190, 191]
print("Bag of items :", sorted(items))
print("Total Item sum is : ", sum(items))
knapsack_size = 762
print("Enter knapsack size: ")
if knapsack_size > sum(items):
print("Items picked are :", items)
else:
number_items = len(items)
dp = [[0 for _ in range(knapsack_size + 1)] for __ in range(number_items + 1)]
max_value_obtained = knapsack_dynamic(items, knapsack_size, number_items, 0)
print("Knapsack size", knapsack_size)
print("Max value obtained", max_value_obtained)
backtrack(max_value_obtained, knapsack_size, items, number_items)
|
fa729e7509e45d58afe1c792d586072f89546cd6 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/124 Binary Tree Maximum Path Sum.py | 1,717 | 3.5625 | 4 | """
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1
/ \
2 3
Return 6.
"""
__author__ 'Danyang'
# Definition for a binary tree node
c_ TreeNode:
___ - , x
val x
left N..
right N..
c_ Solution:
global_max -1<<31
___ maxPathSum root
"""
:param root: TreeNode
:return: integer
"""
get_max_component(root)
# global_max can in ANY path in the tree
r.. global_max
___ get_max_component root
"""
Algorithm:
dfs
The path may start and end at any node in the tree.
parent
/
cur
/ \
L R
at current: the candidate max (final result) is cur+L+R
at current: the max component (intermediate result) is cur or cur+L or cur+R
Reference: http://fisherlei.blogspot.sg/2013/01/leetcode-binary-tree-maximum-path-sum.html
:param root:
:return:
"""
__ n.. root:
r.. 0
left_max_component get_max_component(root.left)
right_max_component get_max_component(root.right)
# update global max
current_max_sum m..(root.val, root.val+left_max_component, root.val+right_max_component, root.val+left_max_component+right_max_component) # four situations
global_max m..(global_max, current_max_sum)
# return value for upper layer to calculate the current_max_sum
r.. m..(root.val, root.val+left_max_component, root.val+right_max_component) # excluding arch (i.e. root.val+left_max_component+right_max_component)
|
298a235236b1456f906ce8919c5df8959f7d816f | AlexandreInsua/ExerciciosPython | /exercicios_repaso/exercicio37.py | 2,548 | 3.5 | 4 | # Programa que traduzca una palabra o frase a código morse. (busca en la wikipedia para más información)
# Intentar hacer el ejercicio usando diccionarios.
# Añadir una función que reproduzca el sonido del código morse.
# Pista:
import winsound
Freq = 2500 # Set Frequency To 2500 Hertz
Dur = 1000 # Set Duration To 1000 ms == 1 second
winsound.Beep(Freq,Dur)
# import winsound
def convertirMorse(frase):
alfabeto={}
alfabeto["a"]=".-"
alfabeto["b"]="-..."
alfabeto["c"]="-.-."
alfabeto["d"]="-.."
alfabeto["e"]="."
alfabeto["f"]="..-."
alfabeto["g"]="--."
alfabeto["h"]="...."
alfabeto["i"]=".."
alfabeto["j"]=".---"
alfabeto["k"]="-.-"
alfabeto["l"]=".-.."
alfabeto["m"]="--"
alfabeto["n"]="-."
alfabeto["ñ"]="--.--"
alfabeto["o"]="---"
alfabeto["p"]=".--."
alfabeto["q"]="--.-"
alfabeto["r"]=".-."
alfabeto["s"]="..."
alfabeto["t"]="-"
alfabeto["u"]="..-"
alfabeto["v"]="...-"
alfabeto["w"]=".--"
alfabeto["x"]="-..-"
alfabeto["y"]="-.--"
alfabeto["z"]="--.."
alfabeto["0"]="-----"
alfabeto["1"]=".----"
alfabeto["2"]="..---"
alfabeto["3"]="...--"
alfabeto["4"]="....-"
alfabeto["5"]="....."
alfabeto["6"]="-...."
alfabeto["7"]="--..."
alfabeto["8"]="---.."
alfabeto["9"]="----."
alfabeto["."]=".-.-.-"
alfabeto[","]="-.-.--"
alfabeto["?"]="..--.."
alfabeto["\""]=".-..-."
alfabeto["!"]="--..--"
alfabeto[" "]="/"
morse = ""
for letra in frase:
try:
morse = morse + alfabeto[letra]
except:
#print("no existe ese caracter en morse")
pass
return morse
def sonidoMorse(frase):
morse = convertirMorse(frase)
for simbolo in morse:
if(simbolo == "."): # reproduzco un punto (1/2 segundo)
Freq = 1500 # Set Frequency To 2500 Hertz
Dur = 50 # Set Duration To 1000 ms == 1 second
winsound.Beep(Freq,Dur)
elif (simbolo == "-"):# reproduzco una raya (1 segundo)
Freq = 1500 # Set Frequency To 2500 Hertz
Dur = 200 # Set Duration To 1000 ms == 1 second
winsound.Beep(Freq,Dur)
else: #reproduzco un espacio (2 segundos)
Freq = 37 # Set Frequency To 2500 Hertz
Dur = 1000 # Set Duration To 1000 ms == 1 second
winsound.Beep(Freq,Dur)
print( convertirMorse("sos") )
# sonidoMorse("sos")
print( convertirMorse("aqui grupo 003. chegamos a posicion preliminar"))
sonidoMorse("aqui grupo 003. chegamos a posicion preliminar") |
e2f679f9826745f6a3db8a321586859d3dda934b | vedeninvv/Algorithms | /lab 2/a2.2/a2.2.py | 1,746 | 3.734375 | 4 | def sort(list_of_countries, fst, lst):
if lst - fst == 1:
if list_of_countries[fst] > list_of_countries[lst]:
list_of_countries[fst], list_of_countries[lst] = list_of_countries[lst], list_of_countries[fst]
return
if fst == lst: return
mid = (fst + lst) // 2
sort(list_of_countries, fst, mid)
sort(list_of_countries, mid + 1, lst)
buf = []
i = fst
j = mid + 1
k = 0
while lst - fst + 1 != k:
if (i > mid):
buf.append(list_of_countries[j])
k += 1
j += 1
elif (j > lst):
buf.append(list_of_countries[i])
k += 1
i += 1
elif (list_of_countries[i] > list_of_countries[j]):
buf.append(list_of_countries[j])
k += 1
j += 1
else:
buf.append(list_of_countries[i])
k += 1
i += 1
for i in range(lst - fst + 1):
list_of_countries[i + fst] = buf[i];
fin = open("race.in")
fout = open("race.out", "w")
n = int(fin.readline())
set_of_countries = set()
list_of_sportsmen = []
dict_of_sportsmen = dict()
for line in fin:
set_of_countries.add(line.split()[0])
list_of_sportsmen.append([line.split()[0], line.split()[1]])
list_of_countries = list(set_of_countries)
for country in list_of_countries:
dict_of_sportsmen[country] = []
for sportsmen in list_of_sportsmen:
dict_of_sportsmen[sportsmen[0]].append(sportsmen[1])
sort(list_of_countries, 0, len(list_of_countries) - 1)
for country in list_of_countries:
print("===", country, "===", file=fout)
sportsmen_of_country = dict_of_sportsmen[country]
for sportsmen in sportsmen_of_country:
print(sportsmen, file=fout)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.