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
5b2a21644cbed79b9f35726956dfe6c86c96dcba
rshinoha/DSAWork
/Chapter01/P1.32-simple_calculator.py
2,221
4.34375
4
# Data Structures and Algorithms in Python Ch.1 (Goodrich et. al.) # Project exercise P1.32 # Ryoh Shinohara # ======================================================================================= # Write a Python program that can simulate a simple calculator, using the console as the # exclusive input and output device. That is, each input to the calculator, be it a # number, like 12.34 or 1034, or an operator, like + or =, can be done on a separate # line. After each such input, you should output to the Python console what would be # displayed on your calculator. input_text = "Input: " output_text = "Output: " def get_num(): """ Extracts a number from a given input; if the input is not valid, continues to ask the user for a valid input """ n = None bad_input = True while bad_input: user_input = input("{}".format(input_text)) try: n = int(user_input) bad_input = False except: try: n = float(user_input) bad_input = False except: print("{}ERROR".format(output_text)) return n def calculate(num1, operator, num2): """ Calculates +, -, *, or / of num1 and num2 depending on operator """ if operator == '+': return num1 + num2 elif operator == '-': return num1 - num2 elif operator == '*': return num1 * num2 elif operator == '/': return num1 / num2 else: raise ValueError("Invalid input") def get_operator(): """ Extracts valid operator from a given input; if the input is not valid, continues to ask the user for a valid input """ operators = ['+', '-', '*', '/', '='] operator = None bad_input = True while bad_input: operator = input("{}".format(input_text)) if operator in operators: bad_input = False else: print("{}ERROR".format(output_text)) return operator def main(): print("This program simulates a simple calculator. Type each number and operator on", "a separate line.") num1 = get_num() num2 = None operator = None while operator != '=': operator = get_operator() if operator == '=': print("{}{}".format(output_text, num1)) else: num2 = get_num() num1 = calculate(num1, operator, num2) print("{}{}".format(output_text, num1)) num2 = None operator = None if __name__ == "__main__": main()
72b8f08673c8e52f9ea8c533ff5a721ad5a38b23
jedzej/tietopythontraining-basic
/students/stachowska_agata/lesson_02_flow_control/adding_factorials.py
159
3.796875
4
n = int(input()) sum_of_factorials = 0 factorial = 1 for i in range(1, n + 1): factorial *= i sum_of_factorials += factorial print(sum_of_factorials)
a17fc3ede367fd345a6011d47bd0eca35a48ea1b
MrHamdulay/csc3-capstone
/examples/data/Assignment_5/gvnpri022/question1.py
1,214
3.890625
4
"""question 1- assignment 5 prinesan govender 14 april 2014""" choice="" msg="" #initialise variables while(choice!="X"): print("Welcome to UCT BBS") print("MENU") print("(E)nter a message") print("(V)iew message") print("(L)ist files") print("(D)isplay file") print("e(X)it") choice = (input("Enter your selection:\n")).upper() #converting to uppercase so that you dont have to check for both cases if (choice=="E"): msg= input("Enter the message:\n") elif(choice=="V"): if(msg==""): print("The message is: no message yet") else: print("The message is:",msg) elif(choice=="L"): print("List of files: 42.txt, 1015.txt") elif(choice=="D"): fName= input("Enter the filename:\n") if(fName=="42.txt"): print("The meaning of life is blah blah blah ...") elif(fName=="1015.txt"): print("Computer Science class notes ... simplified") print("Do all work") print("Pass course") print("Be happy") else: print("File not found") print("Goodbye!") #message when loop has ended
7c668d1430781155ce42907fef3580c4924d0724
tarak2014/pytest
/test_cases.py
557
4.125
4
from basicmath import util def test_add_num(): """Test is to Addition of two numbers, and return the output value""" assert util.add_num(3,4) == 7 def test_sub_num(): """Test is to Substraction of two numbers, and return the output value""" assert util.sub_num(3,4) == -1 def test_mul_num(): """Test is to Multiplication of two numbers, and return the output value""" assert util.mul_num(3,4) == 12 def test_div_num(): """Test is to Division of two numbers, and return the output value""" assert util.div_num(3,4) == 0.75
2f348b7d4a765d145ad225dc0f32de0f4f091180
PaulSayantan/problem-solving
/LEETCODE/Easy/Two Sum/twosum.py
372
3.59375
4
from typing import List def twoSum(nums: List[int], target: int) -> List[int]: index = dict() for i , n in enumerate(nums): if target - n in index: return [index[target - n], i] index[n] = i return [] if __name__ == "__main__": nums = [int(x) for x in input().split()] target = int(input()) print(twoSum(nums, target))
905f4234af49a86b33cf4342a63c7d20c0366dc2
gcakir/2017_AaDS
/HW3/1/guess.py
460
3.671875
4
import random def createList(n): lst = list() for i in range(1, n): lst.append(i) return lst def binary_search(A, n, x): p = 0; r = n while p <= r: q = int((p+r)/2) # print(A[p:r+1]) if A[q] == x: return q elif A[q] != x and A[q] > x: r = q - 1 elif A[q] != x and A[q] < x: p = q + 1 return -1 list_size = 100 lst = createList(list_size) random_number = random.randrange(1, n) print(binary_search(lst, len(lst), random_number))
cfbdd781e949bc05b05196e275a02f0f6da47d59
Kaiquenakao/Python
/Estruturas de repetição em Python/Exercicio14.py
469
3.890625
4
""" 14. Faça um programa que leia um número inteiro positivo par N e imprima todos os números pares de 0 até N em ordem decrescente """ try: N = int(input('Insira um número positivo inteiro par: ')) if (N > 0) and (N % 2 == 0): for i in range(N, -1, -2): print(i, end=' ') else: print('ERRO!!! O número é negativo ou não é par') except ValueError: print('ERRO!!! Só pode ser digitado número negativo')
94fc2a8a79adc3f35c4b291091ad0bce0e9a0c77
wmboult94/NLP
/Workshops/Topic 0/solutions/print_word_counts.py
594
3.875
4
# coding: utf-8 def print_word_counts(filepath): input_file_path = filepath input_file = open(input_file_path) input_text = input_file.read() word_counts = collections.defaultdict(int) for word in input_text.split(): word_counts[word] += 1 for word, count in word_counts.items(): if count == 1: print('The word "{0}" occurred once.'.format(word)) else: print('The word "{0}" occurred {1} times.'.format(word,count)) print_word_counts("/Users/davidw/Documents/teach/NLE/NLE Notebooks/Topic 0/sample_text.txt")
fb7779f71755c75a0dbf8ae1313d5dd09c07b4e8
IIITSERC/SSAD_2015_A3_Group2_35
/w.py
4,184
3.671875
4
import random class board: def __init__(self): #creates a rectangle of walls stored in an array self.bord=[] self.data=[]; for i in range(30): self.f=[] for j in range(80): self.f.append(" ") self.bord.append(self.f) for i in range(30): self.bord[i][0]='X' self.bord[i][79]='X' for i in range(80): self.bord[0][i]='X' self.bord[29][i]='X' #creates walls i.e. floors on random lenth and random side def createwall(self): self.hight=5 for j in range(6): self.dt=[] self.wall=random.randrange(1,3) if self.wall==1: self.size=random.randrange(50,70) for i in range(self.size): self.bord[self.hight][i]='X' self.dt.append('l') self.dt.append(self.size-1) if self.wall==2: self.size=random.randrange(50,70) for i in range(self.size): self.bord[self.hight][79-i]='X' self.dt.append('r') self.dt.append(79-self.size) self.hight+=4 self.data.append(self.dt) self.data.append(['l',77]) #creates normal and broken ladders def createladder(self): self.hight=6 lad=0 i=0 k=0 brk=random.sample(range(0,5),3) brk=sorted(brk) while i<5: if self.data[i][0]=='r' and self.data[i+1][0]=='r': t=max(self.data[i][1],self.data[i+1][1]) lad=random.randrange(t+2,75) while self.bord[self.hight][lad+1]=='H' or self.bord[self.hight][lad-1]=='H': lad=random.randrange(t+5,75) self.bord[self.hight-1][lad]=self.bord[self.hight][lad]=self.bord[self.hight+1][lad]=self.bord[self.hight+2][lad]='H' if self.data[i][0]=='l' and self.data[i+1][0]=='l': t=min(self.data[i][1]+2,self.data[i+1][1]-2) lad=random.randrange(5,t-2) while self.bord[self.hight][lad+1]=='H' or self.bord[self.hight][lad-1]=='H': lad=random.randrange(5,t-2) self.bord[self.hight-1][lad]=self.bord[self.hight][lad]=self.bord[self.hight+1][lad]=self.bord[self.hight+2][lad]='H' if self.data[i][0]=='r' and self.data[i+1][0]=='l': lad=random.randrange(self.data[i][1]+2,self.data[i+1][1]-2) while self.bord[self.hight][lad+1]=='H' or self.bord[self.hight][lad-1]=='H': lad=random.randrange(self.data[i][1]+2,self.data[i+1][1]-2) self.bord[self.hight-1][lad]=self.bord[self.hight][lad]=self.bord[self.hight+1][lad]=self.bord[self.hight+2][lad]='H' if self.data[i][0]=='l' and self.data[i+1][0]=='r': lad=random.randrange(self.data[i+1][1]+2,self.data[i][1]-2) while self.bord[self.hight][lad+1]=='H' or self.bord[self.hight][lad-1]=='H': lad=random.randrange(self.data[i+1][1]+2,self.data[i][1]-2) self.bord[self.hight-1][lad]=self.bord[self.hight][lad]=self.bord[self.hight+1][lad]=self.bord[self.hight+2][lad]='H' if i in brk: p=random.randrange(0,3) self.bord[self.hight+p][lad]=" " del brk[0] else: i+=1 self.hight+=4 if self.data[5][0]=='l': lad=random.randrange(3,self.data[5][1]-2) self.bord[self.hight-1][lad]=self.bord[self.hight][lad]=self.bord[self.hight+1][lad]=self.bord[self.hight+2][lad]='H' if self.data[5][0]=='r': lad=random.randrange(self.data[5][1]+2,75) self.bord[self.hight-1][lad]=self.bord[self.hight][lad]=self.bord[self.hight+1][lad]=self.bord[self.hight+2][lad]='H' # Creates coins at random positions on floor def coin(self): self.hight=4 for i in range(7): cns=[] if self.data[i][0]=='l': cns=random.sample(range(2,self.data[i][1]-2),5) else: cns=random.sample(range(self.data[i][1]+2,77),5) for j in cns: if not self.bord[self.hight][j]=='H': self.bord[self.hight][j]='C' self.hight+=4 #creates queen on the top according on which side the top floor is def queen(self): self.hight=2 if self.data[0][0]=='l': self.bord[self.hight-1][14]='Q' for i in range(10): self.bord[self.hight][i+10]='X' self.bord[self.hight-1][10]=self.bord[self.hight-1][19]='X' self.bord[self.hight][16]=self.bord[self.hight+1][16]=self.bord[self.hight+2][16]='H' else: self.bord[self.hight-1][66]='Q' for i in range(10): self.bord[self.hight][i+60]='X' self.bord[self.hight-1][60]=self.bord[self.hight-1][69]='X' self.bord[self.hight][64]=self.bord[self.hight+1][64]=self.bord[self.hight+2][64]='H'
9afefd63cd39a3c32471ed4edd318b01505e1104
hemincong/MachineLearningExercise
/utils/file_utils.py
735
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def read_csv(file_name): m = [] with open(file_name, "r") as infile: for line in infile: pos = line.strip().split(',') tmp = list(map(float, pos)) m.append(tmp) return m def read_csv_split_last_col(file_name): m = read_csv(file_name) import numpy as np mm = np.asarray(m) row, col = np.shape(mm) x = mm[0:row, 0:col - 1] y = mm[0:row, col - 1:col] return x, y.flatten() def read_csv_split_last_col_and_add_one(file_name): x, y = read_csv_split_last_col(file_name) import numpy as np x_row, x_col = np.shape(x) one_col = np.ones((x_row, 1)) x = np.c_[one_col, x] return x, y
59fc3900383a06c8c925050535a78476cb28d3f1
evilnsm/learn-python
/Project Euler/049.py
988
3.640625
4
#coding:utf-8 ''' 公差为3330的三项等差序列1487、4817、8147在两个方面非常特别:其一,每一项都是素数;其二,两两都是重新排列的关系。 一位素数、两位素数和三位素数都无法构成满足这些性质的数列,但存在另一个由四位素数构成的递增序列也满足这些性质。 将这个数列的三项连接起来得到的12位数是多少? ''' from math import sqrt def is_p(n): if n== 1: return False elif n == 2: return True else: for i in xrange(2,int(sqrt(n))+1): if n % i == 0: return False return True for i in range(1000,10000-3330-3330): if is_p(i) and is_p(i+3330) and is_p(i+3330+3330): a = set(list(str(i))) b = set(list(str(i+3330))) c = set(list(str(i+3330+3330))) if len(a & b) == len(c) and len(a & c) == len(b) and i != 1487: print i*100000000 + (i+3330)*10000 + (i+3330+3330)
abb09ed86c1601ee663fbc3574c41a8a76f195e5
Oleksandr015/Python-podstawy
/Day_5.1/inheritance.py
1,339
4
4
class A: def __init__(self, a): self.a = a def square_value(self, value): return value ** 2 class B(A): def __init__(self, a, b): super().__init__(a) self.b = b class Animal: def __init__(self, name, age): self.name = name self.age = age def introduce(self): return f'Hello! my name is {self.name}' class Cat(Animal): def __init__(self, name, age, color): super().__init__(name, age) self.color = color def introduce(self): return f'{super().introduce()}. My color is {self.color}' class Dog(Animal): def __init__(self, name, age, tail_length): super().__init__(name, age) self.tail_length = tail_length def introduce(self): return f'{super().introduce()}. My color is {self.tail_length}' class Cow(Animal): def __init__(self, name, age, weight): super().__init__(name, age) self.weight = weight if __name__ == '__main__': burek = Dog('Burek', 2, 14) murka = Cat('Murka', 1, 'black') dzwon = Cow('Dzwon', 3, 200) a = A(5) b = B(12, 'Ala') print(b.a) print(b.b) print() print(a.square_value(5)) print(b.square_value(5)) print() print(burek.introduce()) print(murka.introduce()) print(dzwon.introduce()) #
3f9df82b5f9c8e5c66ccfac0d30e0175e2ab01c7
thejohnjensen/code-katas
/src/test_sum_terms.py
402
3.5625
4
"""Module to test sum of nth term module.""" import pytest nth_term = [ (1, '1.00'), (0, '0.00'), (2, '1.25'), (3, '1.39'), (59, '2.40'), (9, '1.77'), (5, '1.57'), (99, '2.58') ] @pytest.mark.parametrize('n, result', nth_term) def test_series_sum(n, result): """Test the fuction series sum for nth term.""" from sum_of_nth_terms import series_sum assert series_sum(n) == result
4536bd8802cef5561fb1b16d05eb10a9968c9b82
sornaami/luminarproject
/objectorientedprogramming/bankapplication.py
1,066
4
4
import datetime class Person: def setPerson(self,name,age): self.name=name self.age=age def printPerson(self): print(self.name,",",self.age) class Bank(Person): bank_name="Sbk" def createAccount(self,acno): self.acno=acno self.balance=3000 def deposit(self,amount): self.balance+=amount print("your",Bank.bank_name,"has been credited with",amount,"aval balance",self.balance) def withdraw(self,amount): if(amount>self.balance): print("insufficient balance in your account") else: self.balance-=amount print("your",Bank.bank_name,"has been debited with",amount,"on",datetime.date.today(),"aval balance",self.balance) obj=Bank() obj.setPerson("samvi",27) obj.printPerson() obj.createAccount(1001) obj.deposit(5000) obj.withdraw(1000) #difrnt types of variables #1 instance variables = always related to object #2 static variables= can be accessed using class name #static can be used for efficient memory usage #static related to class
76808eb3ef8c480fe75943cc5a902d14ae2fefdc
jianwenyu/CPP
/python/29_formatMethods.py
927
3.765625
4
defaultOrder = "{},{},{}".format('lee','john','tom') print(defaultOrder) positionalOrder = "{1},{2},{0}".format('lee','john','tom') print(positionalOrder) keywordOrder = "{s},{b},{n}".format(b='lee',s='john',n='tom') print(keywordOrder) print("Binary representation of {0} is {0:b}".format(12)) print("Octal representation of {0} is {0:o}".format(12)) print("Hex representation of {0} is {0:x}".format(12)) print("Exponent representation of {0} is {0:e}".format(12654)) # Lower case print("PrOgRaMiZ".lower()) # Upper case print("PrOgRaMiZ".upper()) # split string print("This will split all words into a list".split()) # split string print("This will split all words into a list".split('i')) # join string print( ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])) # join string print( ','.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string']))
ba8cb0b2acaabe87e809df516f159a3fc3d1bdab
cameronbrown/hello-ci
/hello/util.py
367
3.515625
4
"""Fake utilitites for testing testing""" def add_two(num): """Add two to num""" return num + 2 def add_three(num): """Add three to num""" return num + 3 def add_four(num): """Add four to num""" return num + 4 def add_five(num): """Add five to num""" num += 1 num += 1 num += 1 num += 1 num += 1 return num
244b3b8af83274c8da643d4c9b4639c4919cb247
ThomasTheDane/datasci_course_materials
/assignment3/wordcount.py
2,255
3.71875
4
import MapReduce import sys import json """ Word Count Example in the Simple Python MapReduce Framework """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line # def mapper(record): # # key: document identifier # # value: document contents # key = record[0] # value = record[1] # words = value.split() # for w in words: # mr.emit_intermediate(w, 1) # def reducer(key, list_of_values): # # key: word # # value: list of occurrence counts # # print list_of_values # total = 0 # for v in list_of_values: # total += v # mr.emit((key, total)) # def mapper(record): # # key: document identifier # # value: document contents # # output: word : text document in which it appears # key = record[0] # value = record[1] # words = value.split() # for w in words: # mr.emit_intermediate(w, key) # def reducer(key, list_of_values): # # key: word # # value: list of occurrence counts # # output: word : [list of documents] # mr.emit((key, list(set((list_of_values))))) # def mapper(record): # # input: a record # # output: order_id : rest of dat shit # mr.emit_intermediate(record[1], record) # def reducer(key, list_of_values): # # key: word # # value: list of occurrence counts # # output: word : [list of documents] # for record in list_of_values[1:]: # join = list_of_values[0] + record # mr.emit(join) def mapper(record): if(record[0] == "a"): for k in range(0, 5): mr.emit_intermediate((record[1], k), ("a", record[2], record[3])) else: for i in range(0, 5): mr.emit_intermediate((i, record[2]), ("b", record[1], record[3])) def reducer(key, list_of_values): # print key, list_of_values sumsA = list(0 for i in range(0, 5)) sumsB = list(0 for i in range(0, 5)) for line in list_of_values: if line[0] == "a": sumsA[line[1]] = line[2] else: sumsB[line[1]] = line[2] totSum = 0 for i in range(0,5): totSum += sumsA[i] * sumsB[i] mr.emit((key[0], key[1], totSum)) # Do not modify below this line # ============================= if __name__ == '__main__': inputdata = open(sys.argv[1]) mr.execute(inputdata, mapper, reducer)
c92dfe94b9df589f6bb44a9c86112bd507736fd6
hochan222/vs-code-test
/python/BJ_10039.py
162
3.546875
4
total = [] for _ in range(5): score = int(input()) if score < 40: total.append(40) else: total.append(score) print(int(sum(total)/5))
1785b26b010d448c5dce0e53337ff7988816c2df
vyxxr/python3-curso-em-video
/Mundo3/099.py
579
4.21875
4
''' Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores inteiros. Seu programa tem que analisar todos os valores e dizer qual deles é o maior. ''' from time import sleep def maior(* num): print('-=' * 30) print('Analisando os valores informados...') for c in num: print(c, end=' ') sleep(0.3) print(f'Foram analisados {len(num)} valores ao todo.') print(f'O maior valor informado foi {0 if len(num) == 0 else max(num)}.') maior(2, 9, 4, 5, 7, 1) maior(4, 7, 0) maior(1, 2) maior(6) maior()
153cb0d6624bdccbdedc39e675958b3ee0f415a6
qleoz/snake-learning
/smart_ai.py
2,200
3.6875
4
import snake as s import random import sys import math as m choices = ['l', 'r', 'f'] board = [] snake = [] direction = '' #returns location of food, None if no food def findfood(): global board, snake, direction for i in range(len(board)): for j in range(len(board[i])): if(board[i][j] == 2): return [i, j] return None #return True if nothing in front def checkfront(): global board, snake, direction return s.checknext(board, snake, direction) #return True if nothing on left def checkleft(): global board, snake, direction if(direction == 'u'): tempdir = 'l' elif(direction == 'd'): tempdir = 'r' elif(direction == 'l'): tempdir = 'd' else: tempdir = 'u' return s.checknext(board, snake, tempdir) #return True if nothing on right def checkright(): global board, snake, direction if(direction == 'u'): tempdir = 'r' elif(direction == 'd'): tempdir = 'l' elif(direction == 'l'): tempdir = 'u' else: tempdir = 'd' return s.checknext(board, snake, tempdir) def food_dir(): global board, snake, direction food = findfood(board) dx = food[1] - snake[0][1] dy = snake[0][0] - food[0] print("dx: ", dx, " dy: ", dy) angle = m.atan2(dy, dx) print('angle: ', angle) if(direction == 'l'): if(angle < 0): return 'l' if(angle > 0): return 'r' if(direction == 'u'): if(angle > m.pi/2 or angle < -m.pi/2): return 'l' if(angle < m.pi/2 and angle > -m.pi/2): return 'r' if(direction == 'r'): if(angle > 0): return 'l' if(angle < 0): return 'r' if(direction == 'd'): if(angle < m.pi/2 and angle > -m.pi/2): return 'l' if(angle > m.pi/2 or angle < -m.pi/2): return 'r' return 's' #returns L R or F as input into snake_gui def generate_next_move(): return random.choice(choices) #used by snake_gui to provide info every round def get_info(b, s, d): global board, snake, direction board = b snake = s direction = d
e5000be46058acf6390ddb8275207b625509259e
zhangzongyan/python0702
/day12/obj4.py
647
3.8125
4
import obj1 class Test: def __init__(self): super().__init__() # 父类是object class Student(obj1.Person): def __init__(self, name, age, no, school_tm): # 调用父类obj1.Person的__init__方法,构建name和age属性 # obj1.Person.__init__(self, name, age) # super(Student, self).__init__(name, age) super().__init__(name, age) self.no = no self.school_tm = school_tm # 重写 def getInfo(self): # super().getInfo() #obj1.Person.getInfo(self) print("学号{},{}年入学的".format(self.no, self.school_tm)) s = Student("hello", 11, 1, 2015) s.sayHello() s.getInfo() s.name = "python" s.getInfo() t = Test()
600f34e6b0c35240803a85147416f84e394f9f23
adolgert/cascade
/src/cascade/input_data/db/data_iterator.py
608
4.15625
4
def grouped_by_count(identifiers, count): """ Given a list, iterates over that list in sets of size count. The last set will be of size less than or equal to count. Args: identifiers (List): Can be any iterable. count (int): Number of items to return on each iteration. Returns: List: On each iteration, returns a list of count members or, on the last iteration, less-than-or-equal-to count members. """ identifiers = list(identifiers) for i in range((len(identifiers) - 1) // count + 1): yield identifiers[i * count:(i + 1) * count]
1c9aeea69b0068d3bbc9245ec004c0aebb631d7c
Omkar02/FAANG
/RemoveDupFromSortedArray.py
1,264
3.890625
4
import __main__ as main from Helper.TimerLogger import CodeTimeLogging fileName = main.__file__ fileName = fileName.split('\\')[-1] CodeTimeLogging(Flag='F', filename=fileName, Tag='Array') ''' Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Example 1: Given nums = [1,1,2], Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the returned length. Example 2: Given nums = [0,0,1,1,1,2,2,3,3,4], Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length. ''' def getCountDup(nums): if not nums: return 0 prev_index = 0 prev = nums[0] x = 1 while(prev != nums[-1]): if nums[x] != prev: prev = nums[x] nums[prev_index + 1] = prev prev_index += 1 x += 1 return prev_index + 1 nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4] print(getCountDup(nums))
d30157b9c5f4fc1d6c6c6ec28a270335f19ad5fb
phallusferrus/phallusferrus.github.io
/blogs/works/python/ttt.py
4,727
3.859375
4
import random #import time ###I want the computer to anticipate victory and act on it ###if b_r_1[0] == b_r_1[2] and "2" in a_m: ### move = 2 ###should be roughly 16 different emminent victory conditions twice as many victory conditions...weird math dude... b_r_1 = ["1", "2", "3"] b_r_2 = ["4", "5", "6"] b_r_3 = ["7", "8", "9"] a_m = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] oturns = ["0", "2", "4", "6", "8"] xturns = ["1", "3", "5", "7", "9"] move = 0 player_token = "?" turn = 1 def start(): global player_token print("START") player_token_raw = input("X or O?:\n") player_token = player_token_raw.upper() print("You are: "+player_token) if player_token == "X" or player_token == "O": looper() else: print("BAD INPUT!:\n") start() def logic(move): global turn if str(turn) in xturns: current_token = "X" elif str(turn) in oturns: current_token = "O" if move in a_m: a_m.remove(move) if move == "1": b_r_1[0] = current_token elif move == "2": b_r_1[1] = current_token elif move == "3": b_r_1[2] = current_token elif move == "4": b_r_2[0] = current_token elif move == "5": b_r_2[1] = current_token elif move == "6": b_r_2[2] = current_token elif move == "7": b_r_3[0] = current_token elif move == "8": b_r_3[1] = current_token elif move == "9": b_r_3[2] = current_token else: print("ERROR: logic() did get a good imput") else: print("\nBAD MOVE!\n\nTRY AGAIN\n\n") print("This is a real error idk what to do...line 69") pass def get_player_move(): print("Your turn!") move = input("Take a move:\n ") if str(move) in a_m: logic(move) else: print("BAD INPUT!\n") get_player_move() def draw(): print("\n\n***************\n###############\n---------------") print(b_r_1) print(b_r_2) print(b_r_3) print("\n\n***************\n###############\n---------------") def xmove(): global player_token if player_token == "X": get_player_move() else: get_computer_move() def omove(): global player_token if player_token == "O": get_player_move() else: get_computer_move() def get_computer_move(): #first horizontal checks if b_r_1[0] == b_r_1[1] and "3" in a_m: move = "3" elif b_r_1[0] == b_r_1[2] and "2" in a_m: move = "2" elif b_r_1[1] == b_r_1[2] and "1" in a_m: move = "1" elif b_r_2[0] == b_r_2[1] and "6" in a_m: move = "6" elif b_r_2[0] == b_r_2[2] and "5" in a_m: move = "5" elif b_r_2[1] == b_r_2[2] and "4" in a_m: move = "4" elif b_r_3[0] == b_r_3[1] and "9" in a_m: move = "9" elif b_r_3[0] == b_r_3[2] and "8" in a_m: move = "8" elif b_r_3[1] == b_r_3[2] and "7" in a_m: move = "7" #Vertical checks elif b_r_1[0] == b_r_2[0] and "7" in a_m: move = "7" elif b_r_1[0] == b_r_3[0] and "4" in a_m: move = "4" elif b_r_2[0] == b_r_3[0] and "1" in a_m: move = "1" elif b_r_1[1] == b_r_2[1] and "8" in a_m: move = "8" elif b_r_1[1] == b_r_3[1] and "5" in a_m: move = "5" elif b_r_2[1] == b_r_3[1] and "2" in a_m: move = "2" elif b_r_1[2] == b_r_2[2] and "9" in a_m: move = "9" elif b_r_1[2] == b_r_3[2] and "6" in a_m: move = "6" elif b_r_2[2] == b_r_3[2] and "3" in a_m: move = "3" #Diagonal checks elif b_r_1[0] == b_r_3[2] and "5" in a_m: move = "5" elif b_r_2[1] == b_r_3[2] and "1" in a_m: move = "1" elif b_r_1[0] == b_r_2[1] and "9" in a_m: move = "9" elif b_r_3[0] == b_r_1[2] and "5" in a_m: move = "5" elif b_r_3[0] == b_r_2[1] and "3" in a_m: move = "3" elif b_r_2[1] == b_r_1[2] and "7" in a_m: move = "7" #Else pick center elif b_r_2[1] == "5": move = "5" #Else pick random else: print("\nRANDOM CPU MOVE!!\n") move = random.choice(a_m) logic(move) def win(): global turn turn += 1 if turn > 9: print("CATSGAME") return True elif b_r_1[0] == b_r_1[1] and b_r_1[0] == b_r_1[2]: return True elif b_r_2[0] == b_r_2[1] and b_r_2[0] == b_r_2[2]: return True elif b_r_3[0] == b_r_3[1] and b_r_3[0] == b_r_3[2]: return True elif b_r_3[0] == b_r_2[1] and b_r_3[0] == b_r_1[2]: return True elif b_r_1[0] == b_r_2[1] and b_r_1[0] == b_r_3[2]: return True elif b_r_3[0] == b_r_2[0] and b_r_3[0] == b_r_1[0]: return True elif b_r_3[1] == b_r_2[1] and b_r_3[1] == b_r_1[1]: return True elif b_r_3[2] == b_r_2[2] and b_r_3[2] == b_r_1[2]: return True else: return False def looper(): global turn draw() print("Turn "+str(turn)+"\nX GO") xmove() draw() if win(): print("X Wins") print("Game Over") return else: print("Turn "+str(turn)+"\nO GO") omove() draw() if win(): print("O Wins") print("Game Over") return else: looper() print("Welcome to Tic Tac Toe") enter = input("Press enter to begin:") start()
dad5265b51ef8511575ccc70f5819c276f386bbc
Saurabh-12/Python_Learning
/QueueExamplePython.py
477
3.6875
4
from collections import deque class Queue: def __init__(self, max_size = 10): self._queue = deque(maxlen = max_size) def is_empty(self): return self._queue == [] def enqueue(self, data): self._queue.append(data) def dequeue(self): return self._queue.popleft() queue = Queue(4) queue.enqueue("Saurabh") queue.enqueue("Kumar") queue.enqueue("Sharma") queue.enqueue("Blogs") print(queue._queue) print(queue.dequeue())
48684ade4b7e161c2fa7b222bc1b3c23a49b73f7
xpdAcq/rapidz
/rapidz/orderedweakset.py
1,236
3.578125
4
# -*- coding: utf8 -*- # This is a copy from Stack Overflow # https://stackoverflow.com/questions/7828444/indexable-weak-ordered-set-in-python # Asked by Neil G https://stackoverflow.com/users/99989/neil-g # Answered/edited by https://stackoverflow.com/users/1001643/raymond-hettinger import collections.abc import weakref class OrderedSet(collections.abc.MutableSet): def __init__(self, values=()): self._od = collections.OrderedDict().fromkeys(values) def __len__(self): return len(self._od) def __iter__(self): return iter(self._od) def __contains__(self, value): return value in self._od def add(self, value): self._od[value] = None def discard(self, value): self._od.pop(value, None) class OrderedWeakrefSet(weakref.WeakSet): def __init__(self, values=()): super(OrderedWeakrefSet, self).__init__() self.data = OrderedSet() for elem in values: self.add(elem) def index(self, value): for i, nn in enumerate(self): if nn == value: return i else: # pragma: no cover raise ValueError(f'{value} is not in set')
fd4baecf9b9df4e055ccad8e86d36ef6caca1695
JasonXJ/algorithms
/leetcode/lc56.py
778
3.578125
4
class Solution(object): def merge(self, intervals): if len(intervals) == 0: return intervals intervals.sort(key=lambda x:x.start) merged = [intervals[0]] head = merged[0] for x in intervals[1:]: if x.start > head.end: # New interval merged.append(x) head = x elif x.end > head.end: head.end = x.end return merged class Interval(object): def __init__(self, s, e): self.start = s self.end = e def __eq__(self, x): return self.start == x.start and self.end == x.end def test(): f = Solution().merge i = Interval assert f([i(1, 3), i(2, 6), i(8, 10), i(15, 18)]) == [i(1, 6), i(8, 10), i(15, 18)]
9679aa489481d024695991ca7ee7877da58fd2b5
mhoogs/test
/practice midterm.py
448
3.921875
4
def remove_bracket(sentence): count = 0 for i in sentence: if i =="(": left_bracket = count elif i == ")": right_bracket = count count = count + 1 new_sentence= sentence[0:left_bracket] +sentence[right_bracket+1:len(sentence)] return new_sentence print(remove_bracket("The falling leaves drift by the window (the autumn leaves of red and gold)"))
6dbd2508b1746384c9e4e2a9f313672ebcd8822e
Luzhnuy/katerina_labs
/double_letter.py
74
3.859375
4
word = input("Type a word: ") for el in word: print( el + el, end="")
615e12717cb54f15eae7251b7c52e563cf53712d
sunshot/LeetCode
/480. Sliding Window Median/solution1.py
792
3.9375
4
from typing import List class Solution: def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]: left = 0 right = left + k result = [] while right <= len(nums): temp = sorted(nums[left:right]) if len(temp) % 2 == 0: index = len(temp) // 2 median = (temp[index-1] + temp[index]) / 2.0 else: index = (len(temp) - 1) // 2 median = temp[index] result.append(median) left += 1 right += 1 return result if __name__== '__main__': solution = Solution() nums = [1,3,-1,-3,5,3,6,7] k = 3 result = solution.medianSlidingWindow(nums, k) # expected = [1, -1, -1, 3, 5, 6] print(result)
07cea477966a51de75c9adf51e6e6f16987a0b37
paulross/pprune-calc
/AN-24_Nizhneangarsk/cmn/polynomial.py
2,569
4.15625
4
import typing def polynomial(x: float, *args: typing.List[float]) -> float: """Returns the evaluation of the polynomial factors for the value x.""" ret = 0.0 for i in range(-1, -len(args) - 1, -1): ret += args[i] if i == -len(args): break ret *= x return ret def polynomial_differential(x: float, *args: typing.List[float]) -> float: """Returns the differential of the polynomial factors for the value x.""" ret = 0.0 for i in range(-1, -len(args), -1): if i == -(len(args) - 1): ret += args[i] break ret += args[i] * (len(args) + i) ret *= x return ret def polynomial_integral(x: float, *args: typing.List[float]) -> float: """Returns the integral of the polynomial factors from 0 to x.""" ret = 0.0 for i in range(-1, -len(args) - 1, -1): ret += args[i] / (len(args) + 1 + i) ret *= x return ret def polynomial_differential_factors(*args: typing.List[float]) -> typing.List[float]: """Returns the differential of the polynomial factors for the value x.""" ret = [] for i in range(1, len(args)): ret.append(args[i] * i) return ret def polynomial_3(x, a, b, c, d): """Polynomial order 3 where f(x) = a + b * x + c * x**2 + d * x**3""" return polynomial(x, a, b, c, d) def polynomial_3_integral(x, a, b, c, d): """Integral of polynomial order 3 where f(x) = a + b * x + c * x**2 + d * x**3. Integral(f(x)) 0 -> x = a * x + b * x**2 / 2 + c * x**3 / 3 + d * x**4 / 4 """ return polynomial_integral(x, a, b, c, d) def polynomial_3_differential(x, a, b, c, d): """Polynomial order 3 where f(x) = a + b * x + c * x**2 + d * x**3 Differential(f(x) = b + 2.0 * c * x**1 + 3.0 * d * x**2 """ return polynomial_differential(x, a, b, c, d) def polynomial_4(x, a, b, c, d, e): return polynomial(x, a, b, c, d, e) def polynomial_4_integral(x, a, b, c, d, e): return polynomial_integral(x, a, b, c, d, e) def polynomial_4_differential(x, a, b, c, d, e): return polynomial_differential(x, a, b, c, d, e) def polynomial_string(name: str, x: str, fmt: str, *args) -> str: ret = [ f'{name}({x}) =' ] for i, arg in enumerate(args): sub_str = [] if i: sub_str.append('+') sub_str.append(f'{arg:{fmt}}') if i == 1: sub_str.append(f'* {x}') elif i > 1: sub_str.append(f'* {x}**{i:d}') ret.append(' '.join(sub_str)) return ' '.join(ret)
7d3435373245c23229b485902db816bcff049aa4
angiereyes99/coding-interview-practice
/easy-problems/SubtracttheProductandSumofDigitsofanInteger.py
1,805
4
4
# PROBLEM: # Given an integer number n, return the # difference between the product of its # digits and the sum of its digits. # EXAMPLE: # Input: n = 234 # Output: 15 # Explanation: # Product of digits = 2 * 3 * 4 = 24 # Sum of digits = 2 + 3 + 4 = 9 # Result = 24 - 9 = 15 from typing import List class Solution: # APPROACH 1: BRUTE FORCE # - We can create n to be a list # and multiply and sum up all the # numbers in the list. The we just # return product - sum. # Runtime: 32 ms # Memory: 14 MB # Faster than 45.25% of Python submissions def approach1(self, n: int) -> int: n = list(map(int, str(n))) n_product = 1 n_sum = 0 for num in n: n_product = n_product * num n_sum = n_sum + n return n_product - n_sum # APPROACH 2: HELPER METHODS # - Using a product and sum helper method # uses good OOP principle practice and even # inreases speed in this case. While not # the most optimal solution,it is an # improvement from approach 1. # Runtime: 28 ms # Memory: 13.8 MB # Faster than 75.48% of Python submissions. def approach2(self, n: int) -> int: # HELPER METHOD: Product of n def Nproduct(n): n = list(map(int, str(n))) n_product = 1 for x in n: n_product = n_product * x return n_product # HELPER METHOD: Sum of n def Nsum(n): n = list(map(int, str(n))) n_sum = 0 for x in n: n_sum = n_sum + x return n_sum return Nproduct(n) - Nsum(n) if __name__ == '__main__': solution = Solution() n = 234 print(solution.approach2(n))
b78a81ba2ed1f0a512f4a6caebafa33eddd74249
Lucas-Moura-Da-Silva/UNIFESP-aulas-optativas-de-Python
/Exercícios/Exercícios_aula2_11-05_até_17-05/Ex002.py
776
4.15625
4
'''2) Crie uma rotina que solicite uma frase ao usuário e retorne o número de caracteres na frase e o número de espaços.''' #cores cores = {'limpa':'\033[m', 'branco':'\033[1;30m', 'vermelho':'\033[1;31m', 'verde':'\033[1;32m', 'amarelo':'\033[1;33m', 'azul':'\033[1;34m', 'roxo':'\033[1;35m', 'ciano':'\033[1;36m'} #input da questão frase = input('Digite uma frase').strip() #número de caracteres num_carac = len(frase) #número de espaços num_esp = frase.count(' ') print('-='*30) #retorno com o número da questão e o numero de espaços print(f"O número de caracteres é {cores['azul']}{num_carac}{cores['limpa']} e o número de espaços é" f" {cores['branco']}{num_esp}{cores['limpa']}.")
4176b1afd8ec9a05b41ffb6a8204bd09769276cb
Vladislav124382423/Study
/44.py
278
3.90625
4
x = int(input("enter number")) y = int(input("enter number")) z = int(input("enter number")) if x and y and z < 1: if (x < y) and (y < z): x = (y + z)// 2 print(x) if (y < x) and (y < z): y = (x + z)// 2 print(y) else: z = (x + y)//2 print(z)
4f82110ce9eb8704353c792e806ca40112e955a1
xzpjerry/learning
/python/playground/searching/dfs.py
555
3.890625
4
from tree import Node, tree class dfs_tree(tree): def dfs(self, target): visited, stack = [], [self.root] while stack: node = stack.pop() print(node.value) if node.value == target: return True visited.append(node) stack.extend(filter(None, [node.right, node.left])) return False if __name__ == '__main__': example = dfs_tree([7, 2, 10, 1, 5, 9, 12]) print(example) print(example.dfs(13)) ''' 1 2 5 7 9 10 12 7 2 1 5 10 9 12 False '''
3b6fce219985223c83c1e632d3b16b8ead590f60
Timothy2015/Leetcode
/String/5.最长回文子串.py
1,927
3.625
4
# https://leetcode-cn.com/problems/longest-palindromic-substring/ class Solution: def longestPalindrome(self, s: str) -> str: # 思路:先找到每一个回文子串,再比较每个子串长度,返回最长回文子串 # 双指针:从中心开始,向两边扩展,寻找回文子串 # 自定义切片slice函数 -- 浦发机考python不能直接使用切片 def slice(str, i, j): res = '' for k in range(i,j): res += str[k] return res def palindrome(s, i, j): # while s[i]==s[j] and i>=0 and j<=len(s)-1: #测试用例:"a" while i>=0 and j<=len(s)-1 and s[i]==s[j]: i -= 1 j += 1 # return s[i+1:j] return slice(s, i+1, j) res = '' for k in range(len(s)): # 2021.2.8 我的错解,把问题搞复杂了,理解有误 #测试用例:"abb # * 这里要做的分类是: # 1. 以s[k]为中心的子串 —— 作为奇数串 # - a / b / b 为中心 # 2. 以s[k]和s[k+1]为中心的子串 —— 作为偶数串 # - ab / bb 为中心(地毯式搜索,全面覆盖) """ ## 多此一举 ## # 奇数 if (k+1)%2==1: i = int(k/2) str1 = palindrome(s,i,i) res = str1 if len(res) < len(str1) else res # 偶数 if (k+1)%2==0: i = int((k-1)/2) j = i + 1 str2 = palindrome(s,i,j) res = str2 if len(res) < len(str2) else res """ str1 = palindrome(s,k,k) res = str1 if len(res) < len(str1) else res str2 = palindrome(s,k,k+1) res = str2 if len(res) < len(str2) else res return res
83e27022def1ef851f1bf93159f5235a1477b244
VaishnaviReddyGuddeti/Python_programs
/Python_Tuples/TupleLength.py
172
4.21875
4
# To determine how many items a tuple has, use the len() method: # Print the number of items in the tuple: thistuple = ("apple", "banana", "cherry") print(len(thistuple))
cf69d61426156b42ee7916c2585b73057ffe92e4
GeorgeTheTypist/LearnPythonPR
/Functions.py
4,635
4.3125
4
__author__ = 'Pneumatic' def printme(parameters): # create a function called printme using def """This is a doc sting document what this function will do. This prints a passed string into this function""" print(parameters) # prints anything that is stored inside parameters return printme("I'm first call to user defined function printme") # calls the function printme and stores the string in printme("I am the second call to user defined function printme") # the (parameters) def changeme(mylist): # create function mylist with arguments of mylist """This changes a passed list into this function""" mylist.append([1, 2, 3, 4]) # append(add on to the end) [1, 2, 3, 4] to mylist print("Values inside the function: ", mylist) # print the altered values of mylist return # exit out of the function and go back to the outside code mylist = [10, 20, 30] # create a new list changeme(mylist) # call the function changeme with the arguments of mylist print("Values outside the function: ", mylist) # the values stay through the function def changeme(mylist2): # create function changeme using parameters mylist2 """This changes a passed list into this function""" mylist2 = [1, 2, 3, 4] # This would assign new reference in mylist print("Values inside the function: ", mylist2) # print the new value of mylist2 return mylist2 = [10, 20, 30] # create mylist2 changeme(mylist2) # call changeme function print("Values outside the function: ", mylist2) # print values of mylist # Function definition is here def printme(name, age): # create function printme with arguments name and age """This prints a passed string into this function""" print(name, age) # print name then age return printme(age=50, name="Thomas") # since we defined age and name it doesn't have to be in order like in function printme # if we didn't define them we would have to call printme(name,age). Keyword arguments def printinfo(name, age=35): # create function printinfo with arguments name, and age(defualt to 35 if not specified) """This prints a passed info into this function""" print("Name: ", name) # print name print("Age ", age) # print age, will print 35 unless specified in the call statement return # exit the function printinfo() printinfo(age=50, name="miki") # call printinfo function with arguments age=50 and name = miki printinfo(name="miki") # call printinfo function with args of name=miki, default age to 35 as specified in printinfo() def printinfos(arg1, *vartuple): # create function printinfos() with arguments arg1, and *vartuple # * indicates (hold the values of all nonkeyword variable arguments, 70, 60, 50 in this case" """This prints a variable passed arguments""" print(arg1) # prints arg1 which is 10 for var in vartuple: # assign var to each object in vartuple print(var) # print var will print 70, 60, 50 return # exit the function printinfos() printinfos(10) # call function printinfos set arg1 to 10 don't need to define vartuple it will be left a nothing printinfos(70, 60, 50) # call function print, stores any nonkeyword values (all) to *vartuple total = lambda arg3, arg4: arg3 + arg4 # Lambdas take any # of args but return 1 value in form of an expression, can't contain commands, multiple expressions print(total(10, 20)) # print (call lambda total set arg3=10, arg4=20) will return 30 print(total(20, 20)) # print (call lambda total set arg3=20, arg4=20) will return 40 def sums(arg1, arg2): # create function sums with arguments arg1 and arg2 """ This docstring doesn't need to be here its only for explaining what is happening """ totals = arg1 + arg2 # set the variable totals to equal arg1 + arg2 print("Inside the function : ", totals) # print the totals return totals # return the variable totals defined as arg1 + arg2 totals = sums(10, 20) # call function sum with args 10, 20 set totals to whats returned print("Outside the function : ", totals) # print the variable totals totaled = 0 # This is a global variable def sums1(arg1, arg2): # define(create) function sums1 with arguments arg1 and arg2 # Add both the parameters and return them." totaled = arg1 + arg2 # Here total is local variable sets variable totaled to equal arg1 + arg2 print("Inside the function local total : ", totaled) # print variable totaled which is 30 return totaled # return variable totaled # Now you can call sum function sums1(10, 20) print("Outside the function global total : ", totaled) # prints the variable totaled which is 0
2b3e065bd4d11950d5b53a66c3c9631590d8a38c
wulujunwlj/front-end-learning
/python/python-tutorial/functional-program.py
2,553
3.5625
4
# Functional Programming import functools def add(x, y, f): return f(x) + f(y) def func(x): return x * (x + 1) print add(-5, 6, abs) print add(-5, 6, func) def f(x): return x * x print map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) def add(x, y): return x + y print reduce(add, [1, 4, 6, 7, 8]) print sum([1, 4, 6, 7, 8]) def fn(x, y): return x * 10 + y def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] print reduce(fn, map(char2num, '13579')) def is_odd(n): return n % 2 == 1 print filter(is_odd, [1, 2, 3, 5, 234, 7, 89]) def not_empty(s): return s and s.strip() print filter(not_empty, ['A', '', 'B', None, 'C', ' ']) print sorted([35, 12, 5, 91, 0, -4]) print sorted(['abc', '12cadg', '12', 12]) def reversed_cmp(x, y): if x > y: return -1 if x < y: return 1 return 0 print sorted([35, 12, 5, 91, 0, -4], reversed_cmp) print sorted(['bob', 'about', 'Zoo', 'Credit']) def cmp_ignore_case(s1, s2): u1 = s1.upper() u2 = s2.upper() if u1 < u2: return -1 if u1 > u2: return 1 return 0 print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case) def calc_sum(*args): ax = 0 for n in args: ax += n return ax def lazy_sum(*args): def sum(): # closure ax = 0 for n in args: ax += n return ax return sum f = lazy_sum(1, 2, 6, 123) print f print f() print 'print closure ==========' def count(): fs = [] for i in range(1, 4): def f(): return i * i fs.append(f) return fs f1, f2, f3 = count() print f1() print f2() print f3() print map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]) print 'anonymous function =====' f = lambda x: x * x f print f(4) def build(x, y): return lambda: x * x + y * y print build(3, 4)() print 'decorator ==========' def now(): print '2013-12-25' f = now print f print f() print now.__name__ print f.__name__ def log(func): def wrapper(*args, **kw): print 'call %s():' % func.__name__ return func(*args, **kw) return wrapper @log def now(): print '2013-12-25' now() def log2(text): def decorator(func): def wrapper(*args, **kw): print '%s %s():' % (text, func.__name__) return func(*args, **kw) return wrapper return decorator @log2('execute') def now(): print '2013-12-25' now() print 'print partial function=====' print int('12345') print int('12345', base=8) print int('12345', base=16) def int2(x, base = 2): return int(x, base) print int2('1000000') print int2('1010101') int3 = functools.partial(int, base=2) print int3('1000000') print int3('1010101')
e7c1309e18ea0a4bb3bdb2bb1faae800bf8c0b01
hallgrimur1471/algorithms_and_data_structures
/junkyard/c3_5_sort_stack.py
760
4.1875
4
#!/usr/bin/env python3.5 """ Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary stack, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations: push, pop, peek, and isEmpty. """ def sort_stack(s): r = [] while len(s) > 0: v = s.pop() c = 0 while r != [] and v > r[-1]: x = r.pop() s.append(x) c += 1 r.append(v) for _ in range(0, c): x = s.pop() r.append(x) while len(r) > 0: x = r.pop() s.append(x) return s if __name__ == "__main__": s = [46,6,8,3,6,7] sort_stack(s) print(s)
3cf7d5e752e6cee87333b366260c9653e22e9a66
screx/rosalind_solutions
/ham_distance.py
241
3.5625
4
def ham(dna1, dna2): l = len(dna1) distance = 0 for i in range(l): if dna1[i] != dna2[i]: distance += 1 return distance def solution(txt): f = open(txt) dna1 = f.readline() dna2 = f.readline() f.close() return ham(dna1, dna2)
aa9c8138570085226a5a372e2aeb17d70e6f1c78
fanhexiaoseng/Project-practice
/知识点/code/线性查找.py
278
3.734375
4
# _*_ coding : utf-8 _*_ def search(arr, n, x): for i in range(n): if arr[i] == x: return i return -1 arr = ['A', 'B', 'C', 'D', 'E'] x = 'D' realut = search(arr, len(arr), x) if realut != -1: print(realut) else: print("不存在!") #3
d5b59ff5725bc969689af8de9d5fcea0e6d0d547
theopolis/osquery
/tools/codegen/substitute.py
1,314
3.609375
4
#!/usr/bin/env python3 # Copyright (c) 2014-present, Facebook, Inc. # All rights reserved. # # This source code is licensed in accordance with the terms specified in # the LICENSE file found in the root directory of this source tree. """ Replace every occurrences of pattern in every string of input file and write it in output """ import argparse import re import sys def main(args): r = re.compile(args.pattern) for line in args.infile: args.outfile.write( r.sub(args.replacement, line) ) args.outfile.write('\n') def parse_args(): parser = argparse.ArgumentParser(__doc__) parser.add_argument( "-i", "--infile", type=argparse.FileType('r'), default=sys.stdin, help="Input file", ) parser.add_argument( "-o", "--outfile", type=argparse.FileType('w'), default=sys.stdout, help="Output file", ) parser.add_argument( "--pattern", required=True, help="Regexp pattern to search", ) parser.add_argument( "--replacement", required=True, help="Replacement for matched string", ) return parser.parse_args() def run(): args = parse_args() main(args) if __name__ == "__main__": run()
1040e773bb8f115e2988b2b379893721118c8e4a
katatohuk/python
/python_work/players.py
176
3.71875
4
players = ['Igor', 'Masha', 'Petro', 'Vasya', 'Gena'] print(players[0:3]) print("Here are 3 first players of my dream-team:") for player in players[:3]: print(player.title())
7d40a8e758afcb95a4a7d2d79e5657f43d58eb65
ArchitKumar1/Competitive_Programming
/algs/a.py
210
3.546875
4
n = int(input()) for i in range(1,n+1): s = str(n) cnt = 0 while(len(s)!=1): temp = 1 for i in s: temp *= int(i) s = str(temp) cnt+=1 print(n," ",cnt)
6f72f7bde6149bd82066c6d4eb67a0882bfc1eab
Darrenrodricks/w3resourceBasicPython1
/w3schoolPractice/intdiff.py
382
4.09375
4
# Write a Python program which will return true if the two given integer values are equal or their sum or difference is 5. def test_number5(x, y): if x == y or abs(x - y) == 5 or (x + y) == 5: return True else: return False print(test_number5(7, 2)) print(test_number5(3, 2)) print(test_number5(2, 2)) print(test_number5(7, 3)) print(test_number5(27, 53))
5b70934f7f7f432ee767039a11760219ffaa2353
sphilmoon/coreyschafer
/basic/02_strings.py
688
4.375
4
message = 'Hello Phil\'s World' print (len(message)) # print out the number of length or character. print(message[0:14]) # this is called 'Slicing'. # Method and function. method is a function that belongs to an object. print(message.find('World')) # find the and argument. message = message.replace('World', 'Universe') # return statement. print(message) greeting = "hello" name = "phil" message_2 = greeting + ', ' + name + ". Welcome!" message_2 = '{}. {}. Welcome!'.format(greeting, name) # place holder. print(message_2) # formated string. message_2 = f'{greeting.upper()}, {name}. Welcome!' # f string. print(message_2) print(help(str.upper) # string help instruction.
3a926be93f5fb50af5f6fa053cc6788a56887ca1
samysellami/Face-recognition_ComputerVision
/solution.py
5,079
3.6875
4
def face_rec(image): """function that recognizes the person in the given photo input: image grayscale or color image with face on it output; person_id: id of a person (class) """ from matplotlib import pyplot as plt import numpy as np import cv2 from collections import Counter import pickle from numpy import linalg as LA plt.rcParams["figure.figsize"] = (5, 5) # (w, h) using_VJ = 0 ######## using Viola Jones for detection plot_and_print = 1 ############# plotting the images k_dist = 1 ########### number of distances taken into account in the voting for the id with open('trainingVariables', 'rb') as f: dim, dim1, mean_faces, u, W, W_total, index, ids, A = pickle.load(f) imgbgr = cv2.imread(image, cv2.IMREAD_COLOR) img = cv2.cvtColor(imgbgr, cv2.COLOR_BGR2RGB) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ########################## detecting face #################################### if using_VJ: ################ using viola Jones face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') faces = face_cascade.detectMultiScale(gray, 1.3, 5) if (len(faces) == 0): print('error!! no face detected') return -1 for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) roi_gray = gray[y:y + h, x:x + w] roi_color = img[y:y + h, x:x + w] if len(faces) > 1: return -1 else: ################ using deep learning modelFile = "opencv_face_detector_uint8.pb" configFile = "opencv_face_detector.pbtxt" net = cv2.dnn.readNetFromTensorflow(modelFile, configFile) conf_threshold = 0.9 (h, w) = img.shape[:2] blob = cv2.dnn.blobFromImage(img, 1.0, (300, 300), [104, 117, 123], False, False) net.setInput(blob) detections = net.forward() detect = 0 if detections.shape[2] == 0: return -1 for k in range(detections.shape[2]): confidence = detections[0, 0, k, 2] if confidence > conf_threshold: box = detections[0, 0, k, 3:7] * np.array([w, h, w, h]) roi_gray = gray[int(box[1]): int(box[3]), int(box[0]): int(box[2])] roi_color = img[int(box[1]): int(box[3]), int(box[0]): int(box[2])] detect = 1 if detect == 0: return -1 ######################### resizing the image face############################# roi = cv2.resize(roi_gray, dim1, interpolation=cv2.INTER_AREA) ################### projection onto the face space ########################## gamma_test = roi.flatten()[:] phi_test = (gamma_test.transpose() - mean_faces).transpose() w_test = np.dot(u.transpose(), phi_test) ## weights of each image in columns dist = [] for i in range(W_total.shape[1]): dist.append(LA.norm(w_test - W_total[:, i])) ### euclidean distance ###################### voting for the best minimum distance ################ distance = dist indices = [] for i in range(k_dist): ind = np.argmin(distance) distance.pop(ind) indices.append(ind) occur = Counter(ids[indices]) min_occur = 0 if len(set(ids[indices])) == 1: ind = indices[0] person_id = ids[ind] else: for id, oc in occur.items(): if oc > min_occur: min_occur = oc person_id = id ind = index[person_id][0] if plot_and_print: ######################### plot the input image ##############################"" plt.figure(figsize=(20, 5)) plt.subplot(1, 4, 1) plt.imshow(img, 'gray') plt.title('input image'.format()) plt.xticks([]), plt.yticks([]) ######################## plotting face ###################################### plt.subplot(1, 4, 2) plt.imshow(roi_color, 'gray') plt.title('detected face'.format()) plt.xticks([]), plt.yticks([]) ################## plotting identified and reconstructed face ################ plt.subplot(1, 4, 3) plt.imshow((A[:, ind] + mean_faces).reshape(dim), 'gray') plt.title('identified face') plt.xticks([]), plt.yticks([]) A_rec = np.sum(np.multiply(u, w_test), axis=1) + mean_faces plt.subplot(1, 4, 4) plt.imshow(A_rec.reshape(dim), 'gray') plt.title('reconstruted face ') plt.xticks([]), plt.yticks([]) plt.show() #################### printing distance within and from face space ############ difs = dist[ind] dffs = LA.norm(np.sum(np.multiply(u, w_test), axis=1) - phi_test) print('the distance within the face space is difs = :{}'.format(difs)) print('the distance from the face space is dffs = :{}'.format(dffs)) print('the face identified is id = {}'.format(person_id)) return person_id
c4f6b5025f251b5f195dd50434dfd7b74f4b53b6
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/leap/7c0304694e024bd1ae3362008867ecf6.py
215
3.734375
4
def is_leap_year(year): try: if (year%4==0 and year%100!=0) or year%400==0: return True else: return False except TypeError: return False
538a3a365119431ec35f657a1407989df860b3aa
MarvinSilcGit/Alg
/Python/2018-2019/Quadrado.py
532
4.03125
4
cont = 1 while cont != 0: print() a = input("Digite a lado de um quadrado: ") if a.isdigit() == True: a = int(a) z = 0 y = 0 w = 0 while y != a: while z != a: z += 1 while w != 1: w += 1 print("* "*z) z = 0 w = 0 y += 1 else: print() print("Digite apenas números") continue
c102603ebf4673c8dd6f1fb9c28d7cc98605a09e
lincolnjohnny/py4e
/2_Python_Data_Structures/Week_6/example_08.py
251
3.90625
4
# Sorting Lists of Tuples d = {'a': 10, 'b': 1, 'c': 22} # declaring a dictionary with keys and values print(d.items()) # dict_items([('a', 10), ('b', 1), ('c', 22)]) print(sorted(d.items())) # [('a', 10), ('b', 1), ('c', 22)]
b8f4ad4ce604083791daf84984b9d3563b7ef64a
DilyanTsenkov/SoftUni-Software-Engineering
/Python Fundamentals/03 Lists Basics/Exercises/10_Bread_Factory.py
1,200
3.53125
4
day_events = input().split("|") new_day_events_list = [] energy = 100 coins = 100 close = False for i in day_events: new_day_events_list.append(i.split("-")) for i in range(len(new_day_events_list)): event = new_day_events_list[i][0] number = int(new_day_events_list[i][1]) if event == "rest": if energy + number > 100: print(f"You gained {100 - energy} energy.") energy = 100 else: print(f"You gained {number} energy.") energy += number print(f"Current energy: {energy}.") elif event == "order": if energy >= 30: print(f"You earned {number} coins.") coins += number energy -= 30 else: energy += 50 print("You had to rest!") elif event != "order" and event != "rest": if coins - number > 0: print(f"You bought {event}.") coins -= number else: print(f"Closed! Cannot afford {event}.") close = True break if not close: print(f"Day completed!") print(f"Coins: {coins}") print(f"Energy: {energy}")
49da829aa548a405955939f1342e2356811bc238
Blasco-android/Curso-Python
/desafio99.py
745
4.3125
4
''' Exercício Python 099: Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores inteiros. Seu programa tem que analisar todos os valores e dizer qual deles é o maior. ''' from time import sleep def linha(): print('=-' * 30) def maior(* num): print('Analisando os valores passados...') sleep(.5) print(f' - {num} - Foram informados {len(num)} valores ao todo.') sleep(.5) maior = cont = 0 for n in num: if cont == 0: maior = n else: if n > maior: maior = n print(f'O maior número informado foi {maior}.') linha() maior(1, 5, 8, 9, 11) linha() maior(4, 1, 10) linha() maior(10, 13, 11, 23, 45) linha()
a4c89103de6d9f847d601b9e238a6fa7aa56382b
rd37011/ml
/kmeans/kmeans.py
3,712
3.65625
4
#!/usr/bin/env python import csv import random import numpy as np import math """kmeans.py: K-Means clustering algorithm.""" __author__ = "Ryan Diaz" __copyright_ = "Copyright 2018, University of Miami, Coral Gables, FL " class _kmeans_: def __init__(self, p, label): self.point = p self.label = label def init(data, k): centroids = [] labeleddata = [] length = len(data) for i in range(k): index = random.randint(0, length-1) centroids.append(data[index]) # assigns random centroids for d in data: d = np.array(d) p = _kmeans_(d, None) labeleddata.append(p) # list of _kmeans_ objects with points and blank labels return adjustpoints(centroids, labeleddata) def adjustpoints(centroids, labeleddata): mndist = math.inf for d in labeleddata: for c in centroids: dist = np.sqrt(sum((d.point - c) ** 2)) # gets euclidean distance between point d and centroid c if dist < mndist: mndist = dist label = c mndist = math.inf d.label = label labeleddata = np.asarray(labeleddata) return centroids, labeleddata def adjustcentroids(centroids, labeleddata): newcentroids = [] sum = np.zeros(len(labeleddata[0].point)) count = 0 for c in centroids: c = np.array(c) sum = np.array(sum) for i in range(len(labeleddata)): if all(labeleddata[i].label == c): # checking if label equal elementwise to c count += 1 sum = sum + labeleddata[i].point sum = np.array(sum / count) newcentroids.append(sum) sum, count = 0, 0 newcentroids = np.asarray(newcentroids) return newcentroids, labeleddata def shouldstop(oldcentroids, centroids, iterations, maxiter): if np.array_equal(oldcentroids, centroids): return True if iterations < maxiter: return False return False def kmeans(): # driver program k = 4 maxiter = 30 norm_data = loaddata() data = init(norm_data, k) # sets random centroids, None for labels in object array centroids, labeleddata = data iterations = 0 oldcentroids = None while not shouldstop(oldcentroids, centroids, iterations, maxiter): # while under max iter or centroids dont change oldcentroids = centroids iterations += 1 centroids, labeleddata = adjustcentroids(centroids, labeleddata) centroids, labeleddata = adjustpoints(centroids, labeleddata) export(centroids, labeleddata) print(iterations) for c in centroids: print(c) def export(centroids, labeleddata): csv.register_dialect('output', delimiter=' ', lineterminator="\n") with open('kmeans_2ddata.csv', 'a', newline="\n") as f: writer = csv.writer(f) for c in centroids: writer.writerow(c) writer.writerow("\n") for p in labeleddata: if all(p.label == c): writer.writerow(p.label) writer.writerow(p.point) writer.writerow("\n") return 0 def loaddata(): dataset = [] with open('2dtrain_data.csv', 'r') as f: csv_reader = csv.reader(f, delimiter=',') for row in csv_reader: row = list(map(float, row)) """ mn = min(row) mx = max(row) for i in range(len(row)): if mx - mn == 0: row[i] = 0.0 else: row[i] = (row[i] - mn)/(mx - mn) """ dataset.append(row) return dataset kmeans()
4600cebeebba19779f4825459e18278763094e5c
beatonma/snommoc
/util/cleanup/unused.py
1,167
3.765625
4
""" When inspecting code we may find classes or functions that are not currently in use but we do not want to delete them as they may be useful later. Such classes should be updated to inherit UnusedClass, and such functions should be marked with the @unused decorator. This allows """ class UnusedException(BaseException): pass class UnusedClass: """Utility base class to mark a child class as unused. If a class is currently unused but may be used again in the future, it should inherit Unused. This allows us to search for unused classes later and decide if we still want to keep them. A child of this class will raise UnusedException when instantiated - you must remove the inheritance if you want to use the class. """ def __init__(self, *args, **kwargs): raise UnusedException( f"Class {self.__class__.__name__} is marked as unused! Remove inheritance of Unused to enable it again." ) def unused(func): def f(*args, **kwargs): raise UnusedException( f"Function {func.__name__} is marked as unused! Remove @unused decorator to enable it again." ) return f
892f9108ac5118fe346a440e42e592dc3f1bf8c4
cah835/Intro-to-Programming-1284
/Classwork Programs/classwork.py
461
3.78125
4
def main(): my_list = [1,2,3,4,5,6,7,8,9,10] total = sum(my_list) for each_element in range(11): print(each_element) print(total) total2 = 0 for element in my_list: total2 += element print(total2) total3=0 index =0 while index < len(my_list): total3 += my_list[index] index += 1 print(total3) list_exercise(my_list) def list_exercise(para_list): para_list[0] = 200 main()
f646d10e0c1b8102b04ac91920290900ae0792aa
paulohenriquegama/Blue_Modulo1-LogicaDeProgramacao
/Aula11/Dicionario.py
501
3.578125
4
familia1 = [('Paulo',29),('Morgania',24),('Hadassa',3)] familia = dict(familia1) pais = {'Pai':'Iremi','Mãe':'Odalesa','Irmã':'Alana'} toda= {} ''' print(familia1[1][1]) print() print(familia) print(familia.get('Hadassa'))''' for (k,v),(k2,v2) in zip(familia.items(),pais.items()): print(k,'-',v) print(k2,'-',v2) print() dele = pais.pop("Irmãa","Não encontrado") print(pais) print(f'Deletamos o {dele}') familia.update(pais) toda = familia print(familia) print(pais) print(toda)
d9525dc3aad2d3bea52f7bd70ddbb78fd6c6ea7a
MarcosMon/Python
/Codewars/Kata7/Banking_class.py
1,189
3.921875
4
class User(object): def __init__(self, name, balance, checking_account): self.name = name self.balance = balance self.checking_account = checking_account def withdraw(self, money_withdraw): if money_withdraw > self.balance: raise ValueError() self.money_withdraw = money_withdraw self.balance -= self.money_withdraw return self.name + " has " + str(self.balance) + "." def check(self, other, money): if not other.checking_account: raise ValueError() self.balance+= money other.balance-=money return self.name + " has " + str(self.balance) + " and " + other.name + " has " + str(other.balance) + "." def add_cash(self, money_add ): self.balance+=money_add return self.name + " has " + str(self.balance) + "." Jeff = User('Jeff', 70, True) Joe = User('Joe', 70, True) if __name__ == '__main__': assert Jeff.withdraw(2) == 'Jeff has 68.' assert Joe.check(Jeff, 50) == 'Joe has 120 and Jeff has 18.' assert Jeff.check(Joe, 80) == 'Jeff has 98 and Joe has 40.' assert Jeff.add_cash(20) == 'Jeff has 118.'
b6de0912b8042eb68e3a90f41fdf6eaac6ed47d5
Michellinian/unit-3
/Week29/task2.py
433
4
4
# Write a Python program that generates random passwords of length 20. # The user provides how many passwords should be generated import string, random usrinput = int(input()) lett = string.ascii_letters num = string.digits punct = string.punctuation allchar = lett + num + punct for x in range(1, usrinput+1): pwd = '' for y in range(20): pwd += random.choice(allchar) print(f"Password {x}: {pwd}")
134610466ca7ed40e2cd01a4733787e4f588314b
ServioTRC/CodeFights_Solutions
/Arcade/Intro/Exploring the Waters/palindromeRearranging.py
379
3.5625
4
def palindromeRearranging(inputString): letras = [0 for _ in range(26)] for i in inputString: letras[ord(i.lower())-97] += 1 impar = False if len(inputString) % 2 != 0: impar = True for val in letras: if val % 2 != 0: if impar: impar = False else: return(False) return(True)
266ee3d0d77628384d2760e245512133a9673269
afsalcodehack/leetcode
/Interview/KMostFrequentElements.py
415
4.15625
4
# K Most Frequent Elements # input: [1,6,2,1,6,1,6], k=2 # output:[1,6] # # k1 = will be 1 and k=2 will be 6 so bothe are same count(3) # in this case combine together def most_freq_num(ar, k): dict = {} for i in ar: if i in dict: dict[i] = dict[i] + 1; else: dict[i] = 1; dict = sorted(dict.items()); print(dict); a = [1,6,2,1,6,1,6] most_freq_num(a, 2)
b5f1c955ad5ce1634d9d62fecce5e22276213217
jnoas123/python
/oef sequence 1/oef_7.py
193
3.984375
4
number = 15 print('the starting number is 15') number *= 10 print(number) number += 5 print(number) number -= 7 print(number) number += 1 number *= 100 print(number) number //= 2 print(number)
2a6d4d1d3e5f04499baa2eebb7f45c3e102d993f
chanyoonzhu/leetcode-python
/516-Longest_Palindromic_Subsequence.py
1,145
3.828125
4
""" - https://leetcode.com/problems/longest-palindromic-subsequence/ - intuition: greedily match from two ends into middle """ """ - dynamic programming (top-down) - O(n^2), O(n^2) """ class Solution: def longestPalindromeSubseq(self, s: str) -> int: @lru_cache(None) def dp(i, j): if i > j: return 0 if i == j: return 1 if s[i] == s[j]: return 2 + dp(i + 1, j - 1) else: return max(dp(i + 1, j), dp(i, j - 1)) return dp(0, len(s) - 1) """ - dynamic programming (bottom-up) - O(n^2), O(n^2) """ class Solution: def longestPalindromeSubseq(self, s: str) -> int: N = len(s) dp = [[0] * N for _ in range(N)] for diff in range(N): for i in range(N - diff): if diff == 0: dp[i][i] = 1 else: j = i + diff if s[i] == s[j]: dp[i][j] = 2 + dp[i+1][j-1] else: dp[i][j] = max(dp[i+1][j], dp[i][j-1]) return dp[0][N-1]
9d7de9e9233063d2b8ebd0f968d7cdc6169cdf03
inverseundefined/DataCamp
/Regular_Expressions_in_Python/03-Regular_Expressions_for_Pattern_Matching/09-Invalid_password.py
1,335
4.25
4
''' Invalid password The second part of the website project is to write a script that validates the password entered by the user. The company also puts some rules in order to verify valid passwords: It can contain lowercase a-z and uppercase letters A-Z It can contain numbers It can contain the symbols: *, #, $, %, !, &, . It must be at least 8 characters long but not more than 20 Your colleague also gave you a list of passwords as examples to test. The list passwords and the module re are loaded in your session. You can use print(passwords) to view them in the IPython Shell. Instructions 100 XP Instructions 100 XP Write a regular expression to match valid passwords as described. Scan the elements in the passwords list to find out if they are valid passwords. To print out the message indicating if it is a valid password or not, complete .format() statement. ''' # Write a regex to match a valid password regex = r"[a-zA-Z0-9*#\$%!&\.]{8,20}" for example in passwords: # Scan the strings to find a match if re.search(regex, example): # Complete the format method to print out the result print("The password {pass_example} is a valid password".format(pass_example=example)) else: print("The password {pass_example} is invalid".format(pass_example=example))
723f4bb634b5edf0dd63786516a3ec391410c844
Ryan-lee0217/Python-jeffrey0912
/untitled21.py
322
3.75
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 28 15:05:47 2020 @author: ryanl """ import tkinter as tk window = tk.Tk() window.geometry("300x300") for i in range(1,10): for j in range(1,10): l = tk.Label(window,text=i*j) l.grid(row=i,column=j,padx=5,pady=5) window.mainloop()
6ad99ca0a227e02cf664cb0f10516d5a31021da9
fornutter/git_test
/python_example/0011/0011.py
399
4.03125
4
# 敏感词屏蔽 import string def open_file(name): b=[] with open(name,"r") as f: f=f.readlines() for i in f: i=i.strip() b.append(i) return b def decide(str,ListWord): if str in ListWord: print("Freedom") else: print("Human Rights") if __name__ == "__main__": yourWord=input("please input your word:") fi=open_file("filtered_words.txt") decide(yourWord,fi)
2f82c2a75a14fdca740fc0ee2453952e35ab6b5b
Franktian/leetcode
/addDigits.py
209
3.859375
4
def addDigits(num): if num < 10: return num s = sumOfDigit(num) return addDigits(s) def sumOfDigit(num): s = 0 while num != 0: s += num % 10 num /= 10 return s
0c8c491aa4b16d8690585ad0675ec3931db16ecb
reevesba/computational-intelligence
/projects/project3/src/max_func/mf_mutate.py
1,430
3.5
4
''' Function Maximization Mutator Author: Bradley Reeves, Sam Shissler Date: 05/11/2021 ''' from numpy import random from typing import List, TypeVar MaxFuncMutator = TypeVar("MaxFuncMutator") class MaxFuncMutator: def __init__(self: MaxFuncMutator, length: int, mutation_prob: float) -> None: ''' Initialize MaxFuncMutator instance Parameters ---------- self : MaxFuncMutator instance length : Individual length mutation_prob : Probability of mutation occuring Returns ------- None ''' self.length = length self.mutation_prob = mutation_prob def mutate(self: MaxFuncMutator, children: List) -> List: ''' Possibly mutate children Parameters ---------- self : MaxFuncMutator instance children : Mutator candidates Returns ------- children : Children with possible mutations ''' for child in children: if random.rand() < self.mutation_prob: # Select a random index to mutate index = random.randint(self.length) # Do mutation if index == 0: child[index] = random.randint(3, 11) if index == 1: child[index] = random.randint(4, 9) return children
de90b598e1bccd7980b5918da1f8f2f5bd967e06
HelenaOliveira1/Exerciciosprova2bim
/Questão 40.py
1,236
3.828125
4
print("Questão 40") print("") codigo = int(input("Digite o Código da Cidade: ")) veiculos = int(input("Digite o número de veículos de passeio (em 1999): ")) acidentes = int(input("Digite o número de acidentes de trânsito com vítimas (em 1999): ")) MA = acidentes ME = acidentes soma = 0 soma2 = 0 aux = 1 ccm = codigo cc = codigo for i in range (1,6): if (acidentes >= MA): MA = acidentes ccm = codigo else: ME = acidentes cc = codigo soma += veiculos if (veiculos <= 2000): soma2 += acidentes aux += 1 for a in range (1,5): print("") codigo = int(input("Digite o Código da Cidade: ")) veiculos = int(input("Digite o número de veículos de passeio (em 1999): ")) acidentes = int(input("Digite o número de acidentes de trânsito com vítimas (em 1999): ")) media = soma/ 5 media2 = soma2/ aux print("") print("Maior índice de acidentes de trânsito: ",MA, "na cidade",ccm) print("Menor índice de acidentes de trânsito: ",ME, "na cidade",cc) print("Media de veículos da Somatória de todas as cidades: ", media) print("Media de acidentes de trânsito nas cidades com menos de 2.000 veículos de passeio: ", media2)
6ae07cc5c0f2161166169f008167e0ec69b6b7db
melvz/frisby
/object-oriented-exercise/main_bank.py
1,737
3.984375
4
from bank_account import Account ACCOUNTS = {} show_menu = True while(show_menu): print "1 - CREATE account" print "2 - VIEW accounts" print "3 - WITHDRAWAL" print "4 - EXIT" selection = raw_input("Select Action: ") if selection == "1": name = raw_input("Enter Name: ") balance = raw_input("Indicate initial balance amount: ") account = Account(name=name, balance=float(balance), number=str(len(ACCOUNTS) + 1)) ACCOUNTS[account.number] = account print "Account Created =) " elif selection == "2": for account_no, account in ACCOUNTS.items(): print "Account Number: %s; Account Name: %s; Is Open?: %s; Date Opened: %s; Balance: %s" % (account_no, account.name, account.is_open, account.date_opened, account.balance) if selection == "3": print "Time to WITHDRAW your cash" withdraw_acct = raw_input("Accountnumber: ") for withdraw_acct, account in ACCOUNTS.items(): withdrawal_amount = float(raw_input("key in the cash amount you want spill out from this Machine---> : ")) if withdrawal_amount < account.balance: account.balance -=withdrawal_amount print "your new balance is ", account.balance else: print "No sufficient funds" elif selection == "4": show_menu = False print "Exit" else: print "Please try again and select valid option" ## end of code
8da54b6556a56b49e593a17121b86df269a95b4c
vigorousyd168/leetcode
/Python/374GuessNumberI.py
853
3.875
4
# 374 Guess Number Higher or Lower I # The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num): number = 7 def guess(num): if num < number: return 1 elif num > number: return -1 else: return 0 class Solution(object): def guessNumber(self, n): """ :type n: int :rtype: int """ lo, hi = 1, n while lo <= hi: # guess is mid mid = (lo + hi)/2 r = guess(mid) if r == -1: hi = mid - 1 elif r == 1: lo = mid + 1 else: return mid def main(): sol = Solution() print sol.guessNumber(10) # return 6 if __name__ == '__main__': main()
7c51ec1ce587446cc86843bac03cca177c28207d
GjjvdBurg/ffcount
/ffcount/__init__.py
1,458
3.75
4
# -*- coding: utf-8 -*- __version__ = "0.1.5" # Author: Gertjan van den Burg <gertjanvandenburg@gmail.com> # # License: Apache License 2.0 from pathlib import Path from typing import Tuple from typing import Union from .count import fast_file_count def ffcount( path: Union[str, bytes, Path] = ".", recursive: bool = True, hidden: bool = True, quiet: bool = True, ) -> Tuple[int, int]: """Fast file count Count the files and directories in the given path. By default the function is recursive and does not print errors. This function uses the C implementation by Christopher Schultz. Parameters ---------- path : str or bytes The path where to start counting. By default the current working directory will be used. recursive : bool To recurse or not to recurse. If recurse is False, only the files and directories in the directory given by ``path`` will be counted. hidden : bool Count hidden files and directories as well. quiet : bool Don't print errors to the screen. If True, the function will fail quietly and not print any errors. Returns ------- files_count : int Number of files counted. dir_count : int Number of directories counted. """ if isinstance(path, Path): path = str(path) if not isinstance(path, bytes): path = path.encode() return fast_file_count(path, recursive, hidden, quiet)
3c33b4e84743a21e1b12794b4e3a6a309ae8ba37
sthefanni/pythonrepeticao
/questao2.py
194
3.578125
4
login = input("login: ") senha = input("senha: ") while login == senha: print("sua senha deve ser diferente do login: ") senha = input("senha: ") print("resposta válida")
8d05ab89d96a42ac71de3b0d1ece0f4aaebdf409
treedbox/python-3-basic-exercises
/concatenate/app.py
687
3.859375
4
"""Concatenation.""" def bar(name, times): """Hello many times in many languages.""" print('Hello', name, times, 'times!') # it's not concatenated but seems like print('Hallo %s %s mal!' % (name, times)) print('Bonjour ' + name + ' ' + str(times) + ' fois!') print('こんにちは {name} {times}回!'.format(name=name, times=times)) print('Kon\'nichiwa %(name)s %(times)s-kai!' % {'name': name, 'times': times}) print('Olá %(name)s %(times)s vezes!' % locals()) bar('Treedbox', 10) # Hello Treedbox 10 times! # Hallo Treedbox 10 mal! # Bonjour Treedbox 10 fois # こんにちは Treedbox 10回! # Kon'nichiwa Treedbox 10-kai! # Olá Treedbox 10 vezes!
d8c0d059ac676203ebd29bfdd22809b5e8fb292b
liyi0206/leetcode-python
/231 power of two.py
401
3.828125
4
class Solution(object): #def isPowerOfTwo(self, n): # """ # :type n: int # :rtype: bool # """ # if n<=0: return False # while n>1: # m =n%2 # if m==1: return False # else: n /= 2 # return True def isPowerOfTwo(self, n): return n>0 and n&(n-1) == 0 a=Solution() print a.isPowerOfTwo(6)
10c60d63373a72135749d3e0433c0ccef04f13a8
AlejoJorgeGonzalez/DS_A02_Basico_de_Python
/c27_adivina_el_numero.py
926
4.1875
4
# Se utiliza módulos, los módulos de python son códigos # que los mismos desarrolladores de python han realizado para # nosotros, son funciones que permiten ahorrar tiempo y trabajo # en la escritura de nuestro código, para llamarlos usamos la # palabra reservada import # El módulo ramdom es el diseñado para funciones de aleatoriedad import random def run(): # random.randint da un número entero aleatorio entre un # rango, que para este caso es de 1 al 100 numero_aleatorio = random.randint(1, 100) numero_elegido = int(input('Elige un número del 1 al 100: ')) while numero_elegido != numero_aleatorio: if numero_elegido < numero_aleatorio: print('Busca un número más grande') else: print('Busca un número más pequeño') numero_elegido = int(input('Elige otro número: ')) print('¡Ganaste!') if __name__ == '__main__': run()
04eacefca9fae1436fe64cdee379d5143c34b221
JavonDavis/Competive-Programming-Python
/hackerrank/competitions/rookierank3/comparing_times.py
974
3.71875
4
#!/bin/python import sys def timeCompare(t1, t2): t1 = t1.split(":") t2 = t2.split(":") decider1 = t1[1][-2:] decider2 = t2[1][-2:] if decider1 == "AM" and decider2 == "PM": return "First" elif decider2 == "AM" and decider1 == "PM": return "Second" else: decider1 = int(t1[0]) decider2 = int(t2[0]) if decider1 == 12: decider1 = 0 if decider2 == 12: decider2 = 0 if decider1 < decider2: return "First" elif decider1 > decider2: return "Second" else: decider1 = int(t1[1][:-2]) decider2 = int(t2[1][:-2]) if decider1 < decider2: return "First" else: return "Second" q = int(raw_input().strip()) for a0 in xrange(q): t1, t2 = raw_input().strip().split(' ') t1, t2 = [str(t1), str(t2)] result = timeCompare(t1, t2) print(result)
e2661f4d33cfe58e3b18b4b65cc16525eb806a51
RowanArland/90-beginner-python-programs-
/quest77.py
199
3.671875
4
exp77list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'] def listslicing(S, slicing): return [S[i::slicing] for i in range(slicing)] print(listslicing(exp77list,3))
9aa87bd965074921c0e4b45a67d858cd8d02f09d
ralphtatt/project-euler
/problem_007.py
716
4.0625
4
""" Problem 7: By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ def is_prime(num: int, primes: list[int]) -> bool: # This is assuming the list 'primes' contains all lower valued prime numbers for i in primes: if num % i == 0: return False return True def find_prime(position: int) -> int: if position < 1: raise Exception() primes = [2] candidate = 3 while len(primes) < position: if is_prime(candidate, primes): primes.append(candidate) candidate += 2 return primes[-1] prime = find_prime(10001) print(f"{prime=}")
e263907afdecddd84d6f35fdbab589400a32a0a5
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/thomasvad/lesson3/slicinglab.py
1,234
4.1875
4
def seq1(seq): '''swaps th first and last items of a sequence''' newseq = seq[-1:] + seq[1:-1] + seq[:1] return newseq def seq2(seq): '''returns every other item removed''' newseq = seq[::2] return newseq def seq3(seq): '''removes the first 4, last 4 and every other item''' newseq = seq[4:-4:2] return newseq def seq4(seq): '''returns elements reversed''' newseq = seq[::-1] return newseq def seq5(seq): """returns the last third, then first third, then the middle third of a sequence""" apart = int(len(seq)/3) newseq = seq[-apart:] + seq[:apart] + seq[apart:-apart] return newseq if __name__ == "__main__": #test a_string = "this is a string" a_tuple = (2, 54, 13, 12, 5, 32) assert seq1(a_string) == "ghis is a strint" assert seq1(a_tuple) == (32, 54, 13, 12, 5, 2) assert seq2(a_string) == "ti sasrn" assert seq2(a_tuple) == (2, 13, 5) assert seq3(a_string) == " sas" assert seq3(a_tuple) == () assert seq4(a_string) == "gnirts a si siht" assert seq4(a_tuple) == (32, 5, 12, 13, 54, 2) assert seq5(a_string) == "tringthis is a s" assert seq5(a_tuple) == (5, 32, 2, 54, 13, 12) print('passed test')
26d00be2e331610824d1e29d00da279be80b49a2
rafaelacarnaval/uri-online-judge
/uri_1008.py
156
3.71875
4
numero = int(input()) horas = int(input()) valor = float(input()) salario = horas * valor print("NUMBER = %d" %numero) print("SALARY = U$ %.2f" %salario)
19d0b2b7c377fe41451fe92a99b7961ee5eb568e
getabear/leetcode
/git.py
2,185
3.90625
4
# 这是一个测试 class ListNode: def __init__(self, x): self.val = x self.next = None class lian: def creat(self,nums): #构造一个链表的函数 ret=ListNode(-1) res=ret for i in nums: ret.next=ListNode(i) ret=ret.next return res.next def display(self,head): #展示一个链表的值 while head: print(head.val) head=head.next class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class er: def creat_er(self,nums): #宽度优先遍历利用数组构造二叉树,nums是构造二叉树的数组 if not nums: return root=TreeNode(nums[0]) queue=[root] length=len(nums) index=1 while(queue): newroot=queue.pop(0) if index<length and newroot: if nums[index]!=None: newroot.left=TreeNode(nums[index]) else: newroot.left=None index+=1 queue.append(newroot.left) if index<length and newroot: if nums[index]!=None: newroot.right=TreeNode(nums[index]) else: newroot.right=None index+=1 queue.append(newroot.right) return root def creat_er(nums): #宽度优先遍历利用数组构造二叉树,nums是构造二叉树的数组 if not nums: return root=TreeNode(nums[0]) queue=[root] length=len(nums) index=1 while(queue): newroot=queue.pop(0) if index<length and newroot: if nums[index]!=None: newroot.left=TreeNode(nums[index]) else: newroot.left=None index+=1 queue.append(newroot.left) if index<length and newroot: if nums[index]!=None: newroot.right=TreeNode(nums[index]) else: newroot.right=None index+=1 queue.append(newroot.right) return root
b055a7e7d4c44ed9d18eb777fce43d337518671f
imichaelnorris/LindoParser
/lindoparse.py
3,276
3.984375
4
import sys import string EQUALITY = ['=', '<=', '>=', '<', '>'] def lhs(line): '''move variables to left of equals sign''' if (not '=' in line): return line temp = line.split(' ') for i in EQUALITY: if i in temp: equalsLocation = temp.index(i) #print('equalsLocation {0}'.format(equalsLocation)) for i in range(1, len(temp)): #if the intersection of a string of only numbers # and only numbers has length of zero, the string only contains nums if not len(set(temp[i]) - set(string.digits+'+'+'-')) == 0: #print('true') if ( (i-1) == equalsLocation): #print('eqsignloc') equalsLocation += 1 temp[i], temp[i-1] = temp[i-1], temp[i] #print("swapped: " + temp[i-1]) if (temp[i-1][0]) == '+': temp[i-1] = temp[i-1].replace('+', '-') elif (temp[i-1][0] == '-'): temp[i-1] = temp[i-1].replace('-', '+') else: temp[i-1] = '-' + temp[i-1] else: pass #print('false') if (temp[-1] in ['=', '<', '<=', '>', '>=']): temp.append('0') return " ".join(temp) def expandVariable(text, parameters): if (text in ['=', '<=', '>=', '>', '<']) or (len(set(text) - set(string.digits)) == 0): temp = [text] for i in range(0, len(parameters)//2): temp *= (parameters[2*i+1] - parameters[2*i] + 1) return temp temp = [text] while True: if ('_i' in temp[0]): pass else: break newtemp = [] print(temp) for equation in temp[:]: for i in range(parameters[0], parameters[1]+1): tempEquation = equation #can replace a single digit number in an equation with an index # _i-n, with 0<=n<=9 try: minusIndex = equation.index("_i") + 2 if equation[minusIndex] == '-': i = i - int(equation[minusIndex + 1]) print("equation before: " + equation) tempEquation = equation[:minusIndex] + equation[minusIndex+2:] print("equation after: " + equation) except IndexError: pass except ValueError: pass newtemp.append(tempEquation.replace('_i', str(i), 1)) temp = newtemp parameters.pop(0) parameters.pop(0) return temp def getequations(text, parameters): temp = text.split(' ') tempList = [] for i in temp: tempList.append(expandVariable(i, parameters[:])) print(tempList) output = [] for i in range(0, len(tempList[0])): tempLine = [] for j in range(0, len(tempList)): tempLine.append(tempList[j][i]) output.append(" ".join(tempLine)) return "\r\n".join([lhs(i) for i in output]) if __name__ == '__main__': '''text = sys.argv[1] parameters = [int(i) for i in sys.argv[2:]] print(getequations(text, parameters))''' pass
98d107db396e68ee1a3c97fbc5caacbb2fa0cece
ParkKeunYoung/py_projects
/basic/p4.py
1,148
3.796875
4
''' > 딕셔너리 : {} -> , js의 객체와 동일, 순서 x, 키: 값, 키는 중복되면 안됨, 값 중복은 허용 => 테이블상의 한 개의 row,json의 객체 ''' # 이 스타일을 가장 많이 사용 dic = {} print(dic, len(dic), type(dic)) dic = dict() print(dic, len(dic), type(dic)) ##################################################################################### # 키를 통해서 값을 이해할 수 있다. 직관적으로 dic = { 'name' : '홍길동', 'age' : 100 } print(dic, len(dic), type(dic)) # 인덱싱 : 딕셔너리는 순서가 없으므로, 데이터를 특정할 수 있는 키 값을 사용한다. print(dic['name']) # 데이터추가, 키는 모든지 올 수 있다. 2는 인덱스가 아닌 => <<< 키를 의미!! >>> dic[2] = 'hello' print(dic, len(dic), type(dic)) print( dic[2] ) ##################################################################################### print( dic.keys() ) # 키 list 출력 print( dic.values() ) # 키 조사 print( 'name' in dic ) # for문으로 돌려보기 => for 에서 확인
69f7ad020546ec1c39fac6138c1377e27627b9f9
ManaTagawa/GitHubTest
/Make_matrix.py
1,795
3.515625
4
import torch import itertools # '1'で作成 # >>> Make_matrix_one(3) # tensor([[1, 0, 0], # [0, 1, 0], # [0, 0, 1], # [1, 1, 0], # [1, 0, 1], # [0, 1, 1], # [1, 1, 1]]) def Make_matrix_one(x_num): # 説明変数の数 x_list = list(range(0,x_num)) # [0, 1, 2, ..., x_num-1] houjo_num = 2**x_num -1 # べき集合の数(空集合除く) matrix = torch.zeros(houjo_num, x_num) # 要素が全部0のtensor # 行列作成 R = 0 for one_num in range(1,x_num+1): c = list(itertools.combinations(x_list, one_num)) # 組み合わせ計算 for i in range(len(c)): row = i+R # 1列ずつ重み行列を作成 for j in range(one_num): matrix[row][c[i][j]] = 1 R += len(c) # 作成した行列を返す return matrix ################################################## # '0'で作成 # >>> Make_matrix_zero(3) # tensor([[0, 1, 1], # [1, 0, 1], # [1, 1, 0], # [0, 0, 1], # [0, 1, 0], # [1, 0, 0], # [0, 0, 0]]) def Make_matrix_zero(x_num): # 説明変数の数 x_list = list(range(0,x_num)) # [0, 1, 2, ..., x_num-1] houjo_num = 2**x_num -1 # べき集合の数(空集合除く) matrix = torch.ones(houjo_num, x_num) # 要素が全部0のtensor # 行列作成 R = 0 for one_num in range(1,x_num+1): c = list(itertools.combinations(x_list, one_num)) # 組み合わせ計算 for i in range(len(c)): row = i+R # 1列ずつ重み行列を作成 for j in range(one_num): matrix[row][c[i][j]] = 0 R += len(c) # 作成した行列を返す return matrix
7208c16d2466136300a4b15713edbc86c914403f
elsa7718/sc101-2020-Nov
/Upload/boggle/sierpinski.py
2,797
3.875
4
""" File: sierpinski.py Name: --------------------------- This file recursively prints the Sierpinski triangle on GWindow. The Sierpinski triangle is a fractal described in 1915 by Waclaw Sierpinski. It is a self similar structure that occurs at different levels of iterations. """ from campy.graphics.gwindow import GWindow from campy.graphics.gobjects import GLine from campy.graphics.gobjects import GPolygon from campy.gui.events.timer import pause # Constants ORDER = 6 # Controls the order of Sierpinski Triangle LENGTH = 600 # The length of order 1 Sierpinski Triangle UPPER_LEFT_X = 150 # The upper left x coordinate of order 1 Sierpinski Triangle UPPER_LEFT_Y = 100 # The upper left y coordinate of order 1 Sierpinski Triangle WINDOW_WIDTH = 950 # The width of the GWindow WINDOW_HEIGHT = 700 # The height of the GWindow # Global Variable window = GWindow(width=WINDOW_WIDTH, height=WINDOW_HEIGHT) # The canvas to draw Sierpinski Triangle def main(): """ this program shows how to use recursion to draw several levels of sierpinski triangle """ sierpinski_triangle(ORDER, LENGTH, UPPER_LEFT_X, UPPER_LEFT_Y) def sierpinski_triangle(order, length, upper_left_x, upper_left_y): """ :param order: level of triangles :param length: the length of original triangle :param upper_left_x: the initial x-coordination :param upper_left_y: the initial y-coordination :return: Sierpinski Triangle with specific order """ if order == 0: return else: triangle_up = GLine(upper_left_x, upper_left_y, upper_left_x + length, upper_left_y) triangle_left = GLine(upper_left_x, upper_left_y, upper_left_x + length * 0.5, upper_left_y + length * 0.866) triangle_right = GLine(upper_left_x + length, upper_left_y, upper_left_x + length * 0.5, upper_left_y + length * 0.866) window.add(triangle_up) window.add(triangle_left) window.add(triangle_right) # triangle on the left : which has the same left corner as the biggest one sierpinski_triangle(order - 1, length / 2, upper_left_x, upper_left_y) # triangle on the right : which has the left corner on midpoint on the top one sierpinski_triangle(order - 1, length / 2, upper_left_x + length / 2, upper_left_y) # triangle on the bottom : which has the left corner on midpoint on midpoint of left-side line sierpinski_triangle(order - 1, length / 2, upper_left_x + length / 4, upper_left_y + length * 0.866 / 2) # if using the coordination to solve this problem # triangle =GPolygon() # triangle.add_vertex((upper_left_x, upper_left_y)) # triangle.add_vertex((upper_left_x + length,upper_left_y)) # triangle.add_vertex((upper_left_x + length * 0.5,upper_left_y + length * 0.866)) # window.add(triangle) if __name__ == '__main__': main()
5867fe28acdc985097c259ffd9b9832cda10fd30
lyzlovKirill/Geek-pyton
/task6.3.py
1,966
3.546875
4
#Реализовать базовый класс Worker (работник), в котором определить атрибуты: name, surname, position (должность), # income (доход). Последний атрибут должен быть защищенным и ссылаться на словарь, содержащий элементы: оклад и премия, # например, {"wage": wage, "bonus": bonus}. Создать класс Position (должность) на базе класса Worker. # В классе Position реализовать методы получения полного имени сотрудника (get_full_name) и # дохода с учетом премии (get_total_income). Проверить работу примера на реальных данных # (создать экземпляры класса Position, передать данные, проверить значения атрибутов, вызвать методы экземпляров). class Worker: def __init__(self, name, surname, position, wage, bonus): self.name = name self.surname = surname self.position = position self._income = {"wage": int(wage), "bonus": int(bonus)} class Position(Worker): def __init__(self, name, surname, position, wage, bonus): super().__init__(name, surname, position, wage, bonus) def get_full_name(self): return self.name + ' ' + self.surname def get_total_income(self): return self._income["wage"] + self._income["bonus"] name = input("Введите имя ") surname = input("Введите фамилию ") position = input("Введите должность ") wage = input("Введите оклад ") bonus = input("Введите премию ") worker = Position(name, surname, position, wage, bonus) print(worker.get_full_name(), worker.get_total_income())
9c03324049c2f5d2027c0c5458cf8fb4e391aefd
sivasant/python_project
/python/if_statement.py
130
3.9375
4
x=5 y=6 z=7 if x<y: print(x) if x>y: print(x) elif y>z: print(y) elif(y>3): print(y) else: print(z)
80014b9c75b560997e6b54454f3c2bd5091ae516
Kaushik8511/Competitive-Programming
/Graph algos/sudoku.py
694
3.859375
4
row_hash_table = [[0 for i in range(9)]for j in range(9)] col_hash_table = [[0 for i in range(9)]for j in range(9)] sudoku = [[0 for i in range(9)]for j in range(9)] while True: for i in sudoku: for j in i: print(j,end=' ') print() print() row = int(input("enter row : ")) col = int(input("enter col : ")) value = int(input("enter value : ")) if row_hash_table[row-1][value-1]==1: print("you lose") break else: row_hash_table[row-1][value-1]=1 if col_hash_table[value-1][col-1]==1: print("you lose") break else: col_hash_table[value-1][col-1]=1 sudoku[row-1][col-1]=value for i in sudoku: if 0 not in i: print("you win") break
bf931738c47f7598cb298f83b08a6cfdfaea53f3
alexmaclean23/Python-Learning-Track
/12-InputOutput/InputOutput.py
1,559
4.4375
4
# Declaration and opening of a file myFile = open("Python-Learning-Track/12-InputOutput/sampleFile.txt") # Reading the contents of a file as a String myFile.seek(0) print(myFile.read()) print() # Reading the contents of a file as a List myFile.seek(0) print(myFile.readlines()) print() # Closing file at end of use <IMPORTANT> myFile.close() # Using a file temporarily in a function with read permissions with open("Python-Learning-Track/12-InputOutput/sampleFile.txt", mode = "r") as myFile: fileContents = myFile.read() print(fileContents) print() # Using a file temporarily in a function with append permissions with open("Python-Learning-Track/12-InputOutput/sampleFile.txt", mode = "a") as myFile: myFile.write("\nThis is a .txt file.") # Using a file temporarily in a function with read permissions with open("Python-Learning-Track/12-InputOutput/sampleFile.txt", mode = "r") as myFile: fileContents = myFile.read() print(fileContents) print() # Using a file temporarily in a function with write permissions with open("Python-Learning-Track/12-InputOutput/sampleFile.txt", mode = "w") as myFile: myFile.write("This is a .txt file.\nThis is a .txt file.\nThis is a .txt file.") # Using a file temporarily in a function with read permissions with open("Python-Learning-Track/12-InputOutput/sampleFile.txt", mode = "r") as myFile: fileContents = myFile.read() print(fileContents) print() # The mode identifier "r+" allows a file to be read, and then written # The mode identifier "w+" allows a file to be written, and then read
fa0c011c21108bcb437cf2bc82755d23b2f35882
smdaa/project-euler
/p3.py
378
3.625
4
#Largest prime factor #Problem 3 def is_prime(n): for i in range(2, n - 1): if (n % i == 0): return False return True def compute(): n = 600851475143 max = 1 for i in range(2, n - 1): if (is_prime(i) and n % i == 0): if (max < i): max = i return max if __name__ == "__main__": print(compute())
4a1b64e11c3d9459172e80115c8dd31a8df643a6
slavonicsniper/learn-python
/emoji-exercise-1.py
262
3.84375
4
import emoji ## ##message = input(">") ##words = message.split(' ') ##emojis = { ## "smile": ":thumbs_up:", ## "sad": ":water_wave:" ##} ## ##output = "" ##for word in words: ## output += emojis.get(word, word) + " " print(emoji.emojize(':thumbs_up:'))
70ff111ef1bf829eefe56edaa22b58421a3cf4b2
nsilver7/imperva
/imperva.py
2,738
3.625
4
#!/usr/bin/env python import requests from requests.auth import HTTPBasicAuth from getpass import getpass import json import sys def authenticate(session, server): """ This function authenticates a requests.Session object. Parameters ========== session: requests.Session object This is the session instance to authenticate server: str This is the server to connect to. """ url = f"{server}/SecureSphere/api/v1/auth/session" user = input("Enter your username: ") res = session.post(url, auth=HTTPBasicAuth(user, getpass()), verify=False) print(res.json()) # TODO check res code and return bool for login status def delete_session(session_token, server): """ This function deletes an authenticated session token manually. Parameters ========== session_token: str The session token to delete. server: str The server to connect to. """ url = f"{server}/SecureSphere/api/v1/auth/session" res = requests.delete(url, headers=session_token, verify=False) def get_lookup_data_set(session, server, data_set): """ This method returns lookup data set data from SecureSphere Parameters ========== session: requests.Session() object This is the authenticated session context. server: str This is the server to connect to. data_set: str This is the lookup data set we want information on. """ res = session.get(f"{server}/SecureSphere/api/v1/conf/dataSets/{data_set}/data") print(res.json()) def update_lookup_data_set(action, url, session, server): """ This function updates the lookup data set 'ElevatedLoginURLs' with the specified action/URL. Parameters ========== action: str This is either "add" or "delete". url: str The URL that is to be added or deleted. session: requests.Session() Authenticated session context. server: str Server to connect to. """ lookup_url = f"{server}/SecureSphere/api/v1/conf/dataSets/ElevatedLoginURLs/data" proxies = {"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"} headers = {'Content-type': 'application/json'} data = { "action": action, "records": [{"URL": url}] } json_data = json.dumps(data) res = session.put(lookup_url, headers=headers, data=json_data, verify=False, proxies=proxies) j = res.text print(f"update API req responded with: {res.status_code}") # TODO check res code and return bool for update status # return res.json() def main(): server = input("Please enter your server URL:port ~ ") s = requests.Session() authenticate(s, server) # get_lookup_data_set(s, server, "ElevatedLoginURLs") update_lookup_data_set("add", sys.argv[1], s, server) # to delete call update_lookup_data_set("delete", sys.argv[1], s) if __name__ == "__main__": main()
ce5d93e4059ce2fa7fddd386b317560528a3aab9
charliealpha094/Project_Data_Visualization
/Chapter_15_Generating_Data/try_15.6/dice_2D8_visual.py
1,292
3.859375
4
#Done by Carlos Amaral (21/08/2020) #Try 15.6 - Two D8's """ Create a simulation showing what happens when you roll two eight-sided dice 1000 times. Try to picture what you think the visualization will look like before you run the simulation; then see if your intuition was correct. Gradually increase the number of rolls until you start to see the limits of your system’s capabilities. """ from plotly.graph_objs import Bar, Layout from plotly import offline from dice import Die #Create two D8 dices. die_1 = Die(8) die_2 = Die(8) #Make some rolls, and store the results in a list. results = [] for roll_num in range(1000): result = die_1.roll() + die_2.roll() results.append(result) #Analyse the results frequencies = [] max_result = die_1.num_sides + die_2.num_sides for value in range(2, max_result+1): frequency = results.count(value) frequencies.append(frequency) #Visualize the results. x_values = list(range(2, max_result+1)) data = [Bar(x=x_values, y=frequencies)] x_axis_config = {'title': 'Result', 'dtick': 1} y_axis_config = {'title': 'Frequency of Result'} my_layout = Layout(title='Results of rolling two D8 dice 1000 times.', xaxis=x_axis_config, yaxis=y_axis_config) offline.plot({'data': data, 'layout': my_layout}, filename='D8_D8.html')
f118dc06c4fcd3fc1136648adc5f3a39b570cb55
igor376/CoffeeMachine
/Coffee Machine/task/machine/coffee_machine.py
6,965
4.34375
4
# water = int(input("Write how many ml of water the coffee machine has:\n")) // 200 # milk = int(input("Write how many ml of milk the coffee machine has:\n")) // 50 # beans = int(input("Write how many grams of coffee beans the coffee machine has:\n")) // 15 # cups_needed = int(input("Write how many cups of coffee you will need:\n")) # cups_in_machine = min(water, milk, beans) # if cups_needed == cups_in_machine: # print("Yes, I can make that amount of coffee") # elif cups_needed < cups_in_machine: # print("Yes, I can make that amount of coffee (and even", cups_in_machine - cups_needed, "more than that)") # else: # print("No, I can make only", cups_in_machine, "cups of coffee") # [water, milk, coffee beans, cups, price] # name_of_resources = ["water", "milk", "coffee beans", "disposable cups", "price"] # resources = [400, 540, 120, 9, 550] # # [water, milk, coffee beans, cups, price] # coffee = [[250, 0, 16, 1, -4], [350, 75, 20, 1, -7], [200, 100, 12, 1, -6]] # # x = 1 # # # def print_status(): # print("The coffee machine has:") # print(resources[0], "of water") # print(resources[1], "of milk") # print(resources[2], "of coffee beans") # print(resources[3], "of disposable cups") # print(resources[4], "of money") # # # def buy(): # print("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:") # type_of_coffee = input() # if type_of_coffee == "back": # return # cooking_coffee(int(type_of_coffee)) # # # def fill(): # resources[0] += int(input("Write how many ml of water do you want to add:\n")) # resources[1] += int(input("Write how many ml of milk do you want to add:\n")) # resources[2] += int(input("Write how many grams of coffee beans do you want to add:\n")) # resources[3] += int(input("Write how many disposable cups of coffee do you want to add:\n")) # # # def take(): # print("I gave you $" + str(resources[4])) # resources[4] = 0 # # # def cooking_coffee(type_of_coffee): # global resources # if check_resources(type_of_coffee): # for i in range(5): # resources[i] -= coffee[type_of_coffee - 1][i] # # # def check_resources(type_of_coffee): # for i in range(4): # if coffee[type_of_coffee - 1][i] > resources[i]: # print("Sorry, not enough", name_of_resources[i] + "!") # return False # print("I have enough resources, making you a coffee!") # return True # # # def work(): # while True: # options = input("Write action (buy, fill, take, remaining, exit):\n") # print() # if options == "buy": # buy() # elif options == "fill": # fill() # elif options == "take": # take() # elif options == "remaining": # print_status() # elif options == exit(): # break # print() # # # # work() class CoffeeMachine: # [water, milk, coffee beans, cups, price] name_of_resources = ["water", "milk", "coffee beans", "disposable cups", "price"] # [water, milk, coffee beans, cups, price] coffee = [[250, 0, 16, 1, -4], [350, 75, 20, 1, -7], [200, 100, 12, 1, -6]] def __init__(self): self.state_of_machine = 0 self.resources = [400, 540, 120, 9, 550] self.print_message() def work(self, command): if command == "buy" or self.state_of_machine == 1: self.buy(command) return True elif command == "fill" or self.state_of_machine >= 20: self.fill(command) return True elif command == "take": print() self.take() return True elif command == "remaining": print() self.state_of_machine = 4 self.print_message() self.state_of_machine = 0 self.print_message() return True elif command == "exit": return False def print_message(self): # 0 - main menu, 1 - buy, 2 - fill, 3 - take, 4 - remaining, 5 - exit if self.state_of_machine == 0: print("Write action (buy, fill, take, remaining, exit):") elif self.state_of_machine == 1: print("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:") elif self.state_of_machine == 4: print("The coffee machine has:") print(self.resources[0], "of water") print(self.resources[1], "of milk") print(self.resources[2], "of coffee beans") print(self.resources[3], "of disposable cups") print("${} of money\n".format(self.resources[4])) def buy(self, type_of_coffee): if self.state_of_machine == 0: print() self.state_of_machine = 1 self.print_message() return if type_of_coffee == "back": self.state_of_machine = 0 print() self.print_message() return self.cooking_coffee(int(type_of_coffee)) self.state_of_machine = 0 def cooking_coffee(self, type_of_coffee): if self.check_resources(type_of_coffee): for i in range(5): self.resources[i] -= self.coffee[type_of_coffee - 1][i] self.state_of_machine = 0 self.print_message() def check_resources(self, type_of_coffee): for i in range(4): if self.coffee[type_of_coffee - 1][i] > self.resources[i]: print("Sorry, not enough {}!\n".format(self.name_of_resources[i])) return False print("I have enough resources, making you a coffee!\n") return True def take(self): print("I gave you {}$\n".format(str(self.resources[4]))) self.resources[4] = 0 self.state_of_machine = 0 self.print_message() def fill(self, command): if self.state_of_machine == 0: print() self.state_of_machine = 21 print("Write how many ml of water do you want to add:") elif self.state_of_machine == 21: self.resources[0] += int(command) self.state_of_machine = 22 print("Write how many ml of milk do you want to add:") elif self.state_of_machine == 22: self.resources[1] += int(command) self.state_of_machine = 23 print("Write how many grams of coffee beans do you want to add:") elif self.state_of_machine == 23: self.resources[2] += int(command) self.state_of_machine = 24 print("Write how many disposable cups of coffee do you want to add:") elif self.state_of_machine == 24: self.resources[3] += int(command) self.state_of_machine = 0 print() self.print_message() machine = CoffeeMachine() while machine.work(input()): pass
958145730877de8fb1af8562ef9c1595ea006553
Baasant/DATA-STRUCTURES-AND-ALGORITHMS-SPECIALIZATION
/Tool box/week3/maximum_salary.py
970
3.96875
4
# python3 from itertools import permutations def largest_number_naive(numbers): numbers = list(map(str, numbers)) largest = 0 for permutation in permutations(numbers): largest = max(largest, int("".join(permutation))) return largest def is_greater(digit, max_digit): return digit + max_digit > max_digit + digit def largest_number(numbers): test_list=numbers res = int(max((''.join(i) for i in permutations(str(i) for i in test_list)), key = int)) return res ''''' #numbers=[21,2] str_num = [str(number) for number in numbers] a_string = "".join(str_num) #print(a_string-2) m=[int(i) for i in a_string ] #print(m) m.sort(reverse=True) #print(m) x = int("".join(map(str, m))) return x ''''' if __name__ == '__main__': n = int(input()) input_numbers = input().split() assert len(input_numbers) == n print(largest_number(input_numbers))
25be9c5ee03f3d3d88f60e903f69607a29085292
jermynyeo/Advent-Of-Code
/adventofcode2.py
712
3.625
4
with open('adventofcode2_input.txt','r') as file: number_three = 0 number_two =0 for lines in file: lines = lines.rstrip("\n") #checking char char_dict = {} for ch in lines: if ch not in char_dict: char_dict[ch] = 1 else: char_dict[ch] += 1 appear_three = 0 appear_two = 0 for key in char_dict: if char_dict[key] == 2: appear_two += 1 elif char_dict[key] == 3: appear_three += 1 if appear_three > 0 : number_three += 1 if appear_two > 0: number_two += 1 print(number_three * number_two)
be484e2e6449a281bc0a61cffe807f5cd4c6769a
Vanditg/Leetcode
/Single_Number_II/EfficientSolution.py
774
3.78125
4
##================================== ## Leetcode ## Student: Vandit Jyotindra Gajjar ## Year: 2020 ## Problem: 137 ## Problem Name: Single Number II ##=================================== #Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. # #Note: # #Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? # #Example 1: # #Input: [2,2,3,2] #Output: 3 # #Example 2: # #Input: [0,1,0,1,0,1,99] #Output: 99 import collections as c #Importing collections module class Solution: def singleNumber(self, nums): return "".join(map(str, [item for item, count in c.Counter(nums) if count == 1])) #Returning element that appears exactly one times.
5d4b36f2004d2c6f34513c86681fa4468ef155bb
liu666197/data1
/8.17/08 对象的嵌套.py
992
3.78125
4
# 5.模拟英雄联盟中的游戏人物的类: # 要求: # a.创建Role(角色)类 # b.初始化方法中给对象封装 name,ad(攻击力),hp(血量)三个属性 # c.创建一个attack方法,此方法是实例化的两个对象,互相攻击的功能 # 例: # 实例化一个Role对象,盖伦,ad为10,hp为100 # 实例化另一个Role对象,亚索,ad为20,hp为80 # attack方法要完成: '谁攻击谁,谁掉了多少血,还剩多少血的提示功能' class Role: def __init__(self,name,ad,hp): self.name = name self.ad = ad self.hp = hp def attack(self,a): # 剩余血量 a.hp -= self.ad print('{}攻击了{},{}掉了{}的血,还剩下{}血!!'.format(self.name,a.name,a.name,self.ad,a.hp)) gailun = Role('盖伦',10,100) yasuo = Role('亚索',20,80) # 盖伦调用attack方法: 由盖伦攻击其他对象 gailun.attack(yasuo) gailun.attack(yasuo) gailun.attack(yasuo) gailun.attack(yasuo) yasuo.attack(gailun)
148e2c2cf65ee27984d3f19ff63bfc461e0d13d5
radiocrew/test_part_2
/two_stack_one_que.py
1,019
3.875
4
#https://www.youtube.com/watch?v=t45d7CgDaDM class Node: def __init__(self, data): self.data = data self.next = None pass def next(self): return self.next def next(self, data): self.data = data class Stack: def __init__(self): self.top = None pass def push(self, data): new_node = Node(data) if None == self.top: self.top = new_node new_node.next = None else: new_node.next = self.top self.top = new_node pass def pop(self): if None == self.top: return if None != self.top.next: self.top = self.top.next return self.top = None pass def peek(self): return self.top.data def is_empty(self): if None == self.top: return True return False stack = Stack()