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
9a9f0d284905b3a59f88d8d88e960b8a0d64adc5
balocik/Simple-Python-Games
/Pet.py
2,023
4.125
4
#--------------------------- # 12/10/2017 # created by Wojciech Kuczer #--------------------------- class Pet(object): """virtual pet""" def __init__(self,name, hunger = 0, boredom =0): self.name = name self.hunger = hunger self.boredom = boredom def __pass_time(self): self.hunger += 1 self.boredom += 1 @property def mood(self): unhappines = self.hunger + self.boredom if unhappines < 5: m = "very happy" elif 5 <= unhappines <= 10: m = "happy" elif 10 <= unhappines <=15: m = "sad" else: m = "angry" return m def talk(self): print("My name is {} and I'm {} now".format(self.name, self.mood)) self.__pass_time() def eat(self, food = 4): print("Yum yum. Thank You") self.hunger -= food if self.hunger < 0: self.hunger = 0 print("\nI'm {} now".format(self.mood)) self.__pass_time() def play(self, fun = 4): print("Yuupee!!!") self.boredom -= fun if self.boredom < 0: self.boredom = 0 print("\nI'm {} now".format(self.mood)) self.__pass_time() def main(): crit_name = input("Enter Your pets name: ") crit = Pet(crit_name) choice = None while choice != "0": print( """ You are a pet owner. What would you like to do with You pet: 0 - Quit game 1 - listen Your pet 2 - feed Your pet 3 - play with Your pet """ ) choice = input("Choose an option: ") if choice == "0": print("Good bye") elif choice == "1": crit.talk() elif choice == "2": crit.eat() elif choice == "3": crit.play() else: print("Soory but Your selection is not correct") main() print("Thanks for playing")
14239b7ebfe8443561adb26054827fee9cea0268
joebigjoe/Hadoop
/Spark快速大数据分析/第 3 章 RDD 编程/Python OOP Basic/classTest8.py
389
3.90625
4
class User: def __init__(self, name, email, gender): self.name = name self.email = email self.gender = gender # this is like the toString() method of C# def __repr__(self): return self.name + " " + self.gender + " " + self.email joey = User("Joey", "412371201@163.com", "Male") print(joey) aria = User("Aria", "aria@pretty.com", "Female") print(str(aria))
6d7f2d6cdeded267a654d962ce7fcb50fde1be62
ishritam/python-Programming--The-hard-way-Exercises
/ex21.py
749
3.828125
4
def add(a,b): return a + b def sub(a,b): return a - b def mult(a,b): return a * b def div(a,b): return a / b addition = add(10, 10) substract= sub(10,10) multiplication = mult(10, 10) division = div(10,10) puzzel = add(addition,sub(substract,mult(multiplication,div(division,1)))) #puzzel = add(add(10,10),sub(sub(10,10),mult(mult(10, 10),div(div(10,10),1)))) #puzzel = add(add(10,10),sub(sub(10,10),mult(mult(10, 10),div(1,1)))) #puzzel = add(add(10,10),sub(sub(10,10),mult(mult(10, 10),1))) #puzzel = add(add(10,10),sub(sub(10,10),mult(mult(100,1)))) #puzzel = add(add(10,10),sub(sub(10,10),100)) #puzzel = add(add(10,10),sub(0,100)) #puzzel = add(add(10,10),-100)) #puzzel = add(20,-100) #puzzel = -80 print(f"{puzzel}") print("\a")
a64d8d6ee3f15bf1c0a5c58b34073103a16eeb0b
hooyao/Coding-Py3
/LeetCode/Problems/36_valid_sudoku.py
2,757
3.578125
4
import sys class Solution: def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ if len(board) != 9 or len(board[0]) != 9: raise Exception() # test block for i in range(3): for j in range(3): block = [row[j * 3:j * 3 + 3] for row in board[i * 3:i * 3 + 3]] if not self.test_block(block): return False # test row for i in range(9): row = board[i] if not self.test_arr(row): return False # test col for i in range(9): col = [row[i] for row in board] if not self.test_arr(col): return False return True def test_block(self, block): if len(block) != 3 or len(block[0]) != 3: raise Exception() stats = [0] * 10 for i in range(3): for j in range(3): if block[i][j] != ".": val = int(block[i][j]) if stats[val] > 0: return False else: stats[val] = 1 return True def test_arr(self, arr): if len(arr) != 9: raise Exception() stats = [0] * 10 for i in range(9): if arr[i] != ".": val = int(arr[i]) if stats[val] > 0: return False else: stats[val] = 1 return True def main(*args): mat1 = [ ["8", "3", ".", ".", "7", ".", ".", ".", "."], ["6", ".", ".", "1", "9", "5", ".", ".", "."], [".", "9", "8", ".", ".", ".", ".", "6", "."], ["8", ".", ".", ".", "6", ".", ".", ".", "3"], ["4", ".", ".", "8", ".", "3", ".", ".", "1"], ["7", ".", ".", ".", "2", ".", ".", ".", "6"], [".", "6", ".", ".", ".", ".", "2", "8", "."], [".", ".", ".", "4", "1", "9", ".", ".", "5"], [".", ".", ".", ".", "8", ".", ".", "7", "9"] ] mat2 = [ ["5", "3", ".", ".", "7", ".", ".", ".", "."], ["6", ".", ".", "1", "9", "5", ".", ".", "."], [".", "9", "8", ".", ".", ".", ".", "6", "."], ["8", ".", ".", ".", "6", ".", ".", ".", "3"], ["4", ".", ".", "8", ".", "3", ".", ".", "1"], ["7", ".", ".", ".", "2", ".", ".", ".", "6"], [".", "6", ".", ".", ".", ".", "2", "8", "."], [".", ".", ".", "4", "1", "9", ".", ".", "5"], [".", ".", ".", ".", "8", ".", ".", "7", "9"] ] solution = Solution() result = solution.isValidSudoku(mat2) print(result) if __name__ == '__main__': main(*sys.argv[1:])
cf7eae842bbbb7aa0f95204b291f06cea21e74a5
isongjosiah/team_pasteur
/Priyanka.py
701
3.59375
4
#!/usr/bin/python3 name = 'Priyanka Pandit' email = 'priyupandit99@gmail.com' slack_username = '@PriyankaPandit' biostack = 'Drug Development' twitter_handle = '@PiiiyuuuPandit' def h_d(string1, string2): # Start with a distance of zero, and count up distance = 0 # Loop over the indices of the string L = len(string1) for i in range(L): # Add 1 to the distance if these two characters are not equal if string1[i] != string2[i]: distance += 1 # Return the final count of differences return distance hamming_distance = h_d(slack_username, twitter_handle) print(name, email ,slack_username, biostack, twitter_handle, hamming_distance, sep=",")
24ebea06a0190a4d771d02761924be048062e6aa
andart7777/haudiho1
/temp.py
1,616
3.78125
4
file = open("newfile.txt", "a") file.write("Всего с наценкой: " + str(c) + "р" + " --- " + "Прибыль с одной штуки: " + str(w) + "р" + "\n") file.write("Итого за все: " + str(f) + "р" + " --- " + "Прибыль за все :" + ee + "р") file.close() # def mem_add(): # # file = open("newfile.txt", "a") # file.write("Всего с наценкой: " + str(c) + "р" + " --- " + "Прибыль с одной штуки: " + str(w) + "р" + "\n") # file.write("Итого за все: " + str(f) + "р" + " --- " + "Прибыль за все :" + ee + "р") # file.close() # # # # while True: # a = float(input("Введите первое число:")) # b = float(input("Введите второе число:")) # what_do = c = a / 100 * b + a # # Прибыль за штуку # w = a / 100 * b # print("Всего с наценкой: " + str(c) + "р" + " --- " + "Прибыль с одной штуки: " + str(w) + "р") # d = float(input("Введите количество продукции: ")) # # Сумма общая на все количество товара # f = c * d # # Прибыль общая на все количество товара # e = w * d # ee = format(e, '.2f') # # print("Итого за все: " + str(f) + "р" + " --- " + "Прибыль за все :" + ee + "р") # #print("Итого за все: " + str(mem_1[0]) + "р" + " --- " + "Прибыль за все :" + str(mem_1[1]) + "р") # #print(len(mem_1)) # # mem_add() # #
f3c4cc748d2b054371102414efa7df108fb357df
ineed-coffee/PS_source_code
/HackerRank/Non-Divisible Subset(Medium).py
917
3.8125
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'nonDivisibleSubset' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER k # 2. INTEGER_ARRAY s # def nonDivisibleSubset(k, s): s_dict={i:0 for i in range(k+1)} for num in s: s_dict[num%k]+=1 ret=0 for i in range(k//2+1): if s_dict[i] and ((i*2==k) or (i==0)): ret+=1 continue ret+=max(s_dict[i],s_dict[k-i]) return ret if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') first_multiple_input = input().rstrip().split() n = int(first_multiple_input[0]) k = int(first_multiple_input[1]) s = list(map(int, input().rstrip().split())) result = nonDivisibleSubset(k, s) fptr.write(str(result) + '\n') fptr.close()
3cf1c86b6856d708be97e25d4541adfd49c9eb79
odlt98/css301
/m3problem3.py
444
3.8125
4
#Omar De La Torre #4/23/2019 import turtle def tree(branchLen,t): if branchLen>5: t.forward(branchLen) t.right(20) tree(branchLen-15,t) t.left(40) tree(branchLen-15,t) t.right(20) t.backward(branchLen) def main(): t=turtle.Turtle() myWin=turtle.Screen() t.left(90) t.up() t.backward(100) t.down() t.color("green") tree(75,t) main()
00ad3e568e039e773e86ff9c28f18bb309221c1e
macluiggy/Python-Crash-Course-2nd-edition-Chapter-1-11-solutions
/CHAPTER 10/10-10. Common Words.py
401
4.15625
4
# Choice a file and show how many times a specific word appears # in the file. filename = 'potions.txt' try: with open(filename, encoding='utf-8') as f: contents = f.read() except UnicodeDecodeError: pass except FileNotFoundError: print(f"Sorry, I couldn't find that file") else: word_count = contents.lower().count('the') print(f"The file {filename} has about {word_count} the word 'the'")
fa44fe7023bddf235ae9ad8beea6e2074d206148
mfbalder/Skills1
/test_skills1.py
1,724
3.515625
4
import unittest from skills1 import * class TestSkills(unittest.TestCase): def setUp(self): self.words = ["hello", "my", "name", "is", "Michaela", "and", "I", "am", "a", "lady"] self.numbers = [1, 2, 7, 12, 15, -2, 3, -17, 100, -2] def test_1_A_all_odd(self): self.assertEqual(all_odd(self.numbers), [1, 7, 15, 3, -17]) def test_1_B_all_even(self): self.assertEqual(all_even(self.numbers), [2, 12, -2, 100, -2]) def test_1_C_long_words(self): self.assertEqual(long_words(self.words), ["hello", "name", "Michaela", "lady"]) def test_1_D_smallest(self): self.assertEqual(smallest(self.numbers), -17) def test_1_E_largest(self): self.assertEqual(largest(self.numbers), 100) def test_1_F_halvesies(self): self.assertEqual(halvesies(self.numbers), [.5, 1, 3.5, 6, 7.5, -1, 1.5, -8.5, 50, -1]) def test_1_G_word_lengths(self): self.assertEqual(word_lengths(self.words), [5, 2, 4, 2, 8, 3, 1, 2, 1, 4]) def test_1_H_sum_numbers(self): self.assertEqual(sum_numbers(self.numbers), 119) def test_1_I_mult_numbers(self): self.assertEqual(mult_numbers(self.numbers), -51408000) def test_1_J_join_strings(self): self.assertEqual(join_strings(self.words), "hellomynameisMichaelaandIamalady") def test_1_K_average(self): self.assertEqual(average(self.numbers), 11.9) def test_1_L_custom_map(self): self.assertEqual(custom_map(lambda x: x * 2, self.numbers), [2, 4, 14, 24, 30, -4, 6, -34, 200, -4]) def test_1_M_custom_filter(self): self.assertEqual(custom_filter(lambda x: x % 2 == 0, self.numbers), [2, 12, -2, 100, -2]) def test_1_N_custom_reduce(self): self.assertEqual(custom_reduce(lambda x, y: x + y, self.numbers), 119) if __name__ == '__main__': unittest.main()
13196f8d1bcfc7400b54a0217710214e21d68642
sakir66/Python_Kitap
/BOLUM_10/KTP_Uygulama10_2.py
254
3.625
4
#!C:\Python38\python.exe yas=input('Yaşınızı Giriniz: ') try: yas=int(yas) print("Üç yıl sonra %d yaşında olacaksınız" % (yas+3)) except: print('Sayı değer girseydiniz üç yıl sonra hangi yaşta olacağınızı söyleyecektim')
3a227a09c89cf391655b574bdccda1ef77a44912
DiogoCastro/prototype_get_data
/app.py
1,665
3.53125
4
#!/usr/bin/env python """Allows to dynamically manipulate a file in a given link and stores its content in a formatted way.""" from flask import Flask, jsonify import io import requests import pandas as pd import ast app = Flask(__name__) @app.route('/get-all-data') def get_data_csv(): """Get data from a specific file in a given URL, read in memory and pass data converted to JSON.""" url = 'http://falconi-test.coupahost.com/api/attachments/2416' headers = {'X-COUPA-API-KEY': '5f9aa3ecacae35a33305ee036e178194e402bf21', 'Accept': 'application/json'} r = requests.get(url, headers=headers) decoded_file = r.content.decode('utf-8') col_list = ["id"] df = pd.read_csv(io.StringIO(decoded_file), usecols=col_list) df_json_string = df.to_json(orient='records') df_json = ast.literal_eval(df_json_string) print(df_json) print(type(df_json)) return jsonify(df_json) @app.route('/send-json', methods=['POST']) def send_json(json_data): """Send data from a Json specified by user, read in memory and pass data converted to JSON.""" # url = 'http://falconi-test.coupahost.com/api/attachments/2416' # headers = {'X-COUPA-API-KEY': '5f9aa3ecacae35a33305ee036e178194e402bf21', 'Accept': 'application/json'} # r = requests.get(url, headers=headers) # decoded_file = r.content.decode('utf-8') # col_list = ["id"] # df = pd.read_csv(io.StringIO(decoded_file), usecols=col_list) # df_json_string = df.to_json(orient='records') # df_json = ast.literal_eval(df_json_string) # print(df_json) # print(type(df_json)) return jsonify(json_data) if __name__ == '__main__': port = int(os.getenv("PORT", 8080)) app.run(host='0.0.0.0', port=port)
b12a4228ef2950a524f1b7754f7fff6d77f772a2
VishalJoshi21/Python_Program
/prg8.py
201
4.125
4
num=int(input("Enter number :")); no=num; res=0; while num>0: temp=num%10; res=(res*10)+temp; num=int(num/10); if(no==res): print("Number is Palindrome"); else: print("Number is not Palindrome");
159bec87265ee9c3ffa81efa3e4656c2873c2b40
keg51051/PythonProjects
/PythonProject/A4THU-Week11.py
680
4.28125
4
# Dictionaries Countries = {"CA": "Canada", "US": "United States", "UK": "United Kingdom", "MX": "Mexico"} # Prompt user to enter a country code # if the country_code is exist # remove it, otherwise display error key = input("Enter a country code: ") if Countries.get(key): Countries.pop(key) else: print("Country not found to remove") print(Countries) # country = input("Enter a country code: ") # for key, value in Countries.items(): # if key == country: # Countries.pop(key) # print(value + " is removed") # print(Countries) # break # else: # print("Country not found to remove")
664a65d139256d64fca2a97d4c30c86c691a4534
404-sdok/python-application
/kpjhg0124/app.py
516
3.53125
4
account = { 'naver' : { 'id' : 'kpjhg0124', 'pw' : 'hello' }, 'facebook' : { 'id' : 'me@ho9.me', 'pw' : 'facebook_password' } } while(1): # 계속 반복 print('naver, facebook?', end = '') # 질문 result = input() # result 변수에 질문 답변 저장 if result in ['naver', 'facebook']: # 만약 질문 답변이 naver이거나 facebook이라면 print('{} 아이디: {}, 비밀번호 : {}'.format(result, account[result]['id'], account[result]['pw']))
0f43cc9e80b8ed4b15fd0f30571c9629a3b17b53
wilsonify/euler
/src/euler_python_package/euler_python/easiest/p007.py
805
3.828125
4
import itertools from euler_python.utils import eulerlib def problem007(): """ Computers are fast, so we can implement this solution by testing each number individually for primeness, instead of using the more efficient sieve of Eratosthenes. The algorithm starts with an infinite stream of incrementing integers starting at 2, filters them to keep only the prime numbers, drops the first 10000 items, and finally returns the first item thereafter. 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 10001st prime number? """ ans = next( itertools.islice(filter(eulerlib.is_prime, itertools.count(2)), 10000, None) ) return ans if __name__ == "__main__": print(problem007())
40cc1f5613666a47c4c55edd2cc66d15b16f340e
pratikv06/python-tkinter
/Radio2.py
719
3.828125
4
from tkinter import * root = Tk() root.title("Radio") def clicked(value): result = Label(frame, text=value) result.pack() # Radiobutton(root, text='Option 1', variable=r, value=1).pack() # Radiobutton(root, text='Option 2', variable=r, value=2).pack() TOPPINGS = [ ("Pepperoni", "Pepperoni"), ("Cheese", "Cheese"), ("Mushroom", "Mushroom"), ("Onion", "Onion"), ] pizza = StringVar() pizza.set('None') for txt, val in TOPPINGS: Radiobutton(root, text=txt, variable=pizza, value=val).pack(anchor=W) btn = Button(root, text="Click Me!", command=lambda: clicked(pizza.get())) btn.pack() frame = LabelFrame(root, padx=10, pady=5) frame.pack() root.mainloop()
a78ad9053d51f535cd1f65fc5d4dc167b32d8b0b
mridhosaputraad/DocumentationPython
/p9. while loop/latihan2.py
588
3.609375
4
# Contoh 3 : else, continue, pass angka = 0 while angka < 10: if angka == 5: # print('checkpoint 1') # break # jadi akan langsung keluar dari looping # Solusinya # angka += 1 # continue # Dia tidak error, tapi akan stack di angka 5 jadinya posisinya infinite loop pass print('nilai angka adalah', angka) angka += 1 else: # Fungsinya nengecek status bahwa while sudah beres print('nilai angka diakhir while adalah', angka) # angka terakhir ini bisa kita catch dengan else print('di luar while')
8ac1fdb4fa0da1ba5ecbfa48dd2816ec8fe79e76
yangdissy/TDClass01
/Lesson-3-初步认识Python/homework/01002-杨帅/Guess the number you entered.py
184
3.765625
4
import random a = int(raw_input("Please enter a number(0-100):")) b = random.randint(0,100) while b != a: if b > a: b -= 1 else: b += 1 print "Thenumber you entered is:%d" % b
6120845bd8b12fbf5b4f0de25f26c9dfd7d7d89e
ferryleaf/GitPythonPrgms
/numbers/total_count_of_number_with_even_number_of_digits.py
1,244
4.40625
4
''' Given an array nums of integers, return how many of them contain an even number of digits. Example 1: Input: nums = [12,345,2,6,7896] Output: 2 Explanation: 12 contains 2 digits (even number of digits). 345 contains 3 digits (odd number of digits). 2 contains 1 digit (odd number of digits). 6 contains 1 digit (odd number of digits). 7896 contains 4 digits (even number of digits). Therefore only 12 and 7896 contain an even number of digits. Example 2: Input: nums = [555,901,482,1771] Output: 1 Explanation: Only 1771 contains an even number of digits. Constraints: 1 <= nums.length <= 500 1 <= nums[i] <= 10^5 ''' from typing import List import math class Solution: def findNumbers(self, nums: List[int]) -> int: count=0 if (len(nums)>=1 and len(nums)<=500): for num in nums: if (num>=1 and num<=int(math.pow(10,5))) : leng = len(str(num)) if (leng>=1 and leng<=500 and leng%2==0): count=count + 1 return count def main(): sol = Solution() nums = [12,345,2,6,7896] print(sol.findNumbers(nums)) nums = [555,901,482,1771] print(sol.findNumbers(nums)) if __name__ == '__main__': main()
4614af1dd882e7d0cbb96c764f990a96509e88a4
eblade/articulate
/articulate/scope.py
3,204
3.609375
4
""" A scope is a local set of variables and functions. """ from .parser import Pattern class Scope(dict): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.functions = {} self.return_value = None self.returning = False self._exposed = [] def define(self, define): function = Function(define) self.functions[define] = function function.functions = self.functions.copy() return function def define_python(self, python_thing): if hasattr(python_thing, '__init__'): self.define_python_class(python_thing) else: self.define_python_function(python_thing) def define_python_function(self, function): python_function = PythonFunction(function) self.functions[python_function.pattern] = python_function return python_function def define_python_class(self, klass): python_class = PythonClass(klass) self.functions[python_class.pattern] = python_class return python_class def copy(self): scope = Scope(self) scope.functions = self.functions.copy() return scope @property def exposed(self): return {k: v for k, v in self.items() if k in self._exposed} def expose(self, name): self._exposed.append(name.strip()) class Function(Pattern): def __init__(self, pattern): super().__init__(pattern, 'function') self.instructions = [] self.functions = {} class PythonFunction(Pattern): def __init__(self, python_function): super().__init__(python_function.__pattern__, 'python-function') self.python_function = python_function self.varnames = python_function.__code__.co_varnames[:python_function.__code__.co_argcount] def run(self, scope): arguments = [scope[argument] for argument in self.varnames] return self.python_method(*arguments) class PythonMethod(Pattern): def __init__(self, python_method): super().__init__(python_method.__pattern__, 'python-method') self.python_method = python_method self.varnames = python_method.__code__.co_varnames[:python_method.__code__.co_argcount] def run(self, scope): arguments = [scope[argument] for argument in self.varnames] return self.python_method(*arguments) class PythonClass(Pattern): def __init__(self, python_class): super().__init__(python_class.__pattern__, 'python') self.python_class = python_class self.varnames = python_class.__init__.__code__.co_varnames[:python_class.__init__.__code__.co_argcount] # Import all defined methods self.functions = {} for name in dir(python_class): if name.startswith('_'): continue obj = getattr(python_class, name) if not hasattr(obj, '__pattern__'): continue self.functions[obj.__pattern__] = PythonMethod(obj) def run(self, scope): arguments = [scope[argument] for argument in self.varnames if argument != 'self'] return self.python_class(*arguments)
75e6bc4ce6edea44ba79ff9815d45d04052a9d88
changeworld/nlp100
/python/01/09.py
1,054
3.890625
4
# -*- coding: utf-8 -*- # 09. Typoglycemia # スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.ただし,長さが4以下の単語は並び替えないこととする.適当な英語の文(例えば"I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind .")を与え,その実行結果を確認せよ. import random def typoglycemia(str): typoglycemia_list = [] for word in str.split(): if len(word) < 4: pass else: char_list = list(word) mid_str = char_list[1:-1] random.shuffle(mid_str) word = word[0] + "".join(mid_str) + word[-1] typoglycemia_list.append(word) return " ".join(typoglycemia_list) print(typoglycemia("I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."))
f037a2b79c4a555e17e6c03c6a994ab40e89894c
Homap/data_science
/09.07.2019/python_problemSolve/fasta_to_dict.py
574
3.796875
4
#!/usr/bin/python import sys #******************************** # Written by Homa Papoli # Version 1. 16 July 2019 #******************************** # Exercise 2: Store the fasta file into a dictionary. #******************************** # Run: python fasta_to_dict.py fasta_exercise_goodheader.fa #******************************** fasta_file = open(sys.argv[1], "r") fasta_dict = {} for line in fasta_file: line = line.strip("\n") #print(line) if line.startswith(">"): key = line.replace(">", "") else: fasta_dict[key] = value print(fasta_dict) fasta_file.close()
c657579877af6e139f66d620cb1c210db091c520
chriszimmerman/python_month
/sudoku/square.py
432
3.640625
4
class Square(object): def __init__(self, number, row, column, block): self.number = number self.row = row self.column = column self.block = block def __eq__(self, other): return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__) def __hash__(self): return int(str(self.number) + str(self.row) + str(self.column) + str(self.block))
87d0f2ebb59cd41510cb9f2a863077c1c758aeef
MikkelPaulson/advent-of-code-2020
/day23/__init__.py
2,685
4.03125
4
"""https://adventofcode.com/2020/day/23""" import io def part1(stdin: io.TextIOWrapper, stderr: io.TextIOWrapper) -> int: """ Using your labeling, simulate 100 moves. What are the labels on the cups after cup 1? """ cups = parse(stdin) play(cups, 100) stderr.write(f"End of game: {cups}\n") output = cups[cups.index(1) + 1:] + cups[:cups.index(1)] return sum(map( lambda cup: cup[1] * pow(10, cup[0]), enumerate(reversed(output)) )) def part2(stdin: io.TextIOWrapper, stderr: io.TextIOWrapper) -> int: """ Determine which two cups will end up immediately clockwise of cup 1. What do you get if you multiply their labels together? """ cups = parse(stdin) cups += range(len(cups) + 1, 1000001) play(cups, 10000000) next_cups = [cups[cups.index(1) + i] % len(cups) for i in [1, 2]] stderr.write(f"{next_cups[0]} * {next_cups[1]} = " f"{next_cups[0] * next_cups[1]}\n") return next_cups[0] * next_cups[1] def play(cups: list, rounds: int): """ Play the game for a specified number of rounds. Modifies cups in place. """ def play_round(edges: dict, current_cup: int) -> int: """ Play a round of the cup game. Returns the new current cup. """ max_cup = len(edges) cups_in_hand = [edges[current_cup]] while len(cups_in_hand) < 3: cups_in_hand.append(edges.pop(cups_in_hand[-1])) edges[current_cup] = edges.pop(cups_in_hand[-1]) destination_cup = current_cup - 1 if current_cup != 1 else max_cup while destination_cup in cups_in_hand: destination_cup -= 1 if destination_cup < 1: destination_cup = max_cup while cups_in_hand: edges[cups_in_hand[-1]] = edges[destination_cup] edges[destination_cup] = cups_in_hand.pop() return edges[current_cup] def cups_to_edges(cups: list) -> dict: edges = {cups[i]: cups[i + 1] for i in range(len(cups) - 1)} edges[cups[-1]] = cups[0] return edges def edges_to_cups(edges: dict) -> list: cups = [1] index = edges[1] while index != 1: cups.append(index) index = edges[index] return cups current_cup = cups[0] edges = cups_to_edges(cups) for _ in range(rounds): current_cup = play_round(edges, current_cup) cups[:] = edges_to_cups(edges) def parse(stdin: io.TextIOWrapper) -> list: """ Parse the input into a list of ints representing the order of the cups. """ return [int(c) for c in stdin.read().strip()]
f45523f038a67ca782530a15ad1532392dc55ee7
nicocavalcanti/processing_py
/Food.py
1,105
3.875
4
# The "Food" class class Food(): def __init__(self, x, y, vel): self.acceleration = PVector(0, 0) self.velocity = vel self.position = PVector(x, y) self.r = 12 self.color = color(127) # Method to update food location def update(self, x, y): newPos = PVector(x,y) self.position = newPos c = color (random(255), random(255), random(255)) self.color = c def applyForce(self, force): # We could add mass here if we want A = F / M self.acceleration.add(force) def display(self): # Draw a triangle rotated in the direction of velocity theta = self.velocity.heading()# + PI / 2 fill(self.color) noStroke() strokeWeight(1) with pushMatrix(): translate(self.position.x, self.position.y) rotate(theta) rect(0, 0, self.r, self.r) # beginShape() # vertex(0, -self.r * 2) # vertex(-self.r, self.r * 2) # vertex(self.r, self.r * 2) # endShape(CLOSE)
3846fa8ac28f483ce33f86978ce318aaa1da2eed
zulhaziq86/GroupProject_client
/modify2.py
1,810
3.546875
4
import socket import math ClientSocket = socket.socket() host = '192.168.0.161' port = 8888 print('Waiting for connection') try: ClientSocket.connect((host, port)) print('Connected!!') except socket.error as ex: print(str(ex)) Response = ClientSocket.recv(1024).decode() print(Response) while True: print (' NL - Nasi Lemak \n S - Sate \n NA - Nasi Ayam \n Q - Quit') table = input('\nEnter table number : ') Input = input('\nOrder your food : ') if Input == 'NL' : option = "NL" table = table quantity = input('Quantity : ') quantity = int(quantity) totprice = 5*quantity l = option + '.' + str(table) + '.' + str(quantity) + '.' + str(totprice) ClientSocket.send(str.encode(l)) elif Input == 'S': option = "S" table = table quantity = input('Quantity : ') quantity = int(quantity) totprice = 1*quantity s = option + '.' + str(table) + '.' + str(quantity) + '.' + str(totprice) ClientSocket.send(str.encode(s)) elif Input == 'NA': option = "NA" table = table quantity = input('Quantity : ') quantity = int(quantity) totprice = 6*quantity e = option + '.' + str(table) + '.' + str(quantity) + '.' + str(totprice) ClientSocket.send(str.encode(e)) elif Input == "Q": option = "Q" table = "0" quantity = "0" totprice = "0" f = option + '.' + str(table) + '.' + str(quantity) + '.' + str(totprice) ClientSocket.send(str.encode(f)) print ('Goodbye!! \n') ClientSocket.close() else : print ('Invalid funtion! Try Again \n') Response = ClientSocket.recv(1024) print(Response.decode()) ClientSocket.close()
0730a9c43c7717baf032a183f288739bd0bd4a1b
poojasingh1995/MOREEXERCISE
/ques_4.py
379
4.21875
4
# num1=int(input("enter the num")) # num2=int(input("enter the num")) # num3=int(input("enter the num")) # if num1>num2>num3 or num3>num2>num1: # print(num2,"second greatest num") # elif num2>num1>num3 or num3>num1>num2: # print(num1,"second gretest num") # elif num2>num3>num1 or num1>num3>num2: # print(num3,"second gretest num") # else: # print("not greater")
b5f13df49f0c56e009e764fa55863c598c52c3c4
AdamZhouSE/pythonHomework
/Code/CodeRecords/2514/60846/277965.py
163
3.90625
4
def func(substr,str): for ch in substr: if ch not in str: return False return True if func(input(),input()): print("True") else: print("False")
a0aa912e46a15faed7aa11dade1eda1ddcf62e08
xuedagong/hello
/leetcode/python/Largest Number.py
822
4.3125
4
#coding=utf-8 ''' Given a list of non negative integers, arrange them such that they form the largest number. For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. Note: The result may be very large, so you need to return a string instead of an integer. Credits: Special thanks to @ts for adding this problem and creating all test cases. ''' class Solution(object): #主要的问题 3 30 这种排序 def largestNumber(self, nums): """ :type nums: List[int] :rtype: str """ str_lst=[] for one_num in nums: str_lst.append(str(one_num)) str_lst.sort( cmp=lambda x, y: cmp(y + x, x + y), reverse=False) strs=''.join(str_lst) return strs.lstrip('0') or '0' print Solution().largestNumber([0,0])
ca8498b5e3ac8cb64c99242c7990326d3f1a2e95
CaiqueAmancio/ExercPython
/exerc_8.py
674
4.09375
4
""" faça um programa que leia 2 notas de um aluno, verifique se as notas são válidas e exiba na tela a média das notas. Uma nota válida deve ser, obrigatoriamente, um valor entre 0.0 e 10.0, onde caso a nota não possua um valor válido, este fato deve ser informado ao usuário e o programa termina. """ print(f'Olá, insira duas notas válidas (entre 0.0 e 10.0) para calcular a média.') nota1 = float(input(f'Insira a primeira nota: ')) nota2 = float(input(f'Insira a segunda nota: ')) media = (nota1 + nota2) / 2 if 10.0 < nota1 > 0.0 or 10.0 < nota2 > 0.0: print('Uma ou ambas as notas está incorreta!') else: print(f'A média do aluno é: {media}')
3843da4195c791ac669cfbaf80d8ad08e9488759
econgrowth/econgrowth.github.io-src
/content/notebooks/RandomWalk.py
748
3.71875
4
#!/usr/bin/env python # coding=utf-8 ''' My First script in Python Author: Me E-mail: me@me.com Website: http://me.com GitHub: https://github.com/me Date: Today This code computes Random Walks and graphs them ''' import numpy as np import matplotlib.pyplot as plt # The function def randomwalk(x0, T, mu, sigma, seed=123456): '''This function computes and plots a random walk starting from x0 for T periods where shocks have distribution N(mu, sigma^2) ''' if seed is not None: np.random.seed(seed) x = [x0] [x.append(x[-1] + np.random.normal(mu, sigma) ) for i in range(T)] plt.plot(x) plt.title('A simple random walk') plt.xlabel('Period') plt.ylabel('Variable') plt.show() return x
8c8e6035c761cd403ab8c6960586af4a2956e0d6
HWALIMLEE/study
/keras/keras17_mlp_test.py
2,693
3.734375
4
# multi layer perceptron #1. 데이터(x, y값 준비) import numpy as np #시작지점은 1, 뒤에서 -1빼기 range여러개 나열하면 오류가 나옴--->리스트로 만들면 된다. #3행 100열로 나오게 된다. >>>100행 3열로 바꿔야 함 #바꾸려면....? x=np.array([range(1,101),range(311,411),range(100)]) #--->x=np.transpose(x)로 바꾸자 y=np.array(range(711,811)) #리스트-다 모아져 있는 것, [ ]쓰지 않으면 출력이 안 된다. x=np.transpose(x) y=np.transpose(y) # print(x) # print(y) # print(x.shape) # print(y.shape) from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=60,train_size=0.5,test_size=0.2)#column채로 잘리게 된다. train=(80,3) test=(20,3) 행의 숫자에 맞춰서 잘림 x_val, x_test, y_val, y_test=train_test_split(x_test,y_test, shuffle=False, test_size=0.5) # print("x_train:",x_train) # print("x_test:",x_test) # print("x_val:",x_val) #2. 모델구성 #transfer learning from keras.models import Sequential from keras.layers import Dense model=Sequential() model.add(Dense(50,input_dim=3)) #x,y한덩어리(input_dim=1) model.add(Dense(10)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(1000)) model.add(Dense(1000)) model.add(Dense(1000)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(1100)) model.add(Dense(1100)) model.add(Dense(1100)) model.add(Dense(11)) model.add(Dense(5000)) model.add(Dense(10)) model.add(Dense(500)) model.add(Dense(500)) model.add(Dense(1)) #output을 3으로 하면 3개이 데이터를 넣었을 때 3개를 예측하는 것은 이상하다. 3개의 상호작용을 통해 하나를 예측하는 것이 더 설득력 있다. #3.훈련-기계 model.compile(loss='mse',optimizer='adam',metrics=['mse']) model.fit(x_train, y_train,epochs=100, batch_size=3,verbose=2) # print("x_train:",x_train) # print("x_test:",x_test) # print("x_train_len:",len(x_train)) # print("x_test_len:",len(x_test)) # 4.평가 loss,mse=model.evaluate(x_test,y_test,batch_size=8) print("loss:",loss) print("mse:",mse) #5.예측 y_predict=model.predict(x_test) print("y_predict:",y_predict) #RMSE구하기 from sklearn.metrics import mean_squared_error as mse def RMSE(y_test,y_predict): return np.sqrt(mse(y_test,y_predict)) #RMSE는 함수명 print("RMSE:",RMSE(y_test,y_predict)) #RMSE는 가장 많이 쓰는 지표 중 하나 #R2구하기 from sklearn.metrics import r2_score r2=r2_score(y_test,y_predict) print("R2:",r2) #즉, RMSE는 낮게 R2는 높게 # 과제 #1. R2를 0.5이하 #2. layers를 5개 이상 #3. node의 개수 10개 이상 #4. epoch는 30개 이상 #5. batch_size는 8이하
f40f4e35b419fa143fbc2e0fb0ab92719e613aa5
minkyeong081004/MK-S-fishgame
/play2.py
2,188
3.8125
4
import turtle as t import random as r #shark shark=t.Turtle() shark.shape("triangle") shark.color("salmon") shark.speed(0) shark.penup() shark.goto(r.randint(-200,200),r.randint(-200,200)) #plain plain=t.Turtle() plain.shape("circle") plain.color("teal") plain.speed(0) plain.penup() plain.goto(r.randint(-200,200),r.randint(-200,200)) #rock rock1=t.Turtle() rock1.shape("circle") rock1.color("teal") rock1.speed(0) rock1.penup() rock1.goto(r.randint(-200,200),r.randint(-200,200)) rock2=t.Turtle() rock2.shape("circle") rock2.color("teal") rock2.speed(0) rock2.penup() rock2.goto(r.randint(-200,200),r.randint(-200,200)) class Game(): def turn_right(self): t.setheading(0) def turn_up(self): t.setheading(90) def turn_left(self): t.setheading(180) def turn_down(self): t.setheading(270) def play(self): t.clear() t.forward(15) ang=shark.towards(t.pos()) shark.setheading(ang) shark.forward(13) duration=0 if t.distance(plain)<15: self.result("find plain",duration) elif t.distance(rock1)<15 or t.distance(rock2)<15: duration=1 self.result("it's rock",duration) elif t.distance(shark)<15: self.result("try again",duration) else: t.ontimer(g.play,100) def result(self,msg,dur): if dur==1: t.forward(15) t.write(msg,False,"center",("",20)) else: t.goto(0,0) t.write(msg,False,"center",("",20)) shark.goto(r.randint(-200,200),r.randint(-200,200)) plain.goto(r.randint(-200,200),r.randint(-200,200)) rock1.goto(r.randint(-200,200),r.randint(-200,200)) rock2.goto(r.randint(-200,200),r.randint(-200,200)) g=Game() t.setup(450,450) t.bgcolor("lightsteelblue") t.shape("turtle") t.speed(0) t.penup() t.goto(0,0) t.color("white") t.onkeypress(g.turn_right,"Right") t.onkeypress(g.turn_up,"Up") t.onkeypress(g.turn_left,"Left") t.onkeypress(g.turn_down,"Down") t.onkeypress(g.play,"space") t.listen()
cced27da5edc8ae83030e57694137f09a33026cb
JimVargas5/Numerical_Analysis
/Numerical_Calculus/HW/HW2/2_2_p3_supp.py
402
3.625
4
# Jim Vargas import math r=math.pi/2.0 def f(x): return (math.cos(x))**2.0 def f_prime(x): return -2*math.sin(x)*math.cos(x) def Newton(x,f,f_prime): return x-f(x)/f_prime(x) def Newton1(x): return (math.cos(x) + 2*x*math.sin(x))/(2*math.sin(x)) x0=1 x=x0 n=0 while abs(x-r)!=0: t1=abs(x-r) x=Newton1(x) t2=abs(x-r) n+=1 print(n, x,'\t',abs(x-r),'\t',t2/t1) print(r)
b9bc654c7d5db43dd9d521343d0a98f7a6b76eff
SirAeroWN/randomPython
/Euler Problems/Euler3.py
2,520
3.90625
4
# This program solves Eulers problem 3 # What is the largest prime factor for the number 600851475143 # this requires finding some primes, which I've done some work in previously: ######################### ###### EXPLENATION ###### ######################### # This is known as a sieve. # the way it works is you assemble a list of all the numbers under x # then starting with the first prime number (2) remove all numbers divisible by it (2) # the next highest number on this list will be the next prime number # repeat the process with this next number # again the next highest number will be the next prime # repeat until the next prime is greater than sqrt(X) # the list now only contains prime numbers def getPrimes6_1(a): potsOld = [] potsNew = [2, 3, 5] # start off with primes 2, 3, 5 because 2 and 5 break the "primes only end in 1, 3, 7, or 9" rule;; include 3 because order is important ceiling = a[0]**0.5 # only need to go to the sqrt() of the max prime because any numbers bigger than sqrt() will have to be multiplied by something smaller than sqrt() which are all already prime curPrime = 2 # start with first prime index = 0 for i in range(6, a[0]): if (i % 10) in [1, 3, 7, 9]: # eliminate any numbers not follwing prime rule, reduces computaions in next step potsNew.append(i) while curPrime < ceiling: potsOld = potsNew # transfer the reduced list to the list of possibles potsNew = [] for pos in potsOld: if pos <= curPrime or pos % curPrime != 0: # if the number is smaller than curPrime it has already been vetted as a prime, if it is divisible by curPrime then it isn't included potsNew.append(pos) index += 1 curPrime = potsNew[index] # move to the next highest number in potsNew, it will be a prime # but this just finds all primes under a certain ceiling, I want the largest prime factor bigNum = 600851475143 #candidates = getPrimes6_1([bigNum]) best = 0 # for pos in candidates: # if pos % bigNum == 0 and pos > best: # best = pos #print(best) # computing all primes under 600 billion takes too long ## this next method takes out the smallest factor, the last indivisible number is the largest prime def smallestPrime(n): for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return i return n prime = smallestPrime(bigNum) while prime != bigNum: bigNum = bigNum / prime prime = smallestPrime(bigNum) print(int(bigNum))
e968eb9e5e60730b4e2b1cd04fa292ef1e3b7191
bpPrg/Tips
/Softwares/geany/some_notes/simple_plot.py
217
3.546875
4
# -*- coding: utf-8 -*- """ This is a simple plot script. """ from matplotlib import pyplot as plt x = [5,8,10] y = [12,16,6] plt.plot(x,y) plt.title('Title') plt.ylabel('Y axis') plt.xlabel('X axis') plt.show()
f18d95d811c0df9376adf5ee25a4fb93cb660189
charan2108/Pythondirectories
/PythonIntroduction/FlowControl/IF/ifweight.py
189
3.84375
4
weight = float(input("ENter the weight ig kg: ")) if weight > 60: print("if weight exceeds the 60kg limit the additional amount has to be paid") if weight < 60: print(" Thank you")
4865022139d5f3ec6835ce21dd6b9e6612491dcb
AshmitaRakshit/Class98
/function.py
343
3.671875
4
def my_function(): print("Hello from a function") my_function() #----------------------- def my_function(name): print("welcome ",name) #calling a function my_function("Ashmita") my_function("XH") #-------------------------- def my_function(fname, lname): print(fname + " " + lname) my_function("Ashmita", "Rakshit")
9b171484fbd231bf01d1fb2ada2a325f47ad3220
withhong/python
/basic/12_if.py
971
4.09375
4
# 1. 조건문 (단일 if, if~else, 다중 if, 중첩 if, 3항 연산자) # 조건문 수행시 코드는 ':'와 indent 를 통해 구분 # 단일 if 문 print("A") if 1: print("B") print("C") print("#"+"-"*20+"#") # if~else 문 print("A") if 1: print("B") else: print("C") print("#"+"-"*20+"#") # 다중 if 문 # 입력을 받으면 문자열이다. # 문자열 -> 정수 : int # 정수 -> 문자열 : str #n = int(input("점수입력:")) n = 100 if (n>90): print("A") elif (n>80): print("B") else: print("C") print("#"+"-"*20+"#") # 중첩 if 문 n = 99 if (n>90): print("A") else: if (n>80): print("B") else: print("C") print("#"+"-"*20+"#") # 3항 연산자 # 보통은 (조건식)? 참일때 : 거짓일때 # python 은 참일때 if (조건식) else 거짓일때 a = 6 result = 100 if a==61 else 200 print(result) print("#"+"-"*20+"#")
4569649fc7f70f53e1ee3f78be583f36a2e7a8c7
GDGGranada/python_django_dic13
/examples/tabulacionComentada.py
681
3.828125
4
def malTabulado(): #Todo lo que tenga una tabulacion pertenece a esta funcion print "Yo estoy bien tabulado" print "Yo la estoy liando parda" print"Yo estoy bien tabulado" malTabulado() ''' Por qu este programa no funciona?, veamoslo tranquilamente En primer logar tenemos la definicion de una funcion, entonces, todo lo que este tabulado por debajo pertenecera a esa funcion En la lnea 6 aparece un print sin tabulacion, cosa que no seria mala si la funcion terminara en el primer print. Sin embargo en la linea 7 tenemos otro print con tabulacion. Python no sabe interpretar a que bloque pertenece y nos lanza un error de indentacion'''
39ab624465e2be9e425796a45fd281b2540c3cc4
harikumar-sivakumar/ticketBooking
/ticketBooking.py
4,081
3.578125
4
class ShowList: shows = [] def createShow(self): name = input("\nEnter the show name: ").strip() if len([1 for show in self.shows if show.name == name]) == 0: self.shows.append(Show(name)) else: print("Show already exists.") def soldDetails(self): if len(self.shows) > 0: print('\n' + '{:<20}'.format('Show Name') + '{:<9}'.format('Sold')) print('-' * 29) for show in self.shows: show.soldDetails() else: print("No shows.") def buyTickets(self): if len(self.shows) > 0: print('\n' + '{:<10}'.format('Show No.') + '{:<25}'.format('Show Name') + '{:<15}'.format('Available Seats')) print('-' * 50) for i,show in enumerate(self.shows): show.buyTicketsDetails(i) showSelected = input("Select show number (C to cancel): ").strip() if showSelected == 'c' or showSelected == 'C': print("Booking Cancelled.") return None try: showSelected = int(showSelected) - 1 if showSelected not in range(0, len(self.shows)): raise ValueError('Invalid input') except: print("Invalid input") return None self.shows[showSelected].buyTickets() else: print("No shows available.") def deleteShow(self): if len(self.shows) > 0: print('\n' + '{:<10}'.format('Show No.') + '{:<25}'.format('Show Name')) print('-' * 35) for i,show in enumerate(self.shows): show.deleteShowDetails(i) delete = input("Enter show number to delete (C to cancel): ").strip() if delete == 'c' or delete == 'C': print("Delete Cancelled.") return None try: delete = int(delete) - 1 if delete in range(0, len(self.shows)): self.shows.pop(delete) print("Deleted successfully") else: print("Invalid input.") except: print("Invalid input.") else: print("No shows.") class Show: def __init__(self, name): self.name = name self.capacity = input("Enter the seating capacity: ").strip() while type(self.capacity) != int: try: self.capacity = int(self.capacity) except: self.capacity = input("Invalid input. Enter capacity as a number: ") self.availableSeats = self.capacity def buyTicketsDetails(self,i): print('{:<10}'.format(str(i + 1)) + '{:<25}'.format(self.name) + '{:<15}'.format(str(self.availableSeats))) def buyTickets(self): seatsSelected = input("Enter number of seats to book: ").strip() try: seatsSelected = int(seatsSelected) except: print("Invalid input") return None if self.availableSeats >= seatsSelected: self.availableSeats -= seatsSelected print(str(seatsSelected) + " ticket(s) booked successfully for the show " + self.name) else: print(str(seatsSelected) + " ticket(s) not available.") def soldDetails(self): print('{:<20}'.format(self.name) + '{:<4}'.format(str(self.capacity - self.availableSeats))) def deleteShowDetails(self,i): print('{:<10}'.format(str(i+1)) + '{:<25}'.format(self.name)) s = ShowList() while True: action = input("\n1. Add new show. \n2. Delete show. \n3. Show sold tickets.\n4. Buy tickets.\n5. Quit. \n\nEnter your selection: ").strip() if action == '1': s.createShow() elif action == '2': s.deleteShow() elif action == '3': s.soldDetails() elif action == '4': s.buyTickets() elif action == '5' or action == 'q' or action == 'Q': break else: print("\nInvalid input.")
6821aef819e5e5cc46f75e58119a710c760186b8
stefifm/Guia02
/temperatura.py
297
3.8125
4
print("Temperaturas en deposito quimico") #datos T1=int(input("Cargue Temperatura 1: ")) T2=int(input("Cargue Temperatura 2: ")) T3=int(input("Cargue Temperatura 3: ")) #proceso prom1=(T1+T2+T3)/3 prom2=(T1+T2+T3)//3 #resultados print("Promedio decimal: ",prom1) print("Promedio entero: ",prom2)
552f8637c1f336084b4abd16b419d9d74a698013
janellecueto/HackerRank
/Security/EncryptionScheme.py
125
3.734375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import math n = int(input()) print(math.factorial(n))
5568f63d737cceb6186b129765f819fac2becd94
gfcharles/euler
/python/euler024.py
1,877
3.9375
4
""" A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120 201 210 What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? """ import json from functools import cache from euler import euler_problem @euler_problem() def euler024(json_text: str = None, elements: list = None, position: int = 0): if elements is None: elements, position = extract(json_text) length = len(elements) if position > factorial(length): raise Exception(f'Position {position} is larger than number of permutations: {factorial(length)}') remaining_elements = list(elements) # Subtract 1 because the 1st position is after 0 permutations, etc. remainder = position - 1 answer = [] for x in reversed(range(length)): # go from (length - 1) to 0 # how many complete permutations of the x largest of the x + 1 remaining elements were there? next_index = remainder // factorial(x) # that gives us the index next element that will be in that position answer.append(remaining_elements.pop(next_index)) remainder -= (next_index * factorial(x)) return ''.join(map(str, answer)) def extract(json_text: str) -> (list, int): obj = json.loads(json_text) return obj['elements'], obj['position'] @cache def factorial(n: int) -> int: if n < 2: return 1 return n * factorial(n - 1) if __name__ == '__main__': print(euler024(elements=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], position=1_000_000)) print(euler024(elements=[0, 1, 2], position=4)) print(euler024('{"elements": [0, 1, 2], "position": 4}'))
f1332a18ae7a5e0934727c1b683f76d335d1198c
rvrheenen/OpenKattis
/Python/gamerank/gamerank.py
736
3.828125
4
def stars_for_rank(rank): if rank >= 21: return 2 if rank >= 16: return 3 if rank >= 11: return 4 return 5 rank = 25 stars = 0 streak = 0 record = list(input()) for game in record: if rank == 0: break if game == "W": streak += 1 stars += (2 if streak >= 3 and rank >= 6 else 1) if stars > stars_for_rank(rank): stars = stars - stars_for_rank(rank) rank -= 1 else: streak = 0 if rank <= 20: if stars > 0: stars -= 1 else: if rank < 20: rank += 1 stars = stars_for_rank(rank) - 1 print(rank if rank > 0 else "Legend")
3a679b66696f92234009fa4d3a3cc2c3b869ab84
jgartsu12/my_python_learning
/python_methods_functions/combine_args.py
864
3.96875
4
# How to Combine All Argument Types in a Single Python Function # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def greeting(time_of_day, *args, **kwargs): # args will be username print(f"Hi {' '.join(args)}, I hope you are having a great {time_of_day}") if kwargs: print('Your tasks for day are:') for key, val in kwargs.items(): # for/in loop over a dictionary print(f"{key} => {val}") # => is the task # large amount args pass args on diff line greeting('Morning', # time_of_day (positional args) 'Krisitne', 'Hudgens', # *args --> tuple first = 'Empty dishwasher', # first, second, third = **kwargs second = 'Take pupper outside', third = 'Math HW') # prints: ''' Hi Krisitne Hudgens, I hope you are having a great Morning Your tasks for day are: first => Empty dishwasher second => Take pupper outside third => Math HW '''
3f8c47d55905dcc5fb9daef459eec9cae06bedac
tonyxuxuxu/tonyxuxuxu.github.io
/leetcode_practice/shell_sort.py
388
3.59375
4
def shell_sort(collection): length = len(collection) gap = int(length/2) while gap > 0: for i in range(gap, length): j = i while j >= gap and collection[j-gap] > collection[j]: collection[j-gap], collection[j] = collection[j], collection[j-gap] j -= gap gap = int(gap/2) return collection
b30be76613b6becd86a21d67faa13c44687fcba2
DayChan/lc
/Pythoncode/42.接雨水.py
785
3.5625
4
class Solution(object): """ https://leetcode-cn.com/problems/trapping-rain-water/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-w-8/ """ def trap(self, height): """ :type height: List[int] :rtype: int """ left_max = {} right_max = {} left_max[0] = 0 right_max[len(height)-1] = 0 for i in range(1, len(height)): left_max[i] = max(left_max[i-1], height[i-1]) right_max[len(height)-1-i] = max(right_max[len(height)-1-i+1], height[len(height)-1-i+1]) water = 0 for i in range(len(height)): up = min(left_max[i], right_max[i]) if up > height[i]: water += up - height[i] return water
3d0102fef6868a1e1726eb52fb6478eb287a044f
Mela2014/lc_punch
/lc22_bk.py
900
3.671875
4
class Solution: def generateParenthesis(self, n: int) -> List[str]: rslt, m = [], 2*n def backtracking(curr, left, right): if left+right == m: rslt.append(curr) else: if left < m -left: backtracking(curr+"(", left + 1, right) if right < left: backtracking(curr+")", left, right+1) backtracking("", 0, 0) return rslt def generateParenthesis(self, n: int) -> List[str]: rslt = [] def backtracking(curr, left, right): if left + right == 0: rslt.append(curr) else: if left > 0: backtracking(curr+"(", left -1, right) if right > left: backtracking(curr+")", left, right-1) backtracking("", n, n) return rslt
63de744a3a03848e29b39a36033a8ad807578bb2
arulkumarkandasamy/PythonNotes
/Programs/fibonacci.py
402
4.03125
4
def userInput(): number = int(input('Please enter the number between 1 - 40 to find out the fibonacci :')) return number def findFibonacci(number): if number == 0: return 0 elif number == 1: return 1 else: return findFibonacci(number - 1) + findFibonacci (number - 2) def main(): userNumber = userInput() print(findFibonacci(userNumber)) main()
d8a6cec93b4a54bfe32b83237120b4cc6cc9f65e
ftonato/python-para-zumbis
/list-02/class-02-resolved-ftonato-ademilson-flores-tonato.py
608
4.0625
4
# -*- coding: UTF-8 -*- # 2) Determine se um ano é bissexto. # Tente dividir o ano por 4. Se o resto for diferente de 0, ou seja, se for indivisível por 4, ele não é bissexto. # Se for divisível por 4, é preciso verificar se o ano acaba em 00 (zero duplo). Em caso negativo, o ano é bissexto. # Se terminar em 00, é preciso verificar se é divisível por 400. Se sim, é bissexto; se não, é um ano normal. year = int(input('Digite o ano: ')) if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0): # -*- coding: UTF-8 - print ('Seu ano é bissexto') else: print ('Seu ano não é bissexto')
2480e6bcb17f4507a535ad94979117ec0345977e
Kunal352000/python_adv
/arithemeticOperation.py
225
3.78125
4
print("hiii") x=10 y="siva" def add(a,b): c=a+b print(c) add(4,5) class test: def sub(self,a,b): self.a=a self.b=b print(self.a-self.b) t1=test() t1.sub(5,2) print(__name__)
91f25aadb02705770ec7a093426b97888b56fb86
juthikashetye/PythonProgrammingForBeginners
/Numbers/NumOperators.py
653
3.90625
4
sum = 1+2 difference = 100-1 product = 3*4 quotient = 8/2 power = 2**4 remainder = 3%2 print ('Sum: {}'.format(sum)) print ('Difference: {}'.format(difference)) print ('Product: {}'.format(product)) print ('Quotient: {}'.format(quotient)) print ('Power: {}'.format(power)) print ('Remainder: {}'.format(remainder)) print ("Sum:" + str(sum)) sumStr = "Sum:" + str(sum) print(sumStr) #print ('Sum: (sum)') #Gives output as Sum: (sum) #print ('Sum:' (sum)) #TypeError: 'str' object is not callable #Just putting anything in round brackets doesn't do anything #print ('Sum:' str(sum)) #print ('Sum:' str(sum)) #^ #SyntaxError: invalid syntax
ce92408de4bd565e57e0b5beb072e1a836062d3d
ProxiDoz/shoblabot
/devka_handler.py
807
3.875
4
# Function return true if all letters in message is 'a' def is_message_has_only_a_char(message_text): # print("check '" + message_text + "' for all A symbols") # debug log if (len(message_text) == 0): return False for char in message_text.lower(): # latin and cyrillic chars if char == 'a' or char == 'а': continue else: return False print("devka detected") return True ## Cases for test ## Must return False #print(is_message_has_only_a_char("aaaatest")) #print(is_message_has_only_a_char("")) ## Must return True #print(is_message_has_only_a_char("aaa")) # latin #print(is_message_has_only_a_char("aAa")) # latin #print(is_message_has_only_a_char("ааа")) # cyrillic #print(is_message_has_only_a_char("аАа")) # cyrillic
3c501d44f4743fc373a9ca1db4a80455799fd932
Govindvr/Tic-Tac-Toe
/tictactoe.py
4,797
3.8125
4
value = [' 'for i in range(9)] #List in which the input from both human and computer is stored markp = "" #Stores the mark of the player markc = "" #Stores the mark of the computer def instructions(): #To display intruction and board layout at the begining print("\n\nChoose a cell numbered from 1 to 9 as below and play") print("\n\n\t\t\t1 | 2 | 3 ") print("\t\t\t----------") print("\t\t\t4 | 5 | 6 ") print("\t\t\t----------") print("\t\t\t7 | 8 | 9 ") print("\n-------------------------------------------------------") def input_values(markp,markc,pos): #Function to accept input from the player positon = pos -1 if value[positon]==markc: print("\t\t\tDON'T EVEN TRY, STUPID CHEATER!!!") exit(0) value[positon] = markp def computer(markp,markc): #Function which plays the game as computer row1 = value[0:3] row2 = value[3:6] row3 = value[6:9] col1 = value[0:7:3] col2 = value[1:8:3] col3 = value[2:9:3] dia1 = [value[0],value[4],value[8]] dia2 = [value[2],value[4],value[6]] corner = [0,2,6,8] def attack_corner(): for i in corner: if value[i]==" ": value[i] = markc break def scan(first,last,skip): for i in range(first,last,skip): if value[i] == " ": value[i] = markc else: continue def comp_logic(mark,id = 2): #Function which analyse all possible winning moves and play accordingly if row1.count(mark)==2 and row1.count(" ") != 0: scan(0,3,1) elif row2.count(mark)==2 and row2.count(" ") != 0: scan(3,6,1) elif row3.count(mark)==2 and row3.count(" ") != 0: scan(6,9,1) elif col1.count(mark)==2 and col1.count(" ") != 0: scan(0,7,3) elif col2.count(mark)==2 and col2.count(" ") != 0: scan(1,8,3) elif col3.count(mark)==2 and col3.count(" ") != 0: scan(2,9,3) elif dia1.count(mark)==2 and dia1.count(" ") != 0: scan(0,9,4) elif dia2.count(mark)==2 and dia2.count(" ") != 0: scan(2,7,2) else: if id == 1: return True elif markc == "X": attack_corner() elif value[4] == " ": value[4]=markc elif value.count(" ")==1: value[value.index(" ")] = markc else: attack_corner() return False if comp_logic(markc,1): comp_logic(markp) def check_result(markp,markc): #To check if any player won and to display winning message def who(w): if value[w] == markp: print("\t\t\tSomthing went wrong, you won!") else: print("\t\t\tHAHA NOOB!!!, COMPUTER WON ") exit(0) for i in range(0,7,3): if (value[i]==value[i+1]== value[i+2]) and value[i] != " ": who(i) return False for i in range(3): if (value[i]==value[i+3]==value[i+6]) and value[i] !=" ": who(i) return False if (value[0]==value[4]==value[8]) and value[0] != " ": who(0) return False if (value[2]==value[4]==value[6]) and value[2] != " ": who(2) return False if value.count(" ") == 0: print("\t\t\tFINALLY!!, A WORTHY OPPONENT, Its a Draw!!!") return False return True def display(): #To display the board with player moves print("\n") print("\t\t\t-------------") for i in range(0,7,3): print("\t\t\t|",value[i],"|",value[i+1],"|",value[i+2],"|") print("\t\t\t-------------") print("\n-------------------------------------------------------") #Main body of the program user=input("\n\t\tchoose your letter (X or O)") #player choosing his character user = user.upper() if user == "X": AI = "O" else: AI = "X" instructions() loop = True while(loop): if user == "X": choice = int(input("\nEnter your choice: ")) input_values(user,AI,choice) computer(user, AI) display() loop = check_result(user,AI) else: computer(user, AI) display() loop = check_result(user,AI) choice = int(input("\nEnter your choice: ")) input_values(user,AI,choice) loop = check_result(user,AI)
4de450b190ac90e31082bbe6940f07d96bcc60a7
SACHSTech/ics2o-livehack1-practice-Kyle-Lue
/windchill.py
368
4.40625
4
temperature = float(input("Enter the temperature in celcius: ")) windspeed = float(input("Enter the windspeed (km/h): ")) # compute windchill windchill = 13.12 + (0.6215*temperature) - (11.37 * windspeed**0.16) + (0.3965 * temperature* windspeed**0.16) # output windchill print("With the windchill factor, it feels like " + str(round(windchill,1)) + "° outside.")
a160d20df88278f4a2ec5b81add76d8a3d71dbed
Jackielo/DT211C-Cloud-Computing
/lab3/lab2II.py
145
4
4
word_input = input('Enter the word: ') word_input = word_input.lower() if(word_input == word_input[::-1]): print("True") else: print("False")
461b50240450c851a8e8dbd42f086a7fc7060fc8
thamudi/maqsam
/Task 1/sudoku.py
4,260
3.71875
4
board = [ [7,8,0,4,0,0,1,2,0], [6,0,0,0,7,5,0,0,9], [0,0,0,6,0,1,0,7,8], [0,0,7,0,4,0,2,6,0], [0,0,1,0,5,0,9,3,0], [9,0,4,0,6,0,0,0,5], [0,7,0,3,0,0,0,1,2], [1,2,0,0,0,7,4,0,0], [0,4,9,2,0,6,0,0,7] ] board_two = [ [3,0,6,5,0,8,4,0,0], [5,2,0,0,0,0,0,0,0], [0,8,7,0,0,0,0,3,1], [0,0,3,0,1,0,0,8,0], [9,0,0,8,6,3,0,0,5], [0,5,0,0,9,0,6,0,0], [1,3,0,0,0,0,2,5,0], [0,0,0,0,0,0,0,7,4], [0,0,5,2,0,6,3,0,0] ] def solve(board): found = find_empty_cell(board) if not found: return True # Exit Script else: row, column = found # Assign found empty cell row by column respectuvly for i in range(1,10): # Loop through the options from 1-9 if valid(board, i, (row, column)): # Validate board[row][column] = i # Assigne the current number to the cell if solve(board): # Recusive Check if the board has been solved return True board[row][column] = 0 # Reset Cell return False def find_empty_cell(board): ''' Name: find_empty_cell Description: Checks if the current position of a cell equels 0, which indicates if empty or not Returns: Tuple (row, column) ''' for row in range(len(board)): for column in range(len(board[0])): if board[row][column] == 0: return (row, column) return None def valid(board, number, position): ''' Name: valid Description: Validate if the currnet position of the assigned number can work for each row and column Returns: Boolean ''' # Check row if not (check_row(board, number, position)): return False # Check column if not (check_column(board, number, position)): return False # Check box if not (check_box(board, number, position)): return False return True def check_row(board, number, position): ''' Name: check_row Description: Validate if the currnet row has the assigned number already Returns: Boolean ''' for i in range(len(board[0])): if board[position[0]][i] == number and position[1] != i: return False return True def check_column(board, number, position): ''' Name: check_column Description: Validate if the currnet column has the assigned number already Returns: Boolean ''' for i in range(len(board)): if board[i][position[1]] == number and position[0] != i: return False return True def check_box(board, number, position): ''' Name: check_box Description: Returns: Boolean ''' box_x = position[1] // 3 box_y = position[0] // 3 for i in range(box_y*3, box_y*3 + 3): for j in range(box_x * 3, box_x*3 + 3): if board[i][j] == number and (i,j) != position: return False return True def print_board(board): ''' Name: print_board Description: Prints the sudko board onto a command line interface Returns: Void ''' for i in range(len(board)): if i % 3 == 0 and i != 0: print("- - - - - - - - - - - - - ") for j in range(len(board[0])): if j % 3 == 0 and j != 0: print(" | ", end="") if j == 8: print(board[i][j]) else: print(str(board[i][j]) + " ", end="") ####################### # Program starts here # ####################### print_board(board) # print board before solving solve(board) # Run the solving script print("=============================") # Spacer print("============= First Board ===============") # Spacer print_board(board) # Print the board after solving print("=============================") # Spacer print("============= Second Board ===============") # Spacer print_board(board_two) # print board before solving solve(board_two) # Run the solving script print("=============================") # Spacer print_board(board_two) # Print the board after solving ####################### ##### End Script ###### #######################
870dbf0d2c19675ac1bb5ae7c63afba0f3046231
Polin-Tsenova/Python-Fundamentals
/Palindrome_strings.py
306
4.03125
4
words = input().split() palindrome = input() def is_palindrome(word): return word == word[::-1] palindrome_words = [word for word in words if is_palindrome(word)] print(palindrome_words) palindrome_count =palindrome_words.count(palindrome) print(f"Found palindrome {palindrome_count} times")
a3ed4afb738a02d139f2c15f2a1f5868518110be
bgriffen/heteromotility
/heteromotility/hmtools.py
9,644
3.53125
4
''' Tools for manipulating data structures. TODO : refactor and replace with standard `pandas` implementations. ''' from __future__ import print_function, division import numpy as np def dict2array(d): ''' Merges a dict of lists into a list of lists with the same order. Parameters ---------- d : dict. Returns ------- output : list. list of lists. order : list. keys from dict in order of listing. ''' output = [] order = [] for u in d: output.append(list(d[u])) order.append(u) return output, order def dictofdict2array(top_dict): ''' Converts a dictionary of dictionaries with scalar values and converts to a list of lists. Parameters ---------- top_dict : dict i.e. { a: {x1 : a1, x2 : a2, x3 : a3}, b: {x1 : b1, x2 : b2, x3 : b3} } Returns ------- output : list i.e. [ [a1, b1, c1], [a2, b2, c2] ] order : list keys of top_dict, ordered as listed. ''' output = [] order = [] N = len( top_dict[ list(top_dict)[0] ] ) # number of cells i = 0 while i < N: row = [] for key1 in top_dict: key2 = list(top_dict[key1])[i] #print(key2) order.append(key2) row.append( top_dict[key1][key2] ) output.append(row) i += 1 return output, dedupe(order) def tripledict2array(top_dict): ''' Converts a teriary leveled dictionary to a list of lists. Parameters ---------- top_dict : dict i.e. { a: {x1 : {y1 : [z1,]}, x2 : {y2: [z2,]} }, b: {x1 : {y1 : [z1,]}, x2 : {y2: [z2, z3, z4]} } } Returns ------- output : list i.e. [[z1, z2], [z1, z2, z3, z4]] order : list. keys of the tertiary dictionaries, ordered as listed. ''' output = [] order1 = [] order2 = [] order3 = [] j = 0 while j < len( top_dict[ list(top_dict)[0] ][ list(top_dict[ list(top_dict)[0] ])[0] ] ): row = [] for key1 in top_dict: order1.append(key1) for key2 in top_dict[key1]: order2.append(key2) order3.append(list(top_dict[key1][key2])[j]) if type(top_dict[key1][key2][ list(top_dict[key1][key2])[j] ]) == list: for item in top_dict[key1][key2][ list(top_dict[key1][key2])[j] ]: row.append(item) else: row.append( top_dict[key1][key2][ list(top_dict[key1][key2])[j] ] ) output.append(row) j += 1 return output, dedupe(order3) def cell_ids2tracks(cell_ids): ''' Converts a `cell_ids` dict to `tracksX` and `tracksY` (N,T) coordinate arrays. Parameters ---------- cell_ids : dict cell paths, keyed by an `id`, valued are a list of tuple (x,y) coordinates. Returns ------- tracksX, tracksY : ndarray. N x T arrays of X and Y locations respectively ''' N = len(cell_ids) T = len(cell_ids[list(cell_ids)[0]]) tracksX = np.zeros([N,T]) tracksY = np.zeros([N,T]) n_count = 0 for c in cell_ids: cell = cell_ids[c] for t in range(T): tracksX[n_count, t] = cell[t][0] tracksY[n_count, t] = cell[t][1] n_count = n_count + 1 return tracksX, tracksY def dedupe(seq, idfun=None): ''' Deduplicates lists. ''' # order preserving if idfun is None: def idfun(x): return x seen = {} result = [] for item in seq: marker = idfun(item) # in old Python versions: # if seen.has_key(marker) # but in new ones: if marker in seen: continue seen[marker] = 1 result.append(item) return result import itertools def merge_flat_lists(lists): ''' Merges a tertiary list of lists into a seconday list of lists. Parameters ---------- lists : list. tertiary list of lists [ [[a0,a1,a2], [b0,b1,b2]] ] Returns ------- merged_list : list. secondary list of lists [[a0,a1,a2,b0,b1,b2]] ''' merged_list = [] n_rows = len(lists[0]) i = 0 while i < n_rows: tmp_list = [] for l in lists: tmp_list.append(l[i]) tmp_merged = list( itertools.chain( *tmp_list ) ) merged_list.append(tmp_merged) i += 1 # merged_list = [ [all vals for one cell], [...], ... ] return merged_list def single_outputs_list(cell_ids, gf, rwf, msdf, output_dir, suffix=None): ''' Creates a list of lists list[N][M] of cell statistics for CSV export. Parameters ---------- cell_ids : dict cell paths, keyed by an `id`, valued are a list of tuple (x,y) coordinates. gf : hmstats.GeneralFeatures object rwf : hmstats.RWFeatures object msdf : hmstats.MSDFeatures object output_dir : string path to output directory. suffix : string suffix appended to output filenames. Returns ------- output_list : list list of lists, output_list[N][M], where `N` is cells and `M` is features. ''' # Creates a list of lists for writing out statistics # Ea. internal list is a single cell's stats output_list = [] if suffix: output_dir = output_dir + str(suffix) for cell in cell_ids: output_list.append([ output_dir, cell, gf.total_distance[cell], gf.net_distance[cell], gf.linearity[cell], gf.spearmanrsq[cell], gf.progressivity[cell], gf.max_speed[cell], gf.min_speed[cell], gf.avg_speed[cell], msdf.alphas[cell], rwf.hurst_RS[cell], rwf.nongaussalpha[cell], rwf.disp_var[cell], rwf.disp_skew[cell], rwf.diff_linearity[cell], rwf.diff_net_dist[cell] ]) return output_list def fix_order(correct_order, new_order, sorting): ''' Fixes the order of a list in `sorting` with `new_order` to match the index order layed out in `correct_order`. Parameters ---------- correct_order : list. contains keys in the correct order, guides sorting of the list `sorting` new_order : list. contains same set of keys in correct_order, but in a different order. sorting : list. list to be sorted based on the order in `correct_order`. ''' # if order is correct, return input seq if correct_order == new_order: return sorting, new_order new_idx_order = [] # idx's of `correct_order[i]` loc in `new_order` for i in correct_order: new_idx_order += [new_order.index(i)] reordered_vals = [] reordered_keys = [] for i in range(len(new_idx_order)): reordered_vals += [sorting[new_idx_order[i]]] reordered_keys += [new_order[new_idx_order[i]]] assert correct_order == reordered_keys, 'keys not correctly ordered in `fix_order()`' return reordered_vals, reordered_keys def make_merged_list(ind_outputs, gf, rwf): '''Merge output lists for all features Parameters ---------- ind_outputs : list ind_outputs[N][M], where `N` is cells and `M` is features. gf : hmstats.GeneralFeatures object rwf : hmstats.RWFeatures object Returns ------- merged_list : list merged_list[N][M], where `N` is cells and `M` is features. Notes ----- Utilized `fix_order` and assertion checks to ensure that dictionary ordering is not perturbed during concatenation, which can occur in Python2 where dict primitive behavior is not robust to ordering in the manner of Python3. This is not official support for Python2, merely an attempt to prevent silent failure and generation of erroneous output. ''' ind_order = [] for i in ind_outputs: ind_order.append(i[1]) autocorr_array, autocorr_order = dict2array(rwf.autocorr) autocorr_array, autocorr_order = fix_order(ind_order, autocorr_order, autocorr_array) assert ind_order == autocorr_order, 'individual and autocorr not in same order' diff_kurtosis_array, diff_kurtosis_order = dictofdict2array(rwf.diff_kurtosis) diff_kurtosis_array, diff_kurtosis_order = fix_order(ind_order, diff_kurtosis_order, diff_kurtosis_array) assert ind_order == diff_kurtosis_order, 'individual and diff_kurtosis not in same order' avg_moving_speed_array, avg_moving_speed_order = dictofdict2array( gf.avg_moving_speed ) avg_moving_speed_array, avg_moving_speed_order = fix_order(ind_order, avg_moving_speed_order, avg_moving_speed_array) assert ind_order == avg_moving_speed_order, 'individual and avg_moving_speed not in same order' time_moving_array, time_moving_order = dictofdict2array( gf.time_moving ) time_moving_array, time_moving_order = fix_order(ind_order, time_moving_order, time_moving_array) assert ind_order == time_moving_order, 'individual and time_moving not in same order' turn_list, turn_list_order = tripledict2array(gf.turn_stats) turn_list, turn_list_order = fix_order(ind_order, turn_list_order, turn_list) assert ind_order == turn_list_order, 'individual and turn_list not in same order' theta_list, theta_list_order = tripledict2array(gf.theta_stats) theta_list, theta_list_order = fix_order(ind_order, theta_list_order, theta_list) assert ind_order == theta_list_order, 'individual and theta_list not in same order' merged_list = merge_flat_lists([ind_outputs, diff_kurtosis_array, avg_moving_speed_array, time_moving_array, autocorr_array, turn_list, theta_list]) return merged_list
3fe2b90f4b3cc87b4ba4a7948544d3bf63bf7706
bitromortac/lnregtest
/lnregtest/lib/graph_testing.py
3,077
3.546875
4
""" Module can be used to check if graphs are defined in the correct convention. """ from typing import Dict def graph_test(nodes): """ Tests if a graph was defined in a certain convention. :param nodes: nodes definition :type nodes: dict """ channel_numbers = sorted(get_channel_numbers(nodes)) test_node_names_alphabetical(nodes) test_channel_numbers_unique(channel_numbers) test_ports(nodes) test_allowed_node_implementations(nodes) def test_allowed_node_implementations(nodes: Dict[str, Dict]): """ Tests if the daemon fields in the node definitions is from the supported set of daemons. """ allowed_nodes = {None, 'electrum', 'lnd'} # None is lnd default present_nodes = set() for n in nodes.values(): present_nodes.add(n.get('daemon')) for pn in present_nodes: if pn not in allowed_nodes: raise ValueError( f"Error in daemon field of graph definition, " f"should be one of {allowed_nodes}, is {pn}.") def get_channel_numbers(nodes): """ Extracts channel numbers from graph definition. :param nodes: nodes definintion :type nodes: dict :return: channel numbers :rtype: list(int) """ channels = [] for node_name, node_data in nodes.items(): channels.extend(node_data['channels'].keys()) return channels def test_node_names_alphabetical(nodes): """ Tests if the names of the nodes were defined in an alpabetical increasing order. :param nodes: nodes definition :type nodes: dict :return: True if test matches expectation :rtype: bool """ node_names = nodes.keys() number_nodes = len(node_names) alphabet = [str(chr(i)) for i in range(65, 91)] node_names_should = alphabet[:number_nodes] assert node_names_should == list(node_names),\ "Node names do not follow convention A, B, C, ..." def test_channel_numbers_unique(channel_numbers): assert len(set(channel_numbers)) == len(channel_numbers), \ 'Channel numbers are not unique.' def get_ports(nodes): """ Extracts ports from nodes definition. :param nodes: nodes definition :type nodes: dict :return: lnd ports, grpc ports, rest ports :rtype: list, list, list """ ports = [] grpc_ports = [] rest_ports = [] for node_name, node_data in nodes.items(): ports.append(node_data['port']) grpc_ports.append(node_data['grpc_port']) rest_ports.append(node_data['port']) return ports, grpc_ports, rest_ports def test_ports(nodes): ports, grpc_ports, rest_ports = get_ports(nodes) assert len(nodes) == len(ports) assert len(nodes) == len(grpc_ports) assert len(nodes) == len(rest_ports) assert len(ports) == len(set(ports)) assert len(grpc_ports) == len(set(grpc_ports)) assert len(rest_ports) == len(set(rest_ports)) if __name__ == '__main__': from lnregtest.network_definitions.default import nodes as star_ring_nodes graph_test(star_ring_nodes)
75c78bfec3aa3f2925c3ea95d0ecbeb64394e6c1
endreujhelyi/endreujhelyi
/week-04/day-3/11b.py
303
3.765625
4
from tkinter import * top = Tk() size = 300 canvas = Canvas(top, bg="#1ce", height=size, width=size) def square_drawer(a, b, color): canvas.create_rectangle(a, a, a+b, a+b, fill=color) j = 10 for i in range(10, 61, 10): square_drawer(j, i, 'purple') j += i canvas.pack() top.mainloop()
e14dc733a61f4654b8781e98d57e00a177e65bbb
vanshikasanghi/dv.pset
/0086 Binomial Expansion/binomialEx.py
886
3.71875
4
#getting the expanion elements = [1] n = int(input("Input : ")) for x in range(0,n) : tripattern = [] tripattern.append(1) #starting term for i in range(0,len(elements)-1) : tripattern.append(elements[i]+elements[i+1]) tripattern.append(1) #ending term elements = tripattern #storing the value of the sequence in elements #printing the binomial expansion i = 0 x = n #for coefficients y = 0 print("Output : ") print("(x+y)"+str(n)+" = ",end='') while (x>=0) : if (y==0) : if (elements[i]!=1) : coeff = elements[i] else : coeff = "" print(str(coeff)+"x^"+str(x)+" + ",end ='') elif (x==0) : if(elements[i]!=1) : coeff = elements[i] else : coeff = "" print(str(coeff)+"y^"+str(y)) else : if(elements[i]!=1) : coeff = elements[i] else : coeff = "" print(str(coeff)+"x^"+str(x)+"y^"+str(y)+" + ",end='') i = i+1 x = x-1 y = y+1
ea97e6e173fcf6e36d9467a7ea042dd3c3647e54
joshsizer/free_code_camp
/algorithms/pairwise/pairwise.py
2,260
4.1875
4
""" Created on Mon May 3 2021 Copyright (c) 2021 - Joshua Sizer This code is licensed under MIT license (see LICENSE for details) """ def pairwise(arr, arg): """Get the sum of all index pairs, where the values at the index pairs add up to arg. For example, pairwise([1, 4, 2, 3, 0, 5], 7) finds the index pairs [1, 3] because arr[1] + arr[3] = 7 as well as index pairs [2, 5] because arr[2] + arr[5] = 7. The total sum of all index pairs is 1 + 3 + 2 + 5 = 11. Arguments: arr: an array of numbers arg: the target sum to look for Returns: The total sum of all index pairs, where each index pair's values add up to arg. """ # We keep a running sum and an auxillary array # to keep track of which indices have already # been used in an index pair. idx_sum = 0 taken = [False for _ in range(len(arr))] # Grab the first index pair. (i, j) = single_pairwise(arr, arg, taken) # Sum of 0 is returned if no pairs were found # yet. Otherwise, we accumulate our index # pairs into idx_sum and update our auxillary # array. while (i != -1): idx_sum += i + j # No index may be used in more than one # pair, so we have to mark which indices # have already been used. taken[i] = True taken[j] = True # Try to find another index pair. (i, j) = single_pairwise(arr, arg, taken) return idx_sum def single_pairwise(arr, arg, taken): """Get a single index pair (i, j), where arr[i] + arr[j] == arg. Arguments: arr: an array of numbers arg: the target sum to look for taken: an array as long as arr designating if a particular index can be in a new index pair. """ i = -1 j = -1 # Compare the sum of every pair of values in # arr to arg, and return the first set of # indices where the pair of values add to arg. for i in range(len(arr)): for j in range(i + 1, len(arr)): if arr[i] + arr[j] == arg and taken[i] == taken[j] == False: return (i, j) # If no pair of values sum to arg, then we # indicate that with special value -1. return (-1, -1)
2ccb674a1c3794bf954b043eaad6549595bd2041
Rwothoromo/hashcode
/2020/slice_practice/slice2.py
1,565
3.625
4
import sys def knapsack(items, capacity): selected_pizzas = [] possible_count = 0 for (index, item) in enumerate(items): if not selected_pizzas: possible_count += item selected_pizzas.append((index, item)) elif item != selected_pizzas[-1]: possible_count += item selected_pizzas.append((index, item)) if possible_count > capacity: break len_selected = len(selected_pizzas) for pizza in selected_pizzas: index = pizza[0] item = pizza[1] if index == 0: if possible_count - item <= capacity: return [i[0] for i in selected_pizzas[index+1:]] elif index < len_selected-1: if possible_count - item <= capacity: return [i[0] for i in (selected_pizzas[:index] + selected_pizzas[index+1:])] # if at the last item else: return [i[0] for i in selected_pizzas[:len_selected-1]] if __name__ == '__main__': if len(sys.argv) > 1: file_location = sys.argv[1].strip() with open(file_location, 'r') as file: input_data = file.read() lines = input_data.split('\n') _capacity = int(lines[0].split()[0]) _items = [int(item) for item in lines[1].split()] result = knapsack(_items, _capacity) result_len = len(result) result_string = ' '.join(map(str, result)) output_file = open(sys.argv[2], 'w') output_file.write("{}\n{}\n".format(result_len, result_string))
60295b7d437d3a45209ac121d33568891e345d33
fqingyu/Leetcode
/Q10.py
992
3.65625
4
class Solution: def isMatch(self, s: str, p: str) -> bool: print("str:{}, pattern:{}".format(s, p)) if not p: return not s elif p: if len(p) >= 2 and p[1] == '*': # if not self.isMatch(s, p[2:]): # if s[1:] and s[1] == s[0]: # return self.isMatch(s[1:], p) # elif s[1:] and s[1] != s[0] and p[0] == '.': # return self.isMatch(s[1:], p) # return self.isMatch(s[1:], p[2:]) if not self.isMatch(s, p[2:]): return self.isMatch(s[1:], p[2:]) else: return self.isMatch(s[1:], p) else: if s: if p[0] == s[0] or p[0] == '.': return self.isMatch(s[1:], p[1:]) elif not s: return False test = Solution() print(test.isMatch('aab', '.*c*a*b'))
a04438ba3ee180ee1c9b7065c39ed460f4f58644
shalakatakale/Python_leetcode
/Leet_Code/1TwoSum.py
1,109
3.71875
4
'''1. Two Sum - Array, Hash table (dictionary) ''' class Solution(): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ store = {} # this dictionary contains complement value of numbers in nums for i in range(len(nums)): # O(n) if nums[i] in store: # or write store.keys() return (store[nums[i]], i) , print(store) else: store[target - nums[i]] = i #append key as complement of nums[i] and value as index of nums ## Example Execution ## obj = Solution() result = obj.twoSum([2,4,757,6,43,15,1,1,11,12], 8) print(result) # 2 faster class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ visited = {} for i in range(len(nums)): if target - nums[i] in visited: return [i, visited[target - nums[i]]] visited[nums[i]] = i
8b8bba10fee596e1c84fba15de610f3f3317e1c5
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4351/codes/1811_2563.py
262
3.609375
4
from numpy import* mf=array(eval(input("vetor de notas finais: "))) while (size(mf)>1): i=0 apr=0 for v in mf: if (mf[i]>=5 and mf[i]<7): apr= apr + 1 i= i + 1 else: i = i + 1 print(apr) mf=array(eval(input("vetor de notas finais: ")))
7a76aba9b677523c886be2f3b79173299fe91fbf
Planet-KIM/planet_teams
/except/raise1.py
450
3.734375
4
def raisetest(): try: integer = int(input('2의 배수를 입력하세요 : ')) if (integer % 2) != 0: raise Exception('2의 배수가 아닙니다.') print(integer) except Exception as e: print('raisetest 함수에서 예외가 발생했습니다.', e) raise try: raisetest() except Exception as e: print('스크립트 파일에서 예외가 발생했습니다.', e)
37c52333ae70d752b926a939fc018b1d4e49e5e4
gorilik324/ctax
/src/ColumnReader.py
3,975
3.515625
4
import csv import re from src.Error import Error class column_reader: """ Returns an iterable reader for the specified file. :param: section configuration section with information about the file such as delimiter, column infos, etc. """ def __init__(self, configuration, filename): self._filename = filename self._configuration = configuration self._file = None def __enter__(self): delimiter = self._get_value('delimiter') encoding = self._get_value('encoding') quotechar = self._get_value('quotechar') columns = self._get_value('columns') currency_map = self._get_value('currency-map') self._file = open(self._filename, 'rt', encoding=encoding) return ColumnReader(csv.reader(self._file, delimiter=delimiter, quotechar=quotechar), columns, currency_map) def __exit__(self, exc_type, exc_val, exc_tb): self._file.close() def _get_value(self, value_id): if value_id not in self._configuration: if 'exchange' not in self._configuration: raise Error(f'missing configuration value "{value_id}"') else: raise Error(f'missing configuration value "{value_id}" for exchange {self._configuration["exchange"]}') return self._configuration[value_id] class ColumnReader: """ Reader that iterates through rows of a CSV file and can be queried for column values. """ def __init__(self, reader, columns, currency_map): self._reader = reader self._columns = columns self._currency_map = currency_map self._header = reader.__next__() self._row = None def __next__(self): self._row = self._reader.__next__() return self def __iter__(self): return self def get_currency(self, column_id): return self._map_currency(self.get(column_id)) def _map_currency(self, currency): if currency in self._currency_map: mapped_currency = self._currency_map[currency] if not mapped_currency: raise Error(f'empty currency symbol after mapping: {currency}') return mapped_currency return currency def get(self, column_id, empty_allowed=False): """ Returns the value of the CSV file column that is configured for the specified column id. If the configuration contains a regular expression for the column, the value is matched against the regular expression and the first match group is returned. """ if column_id not in self._columns: raise Error(f'missing column configuration: {column_id}') column_properties = self._columns[column_id] if 'name' not in column_properties: raise Error(f'missing csv column name for column: {column_id}') csv_column_name = column_properties['name'] if 'regex' in column_properties: csv_column_regex = column_properties['regex'] value = self._get_value_with_regex(csv_column_name, csv_column_regex) else: value = self._get_value(csv_column_name) if not empty_allowed and not value: raise Error(f'column data is emtpy: {column_id}') return value def _get_value(self, csv_column_name): try: index = self._header.index(csv_column_name) except ValueError: raise Error(f'configured column not found in file: {csv_column_name}') value = self._row[index] return value def _get_value_with_regex(self, csv_column_name, csv_column_regex): match = re.match(csv_column_regex, self._get_value(csv_column_name)) if match is None: return None try: return match.group(1) except IndexError: raise Error(f'missing match group in regex for column: {csv_column_name}')
90a87d4777d3d737afa64056e527cc9d86d2e8e9
ramyasutraye/Python-Programming-3
/begginners/oddoreven.py
117
3.625
4
a=int(input()) if(a>=1 and a<=100000): if(a%2==0): print 'even' else: print 'odd' else: print 'invalid value'
34912d7e4a2af598a8ef549dcfd6cac7a8bf4180
mikey-manma/mikey-manma
/1-8d.py
296
3.609375
4
#!/usr/bin/env python # coding: utf-8 # In[2]: s=input() p=input() s+=s ans="No" for i in range(len(s)//2): if(s[i]==p[0]): for j in range(len(p)): if(s[i+j]!=p[j]): break if(j==len(p)-1): ans="Yes" print(ans) # In[ ]:
14c64a73dcf9f628d5a0ef3340fc0caeb264dbc6
Goku-kun/1000-ways-to-print-hello-world-in-python
/using-binary.py
66
3.5
4
str = "hello world" print(" ".join(f"{ord(i):08b}" for i in str))
4281824d2033ab8aed92f1faaed4a70fa4e82d09
hyang012/leetcode-algorithms-questions
/014. Longest Common Prefix/Longest_Common_Prefix.py
1,183
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Leetcode 14. Longest Common Prefix Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Note: All given inputs are in lowercase letters a-z. """ # Horizontal scanning def longestCommonPrefix(strs): """ :type strs: List[str] :rtype: str """ if strs is None or len(strs) == 0: return '' res = strs[0] for word in strs: while word.find(res) != 0: res = res[:-1] if res is '': return res return res # Vertical scanning def longestCommonPrefix(strs): """ :type strs: List[str] :rtype: str """ if strs is None or len(strs) == 0: return '' res = '' for i in range(0, len(strs[0])): for word in strs: if i >= len(word) or strs[0][i] != word[i]: return res res += strs[0][i] def longestCommonPrefix(strs): """ :type strs: List[str] :rtype: str """ print(longestCommonPrefix(["flower","flow","flight"]))
e94cf2cce5b6c19ebc79715b587d1e4edf8739aa
IzLeandro/Tarea-Programada-N1-Zoo
/function.py
3,761
3.734375
4
#Elaborado por: Leandro Camacho Aguilar y Celina Madrigal Murillo #Fecha de Creación: 31/10/2020 2:40pm #Fecha de última Modificación: XX/XX/XX X:XXpm #Versión: 3.9.0 #Importaciones from IntegrationWikipedia import getInfo import random import time import re #Definición de funciones def cargarInfoWiki(animales): """ Función:Imprime la información del animal seleccionado Entrada:el número del animal Salida:la información del animal o un mensaje de error """ lista=[] cont=0 print("Obteniendo información desde Wikipedia...") for i in animales: print("Animales cargados: ",cont,"de",len(animales),end="\r") lista+=[getInfo(i)] cont+=1 print("Información cargada correctamente.") time.sleep(2) return lista def apartarAnimales(num,animales): """ Función:Aparta la cantidad de animales escogida Entrada:el número de animales a apartar y la lista de animales Salida:la lista con los animales restantes """ listaNueva=[] while num!=0: num-=1 listaNueva.append(random.choice(animales)) animales=listaNueva return animales def registrarAnotaciones(matriz): """ Función:Hace anotaciones en los animales Entrada:matriz Salida:la matriz con las anotaciones """ while True: for i in range(len(matriz)): print(i+1,":",matriz[i][0]) eleccion=input("Ingrese el número que represente al animal que desea agregar la anotación: ") while not re.match("^\d{1,}$",eleccion): print("Ingrese un valor correcto.") eleccion=input("Ingrese el número que represente al animal que desea agregar la anotación: ") eleccion=eval(eleccion) while eleccion<1 or eleccion>len(matriz): print("Ingrese un valor correcto.") eleccion=input("Ingrese el número que represente al animal que desea agregar la anotación: ") while not re.match("^\d{1,}$",eleccion): print("Ingrese un valor correcto.") eleccion=input("Ingrese el número que represente al animal que desea agregar la anotación: ") eleccion=eval(eleccion) anotacion=input("Digite la anotación que desea agregar: ") matriz[eleccion-1][5]+=[anotacion] if not siNo(): break return matriz def siNo(): """ Función:pregunta si se desea realizar otra anotación Entrada: si o no Salida:booleano o mensaje de error """ entrada=input("Anotación agregada, desea agregar otra? SI/NO: ") if entrada.upper() == "SI": return True if entrada.upper() == "NO": return False else: print("Solo DEBE ingresar Si o No.") return siNo() def salvaguardandoZoologico(matrizAux): """ Función:Por cada animal en la lista simple agrega el animal a la matriz con todos sus datos, menos la imagen Entrada: matriz Salida:los datos de la matriz """ for i in matrizAux: print("░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░") print(i[1],"Usualmente conocido como",i[0],"\n") print(i[3],"\n") if i[5]==[]: print("No existen anotaciones y/o observaciones.\n") else: print("Observaciones y anotaciónes: ", i[5],"\n") print("Puedes encontrar más información aquí:",i[2],"\n\n") return "" def sacaListaAnimales(listaWiki): """ Función:Genera la lista de solo nombres animales Entrada:Matriz Salida:Lista """ nuevaLista=[] for i in listaWiki: nuevaLista+=[i[0]] return nuevaLista
b7ea5a26f902bfa58db4b2015ba7db3b686e807d
zmlabe/IceVarFigs
/Scripts/SeaIce/read_SeaIceThick_PIOMAS.py
2,924
3.921875
4
""" Script reads PIOMAS binary files stored on remote server through present year. Second function calculates climatological average over a given period. Notes ----- Source : http://psc.apl.washington.edu/zhang/IDAO/data_piomas.html Author : Zachary Labe Date : 7 September 2016 Usage ----- readPIOMAS(directory,years,threshold) """ def readPiomas(directory,years,threshold): """ Function reads PIOMAS binary and converts to standard numpy array. Parameters ---------- directory : string working directory for stored PIOMAS files years : integers years for data files threshold : float mask sea ice thickness amounts < to this value Returns ------- lats : 2d array latitudes lons : 2d array longitudes var : 4d array [year,month,lat,lon] sea ice thickness (m) Usage ----- lats,lons,var = readPiomas(directory,years,threshold) """ print('\n>>> Using readPiomas function!\n') ### Import modules import numpy as np import datetime ### Current times now = datetime.datetime.now() mo = now.month yr = now.year dy = now.day ### Retrieve Grid grid = np.genfromtxt(directory + 'grid.txt') grid = np.reshape(grid,(grid.size)) ### Define Lat/Lon lon = grid[:grid.size//2] lons = np.reshape(lon,(120,360)) lat = grid[grid.size//2:] lats = np.reshape(lat,(120,360)) ### Call variables from PIOMAS files = 'heff' directory = directory + 'Thickness/' ### Read data from binary into numpy arrays var = np.empty((len(years),12,120,360)) print('Currently reading PIOMAS data!') for i in range(len(years)): data = np.fromfile(directory + files + '_%s.H' % (years[i]), dtype = 'float32') ### Reshape into [year,month,lat,lon] months = data.shape[0]//(120*360) if months != 12: lastyearq = np.reshape(data,(months,120,360)) emptymo = np.empty((12-months,120,360)) emptymo[:,:,:] = np.nan lastyear = np.append(lastyearq,emptymo,axis=0) var[i,:,:,:] = lastyear month = datetime.date(yr, months, dy).strftime('%B') print('\nSIT data available through ---> "%s"' % month) print('SIT data available from ---> (%s - %s)' \ % (np.nanmin(years),np.nanmax(years))) elif months == 12: dataq = np.reshape(data,(12,120,360)) var[i,:,:,:] = dataq else: ValueError('Issue with reshaping SIT array from binary') ### Mask out threshold values var[np.where(var < threshold)] = np.nan print('\nMasking SIT data < %s m!' % threshold) print('\n*Completed: Read SIT data!') return lats,lons,var
b7ff3fb95adb33ee351861d6e7a61f0200ee3e39
robertopedroso/euler
/python/problem5.py
421
3.78125
4
from itertools import count def evenlydivisible(n): """Returns whether n is divisible by [1, 20]""" drange = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] # don't call xrange every time for i in drange: if n % i != 0: return False return True if __name__ == "__main__": for i in count(20, 20): # start at 20 and step up by 20 if evenlydivisible(i): print i break
4705d6a0c9fb4122e944c25911d083ed78942c64
rksaxena/leetcode_solutions
/ones_and_zeros.py
1,419
3.78125
4
__author__ = Rohit Kamal Saxena __email__ = rohit_kamal2003@yahoo.com """ In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue. For now, suppose you are a dominator of m 0s and n 1s respectively. On the other hand, there is an array with strings consisting of only 0s and 1s. Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. Each 0 and 1 can be used at most once. Note: The given numbers of 0s and 1s will both not exceed 100 The size of given string array won't exceed 600. Example 1: Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3 Output: 4 """ class Solution(object): def findMaxForm(self, strs, m, n): """ :type strs: List[str] :type m: int :type n: int :rtype: int """ if not strs: return 0 size = len(strs) dp = [[[0] * (n+1) for y in range(m+1)] for x in range(size+1)] for i in range(1, size+1): zeros = strs[i-1].count('0') ones = len(strs[i-1]) - zeros for zi in range(m+1): for oi in range(n+1): taken = -1 if zi >= zeros and oi >= ones: taken = dp[i-1][zi - zeros][oi-ones] + 1 dp[i][zi][oi] = max(dp[i-1][zi][oi], taken) return dp[size][m][n]
7ed8dc438342f221c688a2311e08b81f9c13ae44
andrewhere/MazeGame
/aStar.py
2,758
3.609375
4
# aStar.py # Implementation of the A* search algorithm using # Manhatten distance as heuristc fucntion from utility import * import time def a_star_search(maze, start, goal): neighbors = [(0, 1), (0, -1), (1, 0), (-1, 0)] "(1, 1), (1, -1), (-1, 1), (-1, -1)] " # quick neighbors fiding offset close_list = set() parents = {} # List to hold all parents node_expanded = 0 cost_sofar = 0 g_score = {start: 0} f_score = {start: heuristicFcn(start, goal)} frontier = PriorityQueue() frontier.push(f_score[start], start) parents[start] = None "Start Timer" clk = time.clock() while not frontier.isEmpty(): current = frontier.pop() """ Immediately check if the current node is the goal If this is the goal, we need to back track all the node that we have visted to get the path """ if current == goal: path = [] while current in parents: path.append(current) current = parents[current] cost_sofar += 1 clk_used = time.clock() - clk print("Time Used: ", clk_used, " seconds") return path, node_expanded "If the current node is not our goal, we add it to the close list" close_list.add(current) "Now we need to check all 4 neighbors of the current node" for dx, dy in neighbors: neighbor = current[0] + dx, current[1] + dy g_temp = g_score[current] + heuristicFcn(current, neighbor) f_temp = g_temp + heuristicFcn(neighbor, goal) "Need to make sure that the neighbor location is valid" if 0 <= neighbor[1] < maze.shape[1]: # coordinate validation if 0 <= neighbor[0] < maze.shape[0]: "Check if the intended neighbor is a wall" if maze[neighbor[0], neighbor[1]] == "%": continue else: # if the y-coordinate is not valid continue else: # if the x-coordinate is not valid continue if neighbor in close_list and g_temp >= g_score.get(neighbor, 0): # skip if the node is closed continue if g_temp < g_score.get(neighbor, 0) or (neighbor not in [i[1] for i in frontier.elements]): parents[neighbor] = current g_score[neighbor] = g_temp f_score[neighbor] = f_temp frontier.push(f_score[neighbor], neighbor) node_expanded += 1 else: continue return False
c8e2b4950bcb06b24202b488c6ff52a373c53684
evan886/python
/allpynotes4turtle/eg/ri.py
159
3.859375
4
#-*- coding:utf-8 -*- file_name = input('输入打开的文件名:') f = open(file_name) print('文件的内容是:') for each_line in f: print(each_line)
b45bd68232cae3bc393fffdc5ae9b72a165461ac
nkmashaev/declared_env
/declared_env/_prefixable.py
264
3.53125
4
"""Abstract class with prefix attribute.""" from abc import ABCMeta, abstractmethod class Prefixable(metaclass=ABCMeta): """Abstract class with prefix attribute.""" @property @abstractmethod def prefix(self) -> str: """Prefix string."""
226e06879416c5c58d42fc2d1574a5bdabd06ace
dong-c-git/WSGIServer
/template/programe_celue.py
867
3.65625
4
#coding:utf-8 from abc import ABC,abstractmethod class Strategy(ABC): @abstractmethod def algorithm_interface(self,context): pass class ConcreteStrategyA(): def algorithm_interface(self,context): print("ConcreteStrategyA") class ConcreteStrategyB(Strategy): def algorithm_interface(self,context): print('ConcreteStrategyB') class ConcreteStrategyC(Strategy): def algorithm_interface(self,context): print('ConcreteStrategyc') class Context: def __init__(self,strategy): self.strategy = strategy def context_interface(self): self.strategy.algorithm_interface(self) class Client: @staticmethod def main(): strategy = eval(f'ConcreteStrategy{input()}()') context = Context(strategy) context.context_interface() if __name__ == '__main__': Client.main()
dba97bad9c2359dcaadb611e9b00bf3227494a96
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/nxmgoo002/question1.py
730
4.0625
4
'''this programm checks the palindrome Nxumalo Goodman 09 May 2014''' #this function reverses the string def rev(w): #base case if w == '': return w #returns nothing if there is nothing in the string #recursive step else: return rev(w[1:]) + w[0] #this function checks if the string is the palindrome def chck(w): #if the original string is the same as the reversed string then prints palindrome if w == rev(w): print('Palindrome!') #if the original string is not the same as the reversed string then prints not a palindrome else: print('Not a palindrome!') #prompt a user to enter a string w = input('Enter a string:\n') chck(rev(w))
458003d33ed54e5ce951e7fa29920a2958f715b5
dgpshiva/PythonScripts
/Matrix_BFS.py
1,648
3.609375
4
def findPath(grid, rows, cols): queue = [] visited = [[0 for x in range(0, cols)] for y in range(0, rows)] start = (0, 0, 0) queue.append(start) visited[0][0] = 1 while queue: current = queue.pop() if grid[current[0]][current[1]] == 9: return current[2] else: if current[0]-1 >= 0 and visited[current[0]-1][current[1]] != 1 and grid[current[0]-1][current[1]] != 0: queue.insert(0, (current[0]-1, current[1], current[2]+1)) visited[current[0]-1][current[1]] = 1 if current[1]-1 >= 0 and visited[current[0]][current[1]-1] != 1 and grid[current[0]][current[1]-1] != 0: queue.insert(0, (current[0], current[1]-1, current[2]+1)) visited[current[0]][current[1]-1] = 1 if current[0]+1 < rows and visited[current[0]+1][current[1]] != 1 and grid[current[0]+1][current[1]] != 0: queue.insert(0, (current[0]+1, current[1], current[2]+1)) visited[current[0]+1][current[1]] = 1 if current[1]+1 < cols and visited[current[0]][current[1]+1] != 1 and grid[current[0]][current[1]+1] != 0: queue.insert(0, (current[0], current[1]+1, current[2]+1)) visited[current[0]][current[1]+1] = 1 return -1 if __name__ == '__main__': # grid = [[0, 1, 0], [0, 0, 1], [0, 9, 1]] # print findPath(grid, 3, 3) # #grid = [[0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 9, 1], [0, 0, 0, 0]] # print findPath(grid, 4, 4) grid = [[1, 1, 1, 1], [0, 1, 1, 1], [0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 9, 1]] print findPath(grid, 5, 4)
fe2ba6fee0be809ba576eb07e75cd6aeefe19fb2
rags/playground
/py/exp/common/nodes.py
640
3.5625
4
class Operator: def __init__(self,lhs,rhs): self.lhs = lhs self.rhs = rhs class AddOperator(Operator): def visit(self,visitor): visitor.visitAddOperator(self) class SubstractOperator(Operator): def visit(self,visitor): visitor.visitSubstractOperator(self) class MultiplyOperator(Operator): def visit(self,visitor): visitor.visitMultiplyOperator(self) class DivideOperator(Operator): def visit(self,visitor): visitor.visitDivideOperator(self) class Operand: def __init__(self,num): self.value = num def visit(self,visitor): visitor.visitOperand(self)
41d652aa5a9f6266fa412374375f84e27d3ecb83
FrankMwesigwa/lessons
/python/add.py
352
3.953125
4
while 1: print('Enter a number:') s = input() s = int(s) print ("hello") if s in range(1, 7): if s == 1: print ('Go to ...1') elif s == 2: print ('Go to ...2') elif s == 3: print ('Go to ...3') else: print('party time') else: print('(:-')
bc15206e42dafa502d3d71182900133a11639791
thehimel/data-structures-and-algorithms-udacity
/m03c02-sorting-algorithms/i15e00_sort_012.py
2,155
4.03125
4
""" Problem Statement Write a function that takes an input array (or Python list) consisting of only 0s, 1s, and 2s, and sorts that array in a single traversal. Input: [0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2] Output: [0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2] Note: If we can get the function to put the 0s and 2s in the correct positions, this will aotomatically cause the 1s to be in the correct positions as well. Solution: The idea is to put 0s and 2s in their correct positions, then 1s are automatically placed in their right positions. Initialize next_pos_0 to the first index and next_pos_2 to the last index. We'll keep the 0's at the beginning and 2's at the ending. Thus. 1's will stay in the middle. We search of 0 and 2. If we find a 0, we bring it to it's next_pos_0. If we find a 2, we throw it to it's next_pos_2. For both operations, we swap the values in thoses indexes. Complexity Analysis: TC: O(n) SC: O(1) In-place algorithm. """ def sort_012(input_list): # initialize pointers for next positions of 0 and 2 next_pos_0 = 0 next_pos_2 = len(input_list) - 1 front_index = 0 while front_index <= next_pos_2: if input_list[front_index] == 0: input_list[front_index] = input_list[next_pos_0] input_list[next_pos_0] = 0 next_pos_0 += 1 front_index += 1 elif input_list[front_index] == 2: input_list[front_index] = input_list[next_pos_2] input_list[next_pos_2] = 2 next_pos_2 -= 1 else: front_index += 1 def test_function(test_case): sort_012(test_case) print(test_case) if test_case == sorted(test_case): print("Pass") else: print("Fail") test_case = [0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2] test_function(test_case) test_case = [ 2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1] test_function(test_case) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2] test_case = [2, 2, 0, 0, 2, 1, 0, 2, 2, 1, 1, 1, 0, 1, 2, 0, 2, 0, 1] test_function(test_case) [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]
ea686d384a87e932b95e5289bb8d38cb5044bcdb
rbryan21/ParallelComputing
/Module4/example.py
333
3.859375
4
# Monte Carlo Calculation of Pi from random import * from math import sqrt def main(): "Monte Carlo Calculation of Pi" inside=0 n=1000 for i in range(0, n): x=random() y=random() if sqrt(x*x+y*y)<=1: inside+=1 pi=4*inside/n print(pi) if __name__ == "__main__": print(main.__doc__) main()
992c691839cfb3fe2867637db0aba4e21eaee88b
coolsnake/JupyterNotebook
/new_algs/Number+theoretic+algorithms/Euclidean+algorithm/euklides.py
650
3.8125
4
""" Algorytm Euklidesa ___ _ _ _ _ | __| _| |_| (_)__| |___ ___ _ __ _ _ | _| || | / / | / _` / -_|_-< _ | '_ \ || | |___\_,_|_\_\_|_\__,_\___/__/ (_) | .__/\_, | |_| |__/ Z dedykacja dla Pani Profesor Stajno :) """ a = int(raw_input("Podaj liczbe a: ")) b = int(raw_input("Podaj liczbe b: ")) c = 0 licznik = 1 if b == 0: print("b == 0. Koniec liczenia. NWD wynosi: " + str(a)) exit() while b != 0: print("\n\n\nRunda " + str(licznik)) c = a % b a = b b = c print("a = " + str(a)) print("c = " + str(c)) print("b = " + str(b)) licznik += 1
fc78c8787652766fe6aedad0f9c14214b3865397
atyndall/cits4211
/tools/helper.py
1,143
3.703125
4
import collections UNICODE = True # Unicode support is present in system # The print_multi_board function prints out a representation of the [0..inf] # 2D-array as a set of HEIGHT*WIDTH capital letters (or # if nothing is there). def print_multi_board(a): for row in a: print(''.join(['#' if e == 0 else chr(64 + e) for e in row])) # The print_board function prints out a representation of the [True, False] # 2D-array as a set of HEIGHT*WIDTH empty and filled Unicode squares (or ASCII if there is no support). def print_board(a): global UNICODE for row in a: if UNICODE: try: print(''.join([unichr(9632) if e else unichr(9633) for e in row])) continue except UnicodeEncodeError: # Windows compatibility UNICODE = False print(''.join(['#' if e else '0' for e in row])) # The rall function recursively checks that all lists and sublists of element "a" # have a True value, otherwise it returns False. def rall(a): for i in a: if isinstance(i, collections.Iterable): if not rall(i): return False elif not i: return False return True
054fdd5f28742f4b4534d04a9a30ae14d19ba418
Silocean/Codewars
/7ku_excel_sheet_column_nubmers.py
447
3.890625
4
''' Description: Write a function titleToNumber(title) or title_to_number(title) or titleToNb title ... (depending on the language) that given a column title as it appears in an Excel sheet, returns its corresponding column number. All column titles will be uppercase. ''' def title_to_number(title): #your code here result = 0 for i, x in enumerate(title, 0): result += 26**(len(title)-1-i) * (ord(x)-64) return result
2b449ecd449756a03745f4d6f3876702b01ff77b
mertzjl91/PythonProjects
/Guessthenumber.py
601
4.125
4
import random n=random.randint(1,20) guess = int(input("Enter a number 1 to 20:")) while n != "guess": print() if guess < n: print("Guess is too low, try again!") guess = int(input("Enter a number 1 to 20, better get it right this time!")) elif guess > n: print("Guess is too high, try again!") guess = int(input("Enter a number 1 to 20, better get it right this time, dummy!")) else: print("Oh my god you finally got it that took forever. Thank god! \nCongratulations on your... achievement") break print()
01e9a37af23714762344273e91873693ccd157db
mehtajaghvi/ProjectEuler
/Programs/25_1000Fib.py
596
3.59375
4
################################ #Project Euler #Problem Statement 25 ################################ import time import math #some big number maxNumber=100000000 #max length of the 1000-digit number maxLen=1000 def thou_FibNum(): secondLast=1 last=2 for n in range(1,maxNumber): next=secondLast+last secondLast=last last=next a=str(next) #print(a,len(a)) if (len(a)>=maxLen): break indexFib=(n+3) return indexFib #time for execution of script start_time = time.time() result=thou_FibNum() print(result) print("--- %s seconds ---" % (time.time() - start_time))
33962b6bcc72e025dd1658c180e104d867d56ba5
MohammadRezaG/Loop-Structure
/Loop Structure/Factorial.py
73
3.734375
4
i = int(input()) fact=1 for x in range(1,i+1): fact= fact*x print(fact)
c0581490e44dd2f82d87643719bdf1634bc3e9d2
browncoder98/Python-Projects
/scratches/Selection Sort.py
326
3.828125
4
# Selection Sort: def sort (nums): for i in range(5): minpos = i for j in range (i,6): if nums[j] < nums [minpos]: minpos = j temp = nums[i] nums[i] = nums[minpos] nums[minpos]= temp print(nums) nums = [2,9,6,8,7,10] sort(nums) print(nums)
1dda821f1342a290e60de30988a32358f2fb28c8
wlinco/realpython
/dict.py
345
4.1875
4
my_dict = {"luke":"5/24/19","obiwan":"9/3/09","vader":"9/1/10"} if "yoda" not in my_dict: my_dict["yoda"] = "2/2/2" if "vader" not in my_dict: my_dict["vader"] = "3/3/3" for name in my_dict: print name + " " + my_dict[name] del(my_dict["vader"]) print my_dict other_dict = dict([("luke","1/1/1"), ("vader", "2/2/2")]) print other_dict
3f659e724de8713ab0f610c967d68364fcb27d6d
jasonmcalpin/worldgen
/template/dice.py
1,002
3.921875
4
import random ''' usage: import dice roll = dice.roll(1,6,1,0) roll_2d6 = dice.roll(1,6,2,0) help(dice.roll) help(dice.flux) Notes: Needs tests. Can add shortcuts like dice.roll_2d6 or whatever. ''' def roll(die_min=1, die_max=6, die_count=1, modifier=0): ''' (int, int, int, int) -> int roll(die_minimum, die_maximum, die_count, modifier) Takes lowest number on the die, highest number, number of dice, and any modifiers. Returns an int with the random result. roll(1, 6, 2, 0) A number between 2-12 roll(1,100, 1, 0) A number between 1-100 my_2d6 = roll(1,6,2,0) my_d100 = roll(1,100, 1, 0) print("Rolled %d on 2d6 and %d on 1d100!" % (my_2d6, my_d100)) ''' result = modifier for x in range(die_count): result += random.randint(die_min, die_max) return result def flux(): ''' () -> int flux() Returns an int between -5 and 5, inclusive. Flux is used in T5. ''' flux = 0 flux = roll(1,6,1,0) - roll(1,6,1,0) return flux
63c91cd2ce45d0787004c72a13fa6fcb8d3bbc54
marinasmonteiro/Subjet5
/Exercice AND andOR.py
630
4.0625
4
a=input("Which language are you using?") if a=="Phython" or a=="JavaScript": print("It is a good course") else: print("take thinking and creating with Code courses :)") b=input("which language are you using?") if b=="Phython": print("this is Thinking and Creating with Code courses!") elif b=="JavaScript": print("this is Thinking and Creating with Code courses!") else: print("good try... take a suscription with EPFL extension school!") c=input("Choose a number:") d=input("Choose a color:") result=int(c) if result>10 or d=="blue": print("the test is true") else: print("the test is false")
95d32fa17849e83cf630ff2648104f55d5f9b991
claraqqqq/l_e_e_t
/20_valid_parentheses.py
657
4.03125
4
# Valid Parentheses ''' Given a string containing just the characters '(', ')','{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[] {}" are all valid but "(]" and "([)]" are not. ''' class Solution: # @param {string} s # @return {boolean} def isValid(self, s): lookup = {'(':')', '[':']', '{':'}'} stack = [] for char in s: if char in lookup: stack.append(char) else: if len(stack) == 0 or lookup[stack.pop()] != char: return False return len(stack) == 0