blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
bdfb9a6086705fc23c629a16c1b1db7983e7d2a3
CODEvelopPSU/Lesson-2
/DragonAdventure.py
1,498
4.15625
4
import time print("Welcome to the Dragon Cave Adventure!") time.sleep(2) print("You awake inside a cave and see a dragon!") time.sleep(2) print("It looks like it's asleep...") time.sleep(1) print("You look for a way out. Maybe you could climb over the dragon's tail...") choice1 = int(input("1 - Explore the cave more. 2 - Climb over the dragon's tail")) if choice1 == 1: print("You feel around in the darkness, but you don't find anything useful.") elif choice1 == 2: print("You try to gently climb over the dragon's tail, but it starts to move and growl. You back away.") time.sleep(1) print("The dragon shuffles, and you see an opening where you can squeeze by and escape the cave.") time.sleep(2) print("You hear a noise coming from your right.") time.sleep(1) choice2 = int(input("1 - Investigate the noise. 2 - Try to sneak past the dragon.")) if choice2 == 1: print("You go to investigate and the noise stops, but you see a strange light") time.sleep(1) choice3 = int(input("1 - Continue on. 2 - Head back.")) if choice3 == 1: print("You get closer to the light and see that it's actually a passage to the outside. Hooray!") elif choice3 == 2: print("You turn around to go back...and see the dragon staring right at you. GAME OVER") elif choice2 == 2: print("Slowly tou edge past the dragon, careful not to make a sound.") time.sleep(2) print("You emerge from the cave and see a rescue party approaching you. Hooray!")
fbb1e8227bc21a0c21e3ac074f45a52ad030131a
solsword/dunyazad
/prototypes/simplified/verbs.py
2,181
3.984375
4
""" verbs.py Code for handling verbs and conjugation. """ from utils import * from eng_base import * def base(verb): return verb def add_s(verb): if ( any(verb.endswith(e) for e in ["s", "z", "ch", "sh"]) or verb[-2] in consonants and verb[-1] == "o" ): return verb + "es" elif verb[-2] in consonants and verb[-1] == "y": return verb[:-1] + "ies" else: return verb + "s" def add_ed(verb): # TODO: Final consonant doubling? if verb.endswith("e"): return verb + "d" elif verb[-2] in consonants and verb[-1] == "y": return verb[:-1] + "ied" else: return verb + "ed" def add_ing(verb): # TODO: Consonant doubling here as well? if verb.endswith("ie"): return verb[:-2] + "ying" elif verb.endswith("e") and len(verb) > 2: return verb[:-1] + "ing" else: return verb + "ing" CONJ_DEFAULTS = [ ("present", "singular", "first", base), ("present", "singular", "second", base), ("present", "singular", "third", add_s), ("present", "plural", "any", base), ("past", "any", "any", add_ed), ("infinitive", "any", "any", base), ("imperative", "any", "any", base), ("present participle", "any", "any", add_ing), ("past participle", "any", "any", add_ed), ] IRREGULAR = { "be": [ ("present", "singular", "first", "am"), ("present", "singular", "second", "are"), ("present", "singular", "third", "is"), ("present", "plural", "any", "are"), ("past", "singular", "first", "was"), ("past", "singular", "second", "were"), ("past", "singular", "third", "was"), ("past", "plural", "third", "were"), ("past participle", "any", "any", "been"), ] } def conjugation(verb, tns, nmbr, per): """ Figures out the conjugation of the given verb and returns it. """ lookup = (tns, nmbr, per) if verb in IRREGULAR: irr = table_match(IRREGULAR[verb], lookup) if irr: return irr # else fall out: return table_match(CONJ_DEFAULTS, lookup)(verb) def conj_ref(thing, verb, tns): """ Uses the given noun to help conjugate the given verb (but still needs a tense of course). """ return conjugation(verb, tns, thing.number, thing.person)
f46b1a6b49bcd8bf93b8397531f39e50964dcbf0
augus2349/CYPFranciscoMC
/libro/ejemplo2_4.py
146
3.546875
4
SUE = float(input("ingrese el sueldo ")) if SUE < 1000: NSUE = SUE * 1.15 else: NSUE = SUE * 1.12 print(f"el nuevo sueldo es: { NSUE }")
46f567222aefe95f8dc2d699a94de6ce003823f3
jxie0755/Learning_Python
/ProgrammingCourses/PythonCrashCourse/C6_Dict_set.py
646
3.703125
4
favorite_languages = { "jen": "python", "sarah": "c", "edward": "ruby", "phil": "python", } for name in favorite_languages.keys(): # 可以不写keys,默认也是寻找keys print(name.title()) print() for language in favorite_languages.values(): # value必须要标明 print(language.title()) # 这样会出现重复的language, 可以使用set print() # set跟list很像,但是要求每个item不能重复 for language in set(favorite_languages.values()): print(language.title()) print() for name in sorted(favorite_languages.keys()): # sorted临时排序 print(name.title() + ", thank you for taking the poll.")
4354bb2ea1c70a67c56590218a5d4e59e51a90bf
productivityboyz/Blackjack
/card.py
2,555
4.375
4
"""This module contains the 'Card' class and related methods. """ import pandas as pd import numpy as np class Card: """ A class defining the properties of a card object. On initialisation, the internal attributes for the suit, rank, value and deck number of the Card are defined based on the input variables. By default, cards are created face up. """ def __init__(self, input_suit, input_rank, input_rank_short, input_value, input_deck_num): self._suit = input_suit self._rank = input_rank self._rank_short = input_rank_short self._value = input_value self._deck_num = input_deck_num + 1 self._face_up = True # This logical stores whether the card is face up (True) or face down (False) def print_all_card_details(self): """ Prints the key attributes of a Card object, e.g.: 'Ace of diamonds (Value = 1 or 11, Deck# = 3)' """ if self._rank == 'Ace': print('{} of {} (Value = {} or {}, Deck# = {})' .format(self._rank, self._suit.lower(), str(self._value[0]), str(self._value[1]), str(self._deck_num))) else: print('{} of {} (Value = {}, Deck# = {})' .format(self._rank, self._suit.lower(), str(self._value), str(self._deck_num))) def flip_card(self): """ 'Flips' the card object by setting '_face_up' to the opposite boolean value """ self._face_up = not self._face_up def return_card_value(self): """ Returns the value of the target card. Value can be a tuple (for an Ace) or an integer value (all other cards). """ if self._face_up: return self._value # TODO: Need to make this sensitive to orientation of card. else: return '*-*' def return_card_orientation(self): """ Returns the current card orientation as a boolean (face-up = True, face-down = False) """ return self._face_up def return_shorthand_card_details(self): """ If card is currently face-up, returns details in shorthand notation, e.g.: 'K-H' denoting the King of hearts. If card is face-down, returns a consistent string to communicate this to the player.""" if self._face_up: return '{}-{}'.format(self._rank_short, self._suit[0]) else: return '*-*'
0170145561ba13e15cb46c6cadf22169f1770109
davdevor/AIProject
/src/Oracle/Oracle.py
662
3.734375
4
import json import random def readPoems(): word = input("Enter a topic: ") word = str.lower(word) file = open('poetry.json',encoding = 'UTF-8') data = json.load(file) poems = [] for x in data: if(str.lower(x['classification'])==word): poems.append(x['text']) continue for y in x['keywords']: if(word==str.lower(y)): poems.append(x['text']) continue if(len(poems) ==0): print("No poem generated") else: text = poems[random.randrange(0, len(poems)-1)] for s in text: print(s) def main(): readPoems() main()
04f904df7f6abcaf7eb692fa7f16a2f9ba49f102
professional2684/DK
/BinaryTree.py
1,764
3.875
4
class Custom_Node: def __init__(self, data): self.left = None self.right = None self.data = data def insert_tree(self, data): if self.data == None: self.data = data elif data > self.data: if self.right is None: self.right = Custom_Node(data) else: self.right.insert_tree(data) else: if self.left is None: self.left = Custom_Node(data) else: self.left.insert_tree(data) def find_item(self, data): if self.data == data: print('item found') if data < self.data: if self.left: self.left.find_item(data) else: print('not found') if data > self.data: if self.right: self.right.find_item(data) else: print('not found') def delete_item(self): pass def PrintTree(self): # print('\n', self.data) if self.left: self.left.PrintTree() print('\n', self.data) if self.right: self.right.PrintTree() root = Custom_Node(10) root.insert_tree(8) root.insert_tree(14) root.insert_tree(4) # root.insert_tree(20) root.insert_tree(16) root.insert_tree(5) root.PrintTree() root.find_item(8) root.find_item(20) from binarytree import tree, bst, heap, Node root = Node(1) root.left = Node(2) root.right = Node(3) root.left.right = Node(4) root.left.left = Node(5) root.left.right.left = Node(7) root.left.left.right = Node(8) # print(root)
798f43b157d8124b1c2788aa552a93c8cc374a69
ilarysz/python_course_projects
/object_oriented_programming/oop/composition.py
358
3.765625
4
class Leg: pass class Back: pass class Chair: def __init__(self, num_legs): self.legs = [Leg() for number in range(num_legs)] self.back = Back() def __repr__(self): return "It's a chair with: \n" \ "{} legs and \n" \ "{} back.".format(len(self.legs), 1) print((Chair(num_legs=5)))
e254264a20f73e2c70ad1a5154770877d31dae16
SoyUnaFuente/c3e2
/main.py
322
4.0625
4
name = str(input("Enter your name: ")) age = int(input("Enter your age: ")) ticket_price = 0 if age <= 4: ticket_price = 0 elif age <= 18: ticket_price = 1.50 elif age >= 60: ticket_price = 1 else: ticket_price = 2 print(f"The Customer: {name} has: {age} years and his ticket cost is: $ {ticket_price}")
5e1fbbed2f038ea59f7531ca2b8e1511ca39e6d9
YanSongSong/learngit
/Desktop/python-workplace/从1加到100的递归写法.py
176
3.671875
4
#从1加到100的递归写法 def recurrency(x,result): if(x==1): return result+1 else: return recurrency(x-1,result+x) print(recurrency(100,0))
d1eb7447eeb2042c9b1ba57c40e872db884244e6
TanmayNakhate/headFirstPython
/sanfoundry.com/sanFoundryDict.py
1,329
3.859375
4
class dictProg(): def addinfo(self): """Python Program to Add a Key-Value Pair to the Dictionary""" newdict ={1:"aa",2:"bb",3:"cc",4:"dd",5:"ee"} newdict[6]="ff" newdict.update({7:"gg"}) print(newdict) def dict_combo(self): newdict = {1: "aa", 2: "bb", 3: "cc", 4: "dd", 5: "ee"} newdict1 = {"a": 11, "b": "22", "c": 33, "d": 44, "e": 55} newdict.update(newdict1) print(newdict) def keyexist(self): k = 7 newdict = {1: "aa", 2: "bb", 3: "cc", 4: "dd", 5: "ee"} if k in newdict.keys(): print("Key Exists") else: print("Key not found") def generateDict(self): d = {} n=10 for i in range(1,n+1): d.update({i:i*i}) print(d) def dictSum(self): newdict1 = {"a": 10, "b": "20", "c": 30, "d": 40, "e": 50} print(sum(map(int,newdict1.values()))) def dictmulti(self): newdict1 = {"a": 10, "b": "20", "c": 30, "d": 40, "e": 50} multi = 1 #print(sum(map(int,newdict1.values()))) for value in newdict1.values(): multi = int(value) * multi print(multi) obj = dictProg() #obj.addinfo() #obj.dict_combo() #obj.keyexist() #obj.generateDict() #obj.dictSum() obj.dictmulti()
806824333df95a288086699d34e10c192c978f24
Matthiosso/snake-game
/snake/game/items/snake.py
950
3.796875
4
class Snake: def __init__(self, pos_x, pos_y, size=1): self.body = [[pos_x, pos_y]] self.size = size def head(self): return self.body[-1] def headx(self): return self.head()[0] def heady(self): return self.head()[1] def move(self, direction): if len(direction) < 2: raise Exception('La direction donnée est incorrecte : ' + direction) self.body.append([self.headx() + direction[0], self.heady() + direction[1]]) # Supprime la queue lors d'un déplacement sans manger if len(self.body) > self.size: del self.body[0] # Cas du serpent qui se mord la queue for body_part in self.body[:-1]: if body_part == self.head(): return False return True def grow_up(self): self.size += 1 def __str__(self): return 'Snake ({}) : {}'.format(self.size, self.body)
d9a2b6c105a1362001a9b1903b38a68f38322ee5
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/mclemi002/question2.py
655
3.53125
4
#emile mclennan #assignment 6 #Q2 import math vectA=input('Enter vector A:\n').split(" ") vectB=input('Enter vector B:\n').split(" ") a1 =eval(vectA[0]) #isolate values in array a2= eval(vectA[1]) a3= eval(vectA[2]) b1= eval(vectB[0]) b2= eval(vectB[1]) b3= eval(vectB[2]) calc1 = [a1+b1, a2+b2, a3+b3] #add items calc2 = (a1*b1)+ (a2*b2)+ (a3*b3) #dot multiply calc3 = round(math.sqrt((a1**2)+(a2**2)+(a3**2)),2) #normalise array 1 calc4 = round(math.sqrt((b1**2)+(b2**2)+(b3**2)),2) #normailse array 2 Y="|A| = {0:0.2f}".format(calc3) Z="|B| = {0:0.2f}".format(calc4) print('A+B =', calc1) print('A.B =', calc2) print(Y) print(Z)
cc3352a8cdd74c2c5fa903fdbf7308fe83300b87
abhilampard/SUDOKU-using-Backtracking
/sudoku_create.py
2,469
3.671875
4
import random sudoku=[[0 for i in range(9)] for j in range(9)] sudoku=[[1,2,3,4,5,6,7,8,9],[4,5,6,7,8,9,1,2,3],[7,8,9,1,2,3,4,5,6],[2,3,4,5,6,7,8,9,1],[5,6,7,8,9,1,2,3,4],[8,9,1,2,3,4,5,6,7],[3,4,5,6,7,8,9,1,2],[6,7,8,9,1,2,3,4,5],[9,1,2,3,4,5,6,7,8]] def disp(): for i in range(0,9): for j in range(0,9): if(sudoku[i][j]!=0): print "|",sudoku[i][j], else: print "| ", if(j==2 or j==5): print "|*", print "|\n-------------------------------------------" if(i==2 or i==5): print "*******************************************" def swap(): #swapping columns count=5 while(count>1): sub=random.randrange(1,3,1) count=count-sub j1=random.randrange(0,3,1) j2=random.randrange(0,3,1) for i in range(0,9): sudoku[i][j1],sudoku[i][j2]=sudoku[i][j2],sudoku[i][j1] count=5 while(count>1): sub=random.randrange(1,3,1) count=count-sub j1=random.randrange(3,6,1) j2=random.randrange(3,6,1) for i in range(0,9): sudoku[i][j1],sudoku[i][j2]=sudoku[i][j2],sudoku[i][j1] count=5 while(count>1): sub=random.randrange(1,3,1) count=count-sub j1=random.randrange(6,9,1) j2=random.randrange(6,9,1) for i in range(0,9): sudoku[i][j1],sudoku[i][j2]=sudoku[i][j2],sudoku[i][j1] def easy_gen(): k=0; while(k<40): for i in range(0,9): #deleting random elements from row(max 20) count=3 while(count>1): sub=random.randrange(1,3,1) j=random.randrange(0,9,1) count=count-sub sudoku[i][j]=0 k+=1 for i in range(0,9): #deleting random elements from column(max 20) count=7 while(count>1): sub=random.randrange(1,3,1) j=random.randrange(0,9,1) if(sudoku[j][i]!=0): k+=1 sudoku[j][i]=0 count=count-sub else: count=count-1 if(k>40): break swap() def hard_gen(): k=0; while(k<65): for i in range(0,9): #deleting random elements from row(max 20) count=3 while(count>1): sub=random.randrange(1,3,1) j=random.randrange(0,9,1) count=count-sub sudoku[i][j]=0 k+=1 for i in range(0,9): #deleting random elements from column(max 20) count=7 while(count>1): sub=random.randrange(1,3,1) j=random.randrange(0,9,1) if(sudoku[j][i]!=0): k+=1 sudoku[j][i]=0 count=count-sub else: count=count-1 if(k>65): break swap() def sudoku_input(): for i in range(0,9): for j in range(0,9): print "Enter Value for(",i+1,",",j+1,"):", sudoku[i][j]=input()
78bc18dab2c2c67d2cfe70e9a5431bbd5b1c9c89
aifulislam/Python_Demo_Five_Part
/program19.py
3,478
4.21875
4
#19/October/2020-------- #Python---Classes and Objeects---- #Iterators---------- print("Iterators-----------") mytuple = ("Apple", "banana", "cherry") myit = iter(mytuple) print(next(myit)) print(next(myit)) print(next(myit)) #Iterators--------- print("Iterators-----------") student = ("Arif","Tamim","Nazim") weAre = iter(student) print(next(weAre)) print(next(weAre)) print(next(weAre)) #Iterators--------- print("Iterators-----------") me = ("Arif") weAre = iter(me) print(next(weAre)) print(next(weAre)) print(next(weAre)) print(next(weAre)) #Looping an Iterators--------- print("Looping an Iterators----------") student = ("Arif", "Tamim", "Nazim") for x in student: print(x) #Looping an Iterators--------- print("Looping an Iterators----------") mytuple = ("Apple", "banana", "cherry") for x in mytuple: print(x) #Looping an Iterators--------- print("Looping an Iterators----------") mytuple = ("Ariful Islam") for x in mytuple: print(x) #Create an Iterators by function--------- print("Create an Iterators by function----------") class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): x = self.a self.a += 1 return x myclass = MyNumbers() myiter = iter(myclass) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter)) #Stopiteration an Iterators by function--------- print("Stopiteration an Iterators by function----------") class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20: x = self.a self.a += 1 return x else: raise StopIteration myclass = MyNumbers() myiter = iter(myclass) for x in myiter: print(x) #Method_Overriding----------- print("Method_Overriding--------") class Phone: def __init__(self): print("I am in Phone class") class samsung(Phone): def __init__(self): super().__init__() print("I am in samsung class") s = samsung() #Method_Overriding----------- class me: def __init__(self): print("I am Ariful Islam") class who: def __init__(self): super().__init__() print("He is Tamim Iqbal") w = who() #A practical example of inheritance--------- class Shape: def __init__(self,dim1,dim2): self.dim1 = dim1 self.dim2 = dim2 def area(self): print("I am area method of shape class") class Triangle(Shape): def area(self): area = 0.5 * self.dim1 * self.dim2 print("Area of Triangle : ",area) class Rectangle(Shape): def area(self): area = self.dim1 * self.dim2 print("Area of Rectangle : ",area) t1 = Triangle(20,30) t1.area() r1 = Rectangle(20,30) r1.area() #A practical example of inheritance--------- class shape: def __init__(self,num1,num2): self.num1 = num1 self.num2 = num2 def area(self): print("I am in main class") class triangle(shape): def area(self): area = 0.5 * self.num1 * self.num2 print("Area of Triangle : ",area) class rectangle(shape): def area(self): area = self.num1 * self.num2 print("Area of Rectangle : ",area) t1 = triangle(20,30) t1.area() r1 = rectangle(20,30) r1.area()
701a8b5fac3a6021d7ac42aa800e18363a76a732
Nikhitha913/Datavisualization_ISM6419
/week8ass8-3.py
538
3.78125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import pandas as pd import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') Location = "datasets/gradedata.csv" df = pd.read_csv(Location) df.head() # In[9]: plt.scatter(df['hours'], df['grade'],color= 'red', alpha =0.1) plt.xlabel("Hours") plt.ylabel("Grades of students") plt.title("Scatter plot") # There is a pattern present in the data. As the number of hours increases the grades of the students also increased. # In[ ]:
c0b493e807568f3c7a84f00ba3aff49ffc3c7e8e
KaynRO/Teme-Poli
/IC/lab2/ex1.py
761
3.8125
4
from caesar import * def decrypt(ciphertext): for key in range(28): plaintext = '' for char in ciphertext: value = chr(ord(char) - key) if ord(value) < 65: value = chr(90 - (65 - ord(value)) + 1) plaintext +=value if "YOU" in plaintext: print("[+] Found valid key, " + str(key)) return plaintext if "THE" in plaintext: print("[+] Found valid key, " + str(key)) return plaintext def main(): ciphertexts = [] with open("msg_ex1.txt", 'r') as f: for line in f.readlines(): ciphertexts.append(line[:-1]) for c in ciphertexts: print(decrypt(c)) if __name__ == "__main__": main()
f017615d033168fc9b9492791ddf20715d8e80e2
Jiezhi/myleetcode
/src/429-N-aryTreeLevelOrderTraversal.py
2,746
3.703125
4
#!/usr/bin/env python """ CREATED AT: 2021/8/6 Des: https://leetcode.com/problems/n-ary-tree-level-order-traversal/ https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/613/week-1-august-1st-august-7th/3871/ GITHUB: https://github.com/Jiezhi/myleetcode """ from typing import List from ntree_node import Node class Solution: def levelOrder2(self, root: 'Node') -> List[List[int]]: """ 执行用时:44 ms, 在所有 Python3 提交中击败了98.00%的用户 内存消耗:16.9 MB, 在所有 Python3 提交中击败了36.93%的用户 The height of the n-ary tree is less than or equal to 1000 The total number of nodes is between [0, 104] """ if not root: return [] cur_level = [root] ret = [] while cur_level: new_level = [] ret.append([x.val for x in cur_level]) for node in cur_level: if node.children: new_level += node.children cur_level = new_level return ret def levelOrder(self, root: 'Node') -> List[List[int]]: """ 38 / 38 test cases passed. Status: Accepted Runtime: 44 ms Memory Usage: 16.1 MB :param root: :return: """ if root is None or root.val is None: return [] level_node = [[root]] current_level = 0 while True: child_level_nodes = [] for n in level_node[current_level]: if n is None or n.children is None: continue for child in n.children: child_level_nodes.append(child) if child_level_nodes: current_level += 1 level_node.append(child_level_nodes) else: # if current_level is None or empty, then there's no node left to get break ret = [[x.val for x in level] for level in level_node] return ret def test(): assert Solution().levelOrder(Node()) == [] assert Solution().levelOrder(Node(val=1)) == [[1]] assert Solution().levelOrder2(Node(val=1)) == [[1]] # TODO build nary tree from list # [0,null,10,2,null,1,9,1,null,2,0,4,2,null,6,8,0,null,9,10,null,3,1,7,null,9,8,1,2,6,null,6,7,10,null,7,null,null,4,null,4,10,8,7,10,null,null,6,0,null,3,null,8,7,3,null,8,null,0,7,3,null,null,null,0,4,4,2,null,9,5,1,4,0,null,1,4,9,10,3,null,null,7,7,0,8,1,null,3,2,10,null,2,4,0] # [[0],[10,2],[1,9,1,2,0,4,2],[6,8,0,9,10,3,1,7,9,8,1,2,6,6,7,10,7],[4,4,10,8,7,10,6,0,3,8,7,3,8,0,7,3,0,4,4,2,9,5,1,4,0,1,4,9,10,3,7,7,0,8,1,3,2,10,2,4,0]] if __name__ == '__main__': test()
068b2ceee247c1790fdbdf9d3dc9464d58a30b36
shreyasabharwal/Data-Structures-and-Algorithms
/Trees/4.4CheckBalanced.py
1,242
4.1875
4
'''4.4 Check Balanced: Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one. ''' import math from TreesBasicOperations import Node def checkHeight(root): # base case if root is None: return -1 leftHeight = checkHeight(root.left) rightHeight = checkHeight(root.right) heightDiff = abs(leftHeight-rightHeight) if heightDiff > 1: return math.inf else: return max(leftHeight, rightHeight)+1 def checkBalanced(root): if checkHeight(root) != math.inf: return True else: return False if __name__ == "__main__": # check for balanced tree new_node = Node(40) new_node.insert(60) new_node.insert(10) new_node.insert(5) new_node.insert(15) new_node.insert(45) print(checkBalanced(new_node)) # check for unbalanced tree node1 = Node(1) node1.left = Node(2) node1.left.left = Node(3) node1.left.left.left = Node(4) node1.right = Node(2) node1.right.right = Node(3) node1.right.right.right = Node(4) print(checkBalanced(node1))
77c31251013c0c5697f05d2b627799175f56c838
ayanez16/Tarea-1-Estructura
/Ejercicio6.py
500
3.5
4
#Dado el sueldo de un empleado, encontrar el nuevo sueldo si obtiene un aumento del 10% si su sueldo es inferior a $600, en caso contrario #no tendra aumento. class Ejercicio6: def __init__(self): pass def run(): suel = float(input("Ingrese el sueldo del empleado")) if suel <=600: n=suel+suel*0.10 print() else: s=suel print() print(n,"$") run()
16b0f7617bf462dc06661dacbbb06f3d402aea60
nitinjugal17/PythonPuzzle
/test.py
1,781
3.765625
4
# -*- coding: utf-8 -*- from random import randint import sys # getting 10000 digit number using randint rand_number = randint(10,9999**5630) #print 'Random String Type :',type(rand_number) #print 'Random String :',rand_number #checking for the size of randint #print 'Random String Length :',sys.getsizeof(rand_number) #converting Long int to string for spliting as long doesn't support silicing rand_number = str(rand_number) #print 'Checking Type as String :',type(rand_number) #print 'Printing String :',rand_number last_index = 0 number_list = [] # creating a list of 4 digit number using silicing of string for first_index in range(0,10004,4): number_list.append(rand_number[last_index:first_index]) last_index = first_index # delete first index as it is empty while creating a new empty list del number_list[:1] #print 'Print Length of List :',len(number_list) #print 'Printing the list Values :',number_list sum_dict = {} # iterating over list and saving the sum of digits in a form of # dict_key = to get the number # dict_value = to get the sum of number for num in number_list: dict_key = num number_split = list(num) dict_value = 1 for digit in number_split: digit = int(digit) dict_value = dict_value*digit sum_dict[dict_key] = dict_value #print 'Printing Dictionary :',sum_dict checksum_list = [] # appending all the sum values to list for key,value in sum_dict.iteritems(): checksum_list.append(value) #print "CheckSum List:" , checksum_list #getting max value from the list max_value = max(checksum_list) print "Max Value" , max_value #Checking the Key from the highest value for key,value in sum_dict.iteritems(): if max_value == value: print 'Existing Number From Random List:',key
0b93ac1d2910f037beb008f87b731a41b2a07fec
CleverParty/containers
/algos/squareConvergents.py
1,022
3.96875
4
import sys from fractions import Fraction sys.setrecursionlimit(10000) a = 2 root = a**2 def convergent(num): base = 1 if num == 0: return False elif num > 1000 : return None num -= 1 sumCon = base +1/(1/2 + convergent(num)) # this just calculates the convergence recursively, for full solution it would be better to find numerator and denominator seperatelty in a for/while loop return sumCon def numeratorDenomenatorForm(): numerator = 3 denominator = 2 count = 0 for _ in range(0,1000): # print(f'{numerator} and {denomenator}') """ if(i==0): n = numerator + nextnumerator """ denominator = numerator + denominator numerator = denominator + 2*denominator # print(numerator) if(len(str(numerator)) > len(str(denominator))): count += 1 return count print(convergent(10)) print(f'the number of fractions with more digits in numerator than denomenator are: {numeratorDenomenatorForm()}')
64119ca1ec4197d7ac4a4f95c3eb517876ef4e25
jiangbo721/test
/interview.py
1,672
3.953125
4
# -*- coding:utf-8 -*- # @project: test # @author: liujiangbo # @file: interview.py # @ide: PyCharm # @time: 2019-04-09 15:19 def SepPositiveNegative(test_list): """ 将数组里的负数排在数组的前面,正数排在数组的后面。但不改变原先负数和正数的排列顺序。 """ if len(test_list) <= 1: return test_list for _ in range(len(test_list)): for i in range(len(test_list)): if test_list[i] > 0 and i < len(test_list) - 1: if test_list[i + 1] < 0: test_list[i], test_list[i + 1] = test_list[i + 1], test_list[i] print test_list SepPositiveNegative([-5, 2, -3, 4, -8, -9, 1, 3, -10]) def sort_stack_by_stack(test_list): """ 用一个栈实现另一个栈的排序 :param list test_list: :return: """ temp = [] while test_list: current = test_list.pop() while temp and temp[-1] < current: test_list.append(temp.pop()) temp.append(current) # 将临时的栈倒出来 while temp: test_list.append(temp.pop()) print test_list sort_stack_by_stack([-5, 2, -3, 4, -8, -9, 1, 3, -10]) def check_parenthesis(test_str): """ 检查是否括号平衡 :param str test_str: :return: """ left_pattern = '({[' right_pattern = ')}]' stack = [] for i in test_str: if i in left_pattern: stack.append(i) if i in right_pattern: last = stack.pop() if right_pattern.index(i) != left_pattern.index(last): return False else: return True print check_parenthesis('{}{}()([])')
fe8383297dcb89e1ae938644dda3a47a6860cfbf
group6BCS1/BCS-2021
/src/chapter4/exercise6.py
509
4.0625
4
x = (input("enters hours")) y = (input("enters rate")) def compute_pay(hours, rate): """The try block ensures that the user enters a value between from 0-1 otherwise an error message pops up""" try: hours = float(x) rate = float(y) if hours <= 40: pay= float(hours * rate) else: pay = float(40 * rate + (hours - 40) * 1.5 * rate) return pay except ValueError: return "INVALID ENTRY" pay = compute_pay(x, y) print(pay)
fc49880fbc716444c749b666f7245402442c8a14
paulocesarcsdev/ExerciciosPython
/2-EstruturaDeDecisao/9.py
1,118
4.40625
4
# Faça um Programa que leia três números e mostre-os em ordem decrescente. numeroUm = int(input('Numero um: ')) numeroDois = int(input('Numero dois: ')) numeroTres = int(input('Numero tres: ')) # Exibe o maior if(numeroUm > numeroDois and numeroUm > numeroTres): print("Numero um maior", numeroUm) if(numeroDois > numeroUm and numeroDois > numeroTres): print('Numero dois maior', numeroDois) if(numeroTres > numeroUm and numeroTres > numeroDois): print('Numero tres maior', numeroTres) # Exibe numero do meio if(numeroUm < numeroDois and numeroUm > numeroTres): print("Numero um meio", numeroUm) if(numeroDois < numeroUm and numeroDois > numeroTres): print('Numero dois meio', numeroDois) if(numeroTres < numeroUm and numeroTres > numeroDois): print('Numero tres meio', numeroTres) # Exibe o menor if(numeroUm < numeroDois and numeroUm < numeroTres): print("Numero um menor", numeroUm) if(numeroDois < numeroUm and numeroDois < numeroTres): print('Numero dois menor', numeroDois) if(numeroTres < numeroUm and numeroTres < numeroDois): print('Numero tres menor', numeroTres)
05a4a46e96103dba292866aba9831b4a7d57bbe9
Ensiss/snippets
/dailyprogrammer/180/Easy/looknsay.py
485
3.734375
4
import sys def lookNsay(s, n): if n <= 0: return s nstr = "" count = 0 prev = "\0" for c in s: if c != prev and count: nstr += str(count) + prev count = 0 count += 1 prev = c nstr += str(count) + prev return (lookNsay(nstr, n - 1)) if len(sys.argv) < 2: print "Usage: python looknsay.py <iterations> [seed]" exit() print lookNsay("1" if len(sys.argv) < 3 else sys.argv[2], int(sys.argv[1]))
ef16fa6a312e71fdb5184f044beab2b78be0fac3
achillis2/Leetcode-1
/wip/base/mylist.py
946
3.8125
4
# 数组 li = [1, 2, 3] for i in li: print(i) for i in range(len(li)): print(li[i]) #append(self, object, /) li.append(4) #copy(self, /) ##相当于li2 = li[:] li2 = li.copy() #extend(self, iterable, /) ##前者合并可迭代对象 li2.extend(li) #index(self, value, start=0, stop=9223372036854775807, /) ##通过元素值查找元素下标(元素值,开始坐标=0,结束坐标=无穷大) ## li2 list search the element 2 starting from position 4 to position 7 li2.index(2,4,7) #count(self, value, /) li2.count(1) #insert(self, index, object, /) # 7 is inserted before index 1 li2.insert(1,7) #pop(self, index=-1, /) # remove the second last element # return the removed item li2.pop(-2) #remove(self, value, /) # removes the first matching element 2. The second is not removed. li2.remove(2) #reverse(self, /) li2.reverse() #sort(self, /, *, key=None, reverse=False) li2.sort(reverse=True) #clear(self, /) li2.clear()
f6428de468ea366d08af27782302df49064f88d7
Arnav-17/Project-Euler-Codes
/Problem 19.py
1,763
3.515625
4
days = 0 a = 0 b = [] for year in range(1901, 2001): if year % 4 == 0: for month in range(1, 13): if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12: for date in range(1, 32): days += 1 a = days % 7 if date == 1 and a == 6: b.append(date) elif month == 4 or month == 6 or month == 9 or month == 11: for date in range(1, 31): days += 1 a = days % 7 if date == 1 and a == 6: b.append(date) else: for date in range(1, 30): days += 1 a = days % 7 if date == 1 and a == 6: b.append(date) else: for month in range(1, 13): if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12: for date in range(1, 32): days += 1 a = days % 7 if date == 1 and a == 6: b.append(date) elif month == 4 or month == 6 or month == 9 or month == 11: for date in range(1, 31): days += 1 a = days % 7 if date == 1 and a == 6: b.append(date) elif month == 2: for date in range(1, 29): days += 1 a = days % 7 if date == 1 and a == 6: b.append(date) print(len(b))
5f0a34b78f9de3cc93f2f375b63093c905d5e8c4
tejavarma-twl/python2
/loops.py
657
3.96875
4
a = 1 while a<=5: b = 1 while b<=5: print(b,end=" ") b += 1 a += 1 print("") a = 1 while a<=5: b = 1 while b<=5: print(a,end=" ") b += 1 a += 1 print("") a = 5 while a>=1: b = 1 while b<=a: print(b,end=" ") b += 1 a -= 1 print("") a = 1 while a<=5: b = 1 while b<=a: print(b,end=" ") b += 1 a += 1 print("") a = 1 while a<=5: b = 5 while b>=a: print(b,end=" ") b -= 1 a += 1 print("") a = 5 while a>=1: b = 5 while b>=a: print(b,end=" ") b -= 1 a -= 1 print("")
8b9fa72e9480facc99108ab57a37c405f1b564c0
FrankieZhen/Lookoop
/Data Structures and Algorithm Analysis/Graph/toplogical_sort.py
1,590
3.8125
4
# 2018-8-21 # 拓扑排序 # 算法导论 P335 # 数据结构与算法分析 P219 class Vertex(object): def __init__(self, name=None, degree=None, p=[], c=[]): self.name = name self.degree = degree # 入度 self.p = None # 前驱 self.c = None self.sortNum = None def topSort(G): """ 使用BFS实现拓扑排序。 每次找到入度为0的节点放入列队,遍历与入度为0的点相邻的节点,并将度数减少1,如果度数变为0则放入列队。直到列队为空。 """ Q = [] # 列队存储每个节点 counter = 0 sort = {} for i in G: if i.degree == 0: Q.append(i) while len(Q) != 0: vertex = Q.pop() sort[vertex] = counter counter += 1 if vertex.c == None: continue for j in vertex.c : j.degree -= 1 if j.degree == 0: Q.append(j) if len(sort) != len(G): print("Graph has a cycle!") return None return sort def test(): # 数据结构与算法分析 P218 图9-4 # 实例图 v1 = Vertex(name="v1",degree=0) v2 = Vertex(name="v2",degree=1) v3 = Vertex(name="v3",degree=2) v4 = Vertex(name="v4",degree=3) v5 = Vertex(name="v5",degree=1) v6 = Vertex(name="v6",degree=3) v7 = Vertex(name="v7",degree=2) v1.c = [v2,v3,v4] v2.p = [v1] v2.c = [v4,v5] v3.p = [v1,v4] v3.c = [v6] v4.p = [v1,v2,v5] v4.c = [v3,v6,v7] v5.p = [v2] v5.c = [v4,v7] v6.p = [v3,v4,v7] v7.p = [v4,v5] v7.c = [v6] G = [v1,v2,v3,v4,v5,v6,v7] test = topSort(G) for i in test: print(i.name) if __name__ == "__main__": test() """ v1 v2 v5 v4 v7 v3 v6 符合 数据结构与算法分析 P219 图9-6 结果 """
6a2676c252fad4d7e915d7f94169de53dcc1c467
dahem/handbook
/uri/beginner/1117.py
233
3.71875
4
x = None while True: a = float(input()) if a < 0 or a > 10: print("nota invalida") continue if x == None: x = a continue else: print("media = %.2f" % ((a+x)*0.5)) break
50aec705d915b8b74411b80ca88f381f6718e224
nss-day-cohort-13/language-analyzer-lexi-con-artists
/sentiment.py
9,085
3.515625
4
from lexicon import * class Sentiment(Lexicon): ''' Classify a message into Sentiment subcategories ''' def __init__(self): ''' Call the Lexicon constructor with this lexicon's data ''' super().__init__('sentiment', sentiment_lexicon) def categorize_message(self, token_data): ''' Categorize a message including punctuation data Arguments: The token data for a message to be categorized Returns: A ClassifiedData for the message ''' classified_data = super().categorize_message(token_data) if '!' in token_data.punctuation.keys(): if classified_data.subcount['positive'] > classified_data.subcount['negative']: classified_data.subcount['positive'] += token_data.punctuation['!'] elif classified_data.subcount['negative'] > classified_data.subcount['positive']: classified_data.subcount['negative'] += token_data.punctuation['!'] return classified_data def modify_sentiment_from_behavior(self, message_data): ''' Modify MessageData sentiment from the data's behavior Arguments: The MessageDate to modify ''' classified_data = message_data.classified_data behavior = classified_data['behavior'] sentiment = classified_data['sentiment'] aggressive_count = behavior.subcount['aggressive'] / behavior.count passive_count = behavior.subcount['passive'] / behavior.count mentoring_count = behavior.subcount['mentoring'] / behavior.count positive_count = sentiment.subcount['positive'] / sentiment.count negative_count = sentiment.subcount['negative'] / sentiment.count sentiment_value = None if positive_count > negative_count: sentiment_value = 'positive' elif negative_count > positive_count: sentiment_value = 'negative' def modify_from_subcount(score): ''' Modify sentiment value based on a subcount Arguments: The subcount to be used to modify ''' if score >= 0.5: count_value = 1 if score >= 0.75: count_value = 2 sentiment.count += count_value sentiment.subcount[sentiment_value] += count_value if sentiment_value: modify_from_subcount(aggressive_count) modify_from_subcount(mentoring_count) count_value = 0 if passive_count >= 0.75: count_value = 2 elif passive_count >= 0.5: count_value = 1 sentiment.count += count_value sentiment.subcount['neutral'] += count_value sentiment_lexicon = { 'positive': { 'ability': 1, 'able': 1, 'achieve': 1, 'action': 1, 'advance': 1, 'aimed': 1, 'allowing': 1, 'amazing': 1, 'attainment': 1, 'being': 1, 'belief': 1, 'believe': 1, 'best': 1, 'better': 1, 'blessings': 1, 'blooming': 1, 'brothers': 1, 'can': 1, 'cares': 1, 'celebrate': 1, 'confidence': 1, 'confident': 1, 'considerable': 1, 'continue': 1, 'continuous': 1, 'create': 1, 'creation': 1, 'credit': 1, 'defending': 1, 'definite': 1, 'democracy': 1, 'development': 1, 'discover': 1, 'discovers': 1, 'disneyland': 1, 'dispositions': 1, 'eager': 1, 'earned': 1, 'easier': 1, 'easily': 1, 'embrace': 1, 'encouraging': 1, 'express': 1, 'fact': 1, 'finish': 1, 'friendship': 1, 'first': 1, 'funny': 1, 'gain': 1, 'generous': 1, 'get': 1, 'give': 1, 'goal': 1, 'god': 1, 'good': 1, 'gotten': 1, 'great': 1, 'greatest': 1, 'greatly': 1, 'grow': 1, 'happiness': 1, 'happy': 1, 'help': 1, 'highly': 1, 'honored': 1, 'hopeful': 1, 'ideas': 1, 'imagination': 1, 'imagine': 1, 'impress': 1, 'inspiring': 1, 'intelligence': 1, 'interest': 1, 'interesting': 1, 'its': 1, 'journey': 1, 'lead': 1, 'likely': 1, 'livelihoods': 1, 'lives': 1, 'live': 1, 'lucky': 1, 'made': 1, 'make': 1, 'making': 1, 'many': 1, 'might': 1, 'mind': 1, 'miracles': 1, 'more': 1, 'most': 1, 'motivate': 1, 'much': 1, 'music': 1, 'natasha': 1, 'new': 1, 'opportunity': 1, 'own': 1, 'parties': 1, 'passions': 1, 'permit': 1, 'persistent': 1, 'personal': 1, 'positive': 1, 'positivity': 1, 'rekindle': 1, 'relations': 1, 'reputation': 1, 'respect': 1, 'rewarded': 1, 'romanoff': 1, 'satisfied': 1, 'selfdiscipline': 1, 'selfknowlege': 1, 'spiritual': 1, 'succeed': 1, 'teachings': 1, 'truth': 1, 'validates': 1, 'wealth': 1, 'wish': 1, 'worth': 1 }, 'negative': { 'absurd': 1, 'against': 1, 'anger': 1, 'angry': 1, 'aprehend': 1, 'arduous': 1, 'arguments': 1, 'avengers': 1, 'battle': 1, 'behind': 1, 'blind': 1, 'bribe': 1, 'cautious': 1, 'challenge': 1, 'chance': 1, 'cocky': 1, 'conflict': 1, 'cruel': 1, 'cruelty': 1, 'dare': 1, 'debate': 1, 'defects': 1, 'demand': 1, 'depressed': 1, 'desire': 1, 'despite': 1, 'didnt': 1, 'different': 1, 'disappointment': 1, 'disemboweled': 1, 'disfigured': 1, 'dont': 1, 'doubtful': 1, 'drama': 1, 'drug': 1, 'emotional': 1, 'emotions': 1, 'encounter': 1, 'endeaver': 1, 'endure': 1, 'endured': 1, 'energy': 1, 'enjoyed': 1, 'enthusiasm': 1, 'evil': 1, 'extinguish': 1, 'extreme': 1, 'fear': 1, 'fearful': 1, 'fighting': 1, 'foolish': 1, 'government': 1, 'hard': 1, 'hostages': 1, 'hydra': 1, 'ignorance': 1, 'isnt': 1, 'judgmental': 1, 'least': 1, 'loki': 1, 'manipulate': 1, 'misdeeds': 1, 'mistakes': 1, 'morbid': 1, 'need': 1, 'negative': 1, 'negativity': 1, 'never': 1, 'no': 1, 'nonsense': 1, 'not': 1, 'nothing': 1, 'pander': 1, 'resistance': 1, 'ruin': 1, 'scared': 1, 'sickened': 1, 'sorry': 1, 'terrorists': 1, 'threatening': 1, 'tortured': 1, 'wasnt': 1, 'without': 1 }, 'neutral': { 'a': 1, 'about': 1, 'afterwards': 1, 'again': 1, 'age': 1, 'all': 1, 'already': 1, 'also': 1, 'american': 1, 'apache': 1, 'appear': 1, 'apple': 1, 'assembly': 1, 'assumptions': 1, 'attitude': 1, 'aura': 1, 'banner': 1, 'barton': 1, 'be': 1, 'because': 1, 'been': 1, 'before': 1, 'beforehand': 1, 'beginning': 1, 'bodies': 1, 'boot': 1, 'bottom': 1, 'buy': 1, 'case': 1, 'change': 1, 'civilization': 1, 'class': 1, 'clear': 1, 'entirely': 1, 'evidence': 1, 'exemption': 1, 'experiment': 1, 'find': 1, 'fire': 1, 'habit': 1, 'has': 1, 'have': 1, 'havent': 1, 'having': 1, 'ignored': 1, 'impact': 1, 'kept': 1, 'kindled': 1, 'knives': 1, 'know': 1, 'known': 1, 'laws': 1, 'main': 1, 'majority': 1, 'mankind': 1, 'men': 1, 'meanings': 1, 'meet': 1, 'mental': 1, 'military': 1, 'money': 1, 'must': 1, 'my': 1, 'myself': 1, 'now': 1, 'pass': 1, 'politics': 1, 'reputation': 1, 'trend': 1, 'unique': 1, 'want': 1, 'whole': 1, 'wielded': 1, 'worked': 1, 'working': 1, 'worth': 1, 'would': 1, 'year': 1, 'you': 1, 'your': 1, 'yourself': 1 } }
6efe5693066b42f3cb1c17435858664250bbaddb
DouglasAquino/Fractais-Geometricos
/Quadrado.py
742
3.515625
4
import turtle def drawSpiral(t, length, color): if length != 0: newcolor = (int(color[1:],16) + 2**20)%(2**24) newcolor = hex(newcolor)[2:] newcolor = "#"+("0"*(6-len(newcolor)))+newcolor t.color(newcolor) t.forward(length) t.left(90) drawSpiral(t, length -1 , newcolor) t.home() def main(): t = turtle.Turtle() t.shape("blank") screen = t.getscreen() t.speed(100) t.penup() t.goto(0,0) t.pendown() drawSpiral(t, 200, "#800000") t.left(30) drawSpiral(t, 200, "#FF4500") t.left(90) drawSpiral(t, 200, "#FF4500") t.left(270) drawSpiral(t, 200, "#800000") screen.exitonclick() main()
ece7c3258b84aaec7a0b383990536fdd24005ce6
gabidinica/PEP20G06
/modul6/modul6.py
3,412
3.84375
4
# iterators class ListIterator: def __init__(self, my_list: list): self.my_list = my_list def __next__(self): if len(self.my_list) == 0: raise StopIteration return self.my_list.pop(0) def __iter__(self): return self iterator = ListIterator([1, 2, 3]) for i in iterator: print('i:', i) # print(iterator.__next__()) # print(iterator.my_list) # print(iterator.__next__()) # print(iterator.my_list) # print(iterator.__next__()) # print(iterator.__next__()) # print(iterator.my_list) class IntIterator: def __init__(self, numar: int): self.numar = numar def __iter__(self): return self def __next__(self): for i in range(self.numar + 1): yield i # !!!!!!! la examen obiect iterator : 2clase clasa obiect si clasa iteratorului # # int_iterator = IntIterator(3) # for i in int_iterator: # print('i', i) class IntObject(): def __init__(self, nr): self.nr = nr # variabila de instanta def __iter__(self): return IntIterator(self.nr) # # int_object = IntObject(3) # for i in int_object: # print(i) print() # lambda functions def func1(a, b): return a + b func2 = lambda a, b: a + b func3 = lambda a, b: True print(func3(2, 3)) func1 = lambda x: pow(x, 2) print(func1(3)) print() # map def process_chr(char: str): return chr(ord(char) + 1) text = 'my_test to process' result = map(process_chr, text) print(result) print(dir(result)) for new_obj in result: print(new_obj) print('#' * 80) result = map(lambda char: chr(ord(char) + 1), text) for new_obj in result: print(new_obj) print('#' * 80) # o mapare cu o lista ce contine 100 de numere si mapez nr respective la impartit la 2 my_list = [i for i in range(100)] for i in map(lambda k: k / 2, my_list): print(i) print() print() my_list = [i for i in range(100)] for i in map(lambda k: pow(k, 2) % 2 == 0, my_list): print(i) print() print() list_number = [i for i in range(10)] result = map(lambda k: k if k % 2 == 0 else None, list_number) for i in result: print(i) print('#' * 80) # filter list_number = [i for i in range(10)] result = filter(lambda a: a > 5, list_number) # pentru un obiect din lista, conditia sa returneze True si trece de filtru for i in result: print(i) print() # filtru caracter si fiecare caracter sa verifice daca e mai mare ca m text = "".join([chr(i) for i in range(97, 123)]) result = filter(lambda a: a > 'm', text) for i in result: print(i) print('*' * 80) text = "".join([chr(i) for i in range(97, 123)]) result = filter(lambda a: ord(a) + 1 > 100, text) for i in result: print(i) print('*' * 80) # any #daca un obiect ce a trecut de o mapare ce este adevarat atunci returneaza True my_list = [1, 'a', True, False, False] my_list_f = [0, "", None, False, False] print(any(my_list)) print(any(my_list_f)) # all print('*' * 80) my_list = [1, 'a', True] my_list_f = [1, 'a', True, False] print(all(my_list)) print(all(my_list_f)) # mostenire class Wolf(): bark = True def hunt(self): print("hunting") # raise NotImplemented def method_1(self): pass class Dog(Wolf): def hunt(self): print('can t do that') def method_2(self): pass dog = Dog() print('dog barks: ',dog.bark) dog.method_2() dog.method_1() dog.hunt()
0ab93e622a8d2fee72075a42017e6bdb2f702463
OtherU/Python_Cursos_online
/desafio_028.py
592
3.71875
4
# ------ Modules ------ # from random import randrange # ------ Header & Footers ------ # header = str(' Desafio 028 ') subfooter = ('-'*68) footer = ('='*68) # ------ Header ------ # print('{:=^68}'.format(header)) # ------ Body ------ # n1c = int(randrange(5)) pler = str(input('Digite o nome do jogador: ')) n2p = int(input('Adivinhe o numero escolhido pelo PC de 0 a 5: ')) print() if n1c == n2p: print('{}, YOU WIN!!!'.format(pler)) else: print('YOU LOSE!!!') print('O numero escolhido pelo PC: "{}"'.format(n1c)) # ------ Footers ------ # print(subfooter) print(footer)
7772bfc196e455a5f555d6a7718272f97b70080e
carawaters/AstroImageProcess
/profile_gauss.py
1,474
3.59375
4
""" Creates a Gaussian profile and fits a Sersic profile to the intensity Author: Cara Waters Date: 15/12/20 """ import numpy as np import matplotlib.pyplot as plt from numpy import random from profile import int_radius, sersic_index, sersic def makeGaussian(amp, sigma, center): """ Makes a symmetric 2D gaussian. Inputs: amp = amplitude multiplier (float), sigma = standard deviation (list length 2), center = central point location (list length 2) Output: array of 2D gaussian values """ x = np.arange(0, 100, 1) y = x[:,np.newaxis] x0 = center[0] y0 = center[1] sig_x = sigma[0] sig_y = sigma[1] return amp * np.exp(-(((x - x0)**2/(2*sig_x**2))+((y - y0)**2/(2*sig_y**2)))) #Intializing sigma and mu amp = 30000 sigma = [5, 5] center = [50, 50] #Calculating Gaussian array gauss = makeGaussian(amp, sigma, center) data = gauss data = data.astype(int) intensity = int_radius(data, (50,50), 5000) n, k = sersic_index(intensity) I_0 = intensity[0] radius = np.array(range(0, len(intensity))) fig, ax = plt.subplots(2, 1, figsize=(5, 10)) ax[0].imshow(data, label=("2D Gaussian, sigma= " + str(sigma))) ax[0].set_title("2D Gaussian, sigma= " + str(sigma)) ax[1].plot(radius, sersic(radius, I_0, k, n), label="Sersic profile, n = " + str(round(n, 2)) + ", k = " + str(round(k, 2))) ax[1].plot(radius, np.log(intensity), 'rx') ax[1].set_xlabel("Radius (R)") ax[1].set_ylabel("ln(I)") ax[1].legend() ax[1].grid() plt.show()
78531b3bb399784b2bb12f7d348f69e4a7158b18
cravo123/LeetCode
/Algorithms/0783 Minimum Distance Between BST Nodes.py
1,164
3.640625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Solution 1, recursion # DFS returns previous value class Solution: def dfs(self, node, prev_val): if node is None: return prev_val prev_val = self.dfs(node.left, prev_val) self.res = min(self.res, node.val - prev_val) prev_val = self.dfs(node.right, node.val) return prev_val def minDiffInBST(self, root: TreeNode) -> int: self.res = float('inf') self.dfs(root, float('-inf')) return self.res # Solution 2, iteration # Just in-order traversal class Solution: def minDiffInBST(self, root: TreeNode) -> int: prev = float('-inf') res = float('inf') p, q = root, [] while p or q: if p: q.append(p) p = p.left else: p = q.pop() res = min(res, p.val - prev) prev = p.val p = p.right return res
729acb1426577060b0af61ec52194a2d437bc24b
DanielJHaar/Python_Practice_Jun2020
/Alphabet_Rangoni.py
613
3.78125
4
import string alphabet = list(string.ascii_lowercase) def print_rangoli(size): order = size - 1 for i in range (order, 0, -1): row = ['-'] * (2 * size - 1) for j in range(size - i): row[order - j] = row[order + j] = alphabet[j + i] print('-'.join(row)) for i in range (0, size): row = ['-'] * (2 * size - 1) for j in range (0, size - i): row[order - j] = row[order + j] = alphabet[j + i] print('-'.join(row)) if __name__ == '__main__': n = int(input()) print_rangoli(n)
9f2210ce083407107bd1294da841fdcc445613ef
jacintojosh/advent-of-code-2020
/puzzle1/puzzle1.py
1,219
4.0625
4
f = open('input.txt', 'r') expense_report = [int(line.replace('\n', '')) for line in f] sorted_expense_report = sorted(expense_report) # Find the two entries that sum to 2020; what do you get if you multiply them together? def find_2_num_sum_2020_product(arr): j = len(arr) - 1 i = 0 found_sum = False while(j > i and not found_sum): if((arr[i] + arr[j]) > 2020): j-=1 elif((arr[i] + arr[j]) < 2020): i+=1 elif((arr[i] + arr[j]) == 2020): found_sum = True print(arr[i] * arr[j]) if found_sum else print("No sum for 2020 in array.") # In your expense report, what is the product of the three entries that sum to 2020? def find_3_num_sum_2020_product(arr): k = len(arr) - 1 j = 1 i = 0 found_sum = False while(k > j and j > i and not found_sum): if((arr[i] + arr[j] + arr[k]) > 2020): k-=1 elif((arr[i] + arr[j] + arr[k]) < 2020): if (j - i == 1): j+=1 else: i+=1 elif((arr[i] + arr[j] + arr[k]) == 2020): found_sum = True print(arr[i] * arr[j] * arr[k]) if found_sum else print("No sum for 2020 in array.") find_2_num_sum_2020_product(sorted_expense_report) find_3_num_sum_2020_product(sorted_expense_report)
92bd9f43e5b4af5ee8448aa0a770fa9b6ffea00e
nikmalviya/Python
/Practical 8/remove_string.py
240
3.765625
4
filename = input('Enter Filename : ') string = input('Enter String you want to remove : ') file = open(filename, 'r') file_data = file.read() file.close() file = open(filename, 'w') file.write(file_data.replace(string, '')) file.close()
498d6c5079b143ecc57a5ad4ab2663701fcb70ee
Alexfordrop/Basics
/som_math.py
225
3.546875
4
import math radius = 30 # площадь круга с радиусом 30 area = math.pi * math.pow(radius, 2) print(area) # натуральный логарифм числа 10 number = math.log(10, math.e) print(number)
14822f0ef679b6762a00ed561fb1914ef701ea0c
wilkoklak/cTime
/example.py
346
3.78125
4
import cTime import time # A timer that will return a floating point number cTime.time('timer1', _round=5) # A timer that will print results itself to the console cTime.time('timer2', _print=True) time.sleep(10) cTime.timeEnd('timer2') time.sleep(5) print('Printed timer1: {}'.format(cTime.timeEnd('timer1'))) # See README.md for more details
2e632ec66a84f8a686941dc63f17a3609c2372b1
sphilmoon/karel
/diagnostic/new.py
351
4.3125
4
def main(): sequence_length = 1 intro() user_input = float(input("Enter num: ")) while user_input >= user_input: sequence_length += 1 user_input = float(input("Enter num: ")) if user_input < user_input: print("Thanks for playing!") def intro(): print("Enter a sequence of non-decreasing numbers.") if __name__ == "__main__": main()
822e6592b12d01e409dcba0d1225029f0c13c74a
MrHamdulay/csc3-capstone
/examples/data/Assignment_2/wltaid001/question3.py
314
4.375
4
#Aiden Walton #WLTAID001 #Program to calculate area of circle given radius import math pi=2 den=math.sqrt(2) while den<2: pi=pi*(2/den) den=math.sqrt(2+den) print("Approximation of pi:",round(pi,3)) r=eval(input("Enter the radius:\n")) area=pi*r**2 print("Area:",round(area,3))
595008685003d521fe4ce96d96427ea0bc0a2633
tseddon84/neptune_pride
/battle_checker/battle_check.py
1,430
3.75
4
import math defender_fleet=eval(input("How many ships are in defender fleet? ")) attacker_fleet=eval(input("How many ships are in attacker fleet? ")) defender_weapons=eval(input("What is your defender weapons tech? ")) attacker_weapons=eval(input("What is your attacker weapons tech? ")) hours=eval(input("How many hours until the attack? ")) industry=eval(input("What is the defenders industry? -99 if unsure ")) tech=eval(input("What is your defenders manufacturing? -99 if unsure ")) if(industry==-99 or tech==-99): pass else: defender_fleet+=math.floor((industry*(tech+5)/24)*hours) defender=defender_fleet attacker=attacker_fleet while defender>0 and attacker>0: attacker-=(defender_weapons+1) if attacker<=0: break defender-=attacker_weapons if defender>0: print("Defender Wins. Ship remaining:", defender) while attacker<=0: attacker_fleet+=1 attacker=attacker_fleet defender=defender_fleet while defender>0 and attacker>0: attacker-=(defender_weapons+1) if attacker<=0: break defender-=attacker_weapons print("Attacker needs: ", attacker_fleet," To win") else: print("Attacker Wins. Ship remaining:", attacker) while defender<=0: defender_fleet+=1 attacker=attacker_fleet defender=defender_fleet while defender>0 and attacker>0: attacker-=(defender_weapons+1) if attacker<=0: break defender-=attacker_weapons print("Defender needs: ", defender_fleet," To win")
c76a88f3564c8cf17a5f1a0ee3c288572bbb93d9
Emerson53na/exercicios-python-3
/059 Criando um menu.py
1,134
3.640625
4
from os import system system('clear') go = False while True: v1 = int(input(' Digite o primeiro valor: ')) v2 = int(input(' Digite o segundo valor: ')) go = True while go == True: n = int(input('''\n [1]Somar [2]Multiplicar [3]Maior [4]Novos números [5]Sair do programa \n >> ''')) if n == 1: valor = v1 + v2 print(f' {v1} + {v2} = {valor}') input() elif n == 2: valor = v1*v2 print(f' {v1} x {v2} = {valor}') input() elif n == 3: if v1 > v2: print(f' o valor {v1} é maoir que {v2}.') elif v1 < v2: print(f' O valor {v2} é maior que {v1}.') else: print(f' Os dois valores são iguais.') input() elif n == 4: system('clear') go = False elif n == 5: system('clear') print(' Volte sempre!:)') exit() system('clear')
9ba6e728c08fc5145c20f75d7c7b5557c1d4b0b6
lf832003/C-NMC_evaluation_code
/code/IO.py
426
3.5625
4
import os from natsort import natsorted def readfileslist(pathtofiles, fileext): if not os.path.exists(pathtofiles): raise Exception('Path does not exist!') lstFiles = [] for dirName, _, filelist in os.walk(pathtofiles): for filename in natsorted(filelist): if fileext in filename.lower(): lstFiles.append(os.path.join(dirName, filename)) return lstFiles
93637b0789f59a135c4416ded7fe389e5e841bca
mohitgite/TOC_ASS
/3.py
103
3.703125
4
m = int(input()) n = m.count("0") if n%3==0: print("Accepted") else: print("Rejected")
061f098fa97a7abd3b04dd4006472f481866eee8
piotrch-git/kurs_py
/dzień03/05_Slowniki.py
861
3.84375
4
#Słownik - nieuporządkowoana, mutowalna kolekcja par(klucz - wartość) - od pythona 3.coś gwarantowana jest kolejność zgodna z kolejnością wstawiania slownik = {} print(type(slownik)) stan_konta = {"Kowalski":120, "Nowak":15} print(stan_konta) print(stan_konta["Kowalski"]) print(type(stan_konta["Kowalski"])) #print(stan_konta["we"]) # błąd, nie ma takiego klucza stan_konta["Nowak"] += 10 print(stan_konta) stan_konta["Duda"] = 1300 print(stan_konta) stan_konta.pop("Duda") print(stan_konta) print(f'{"Nowak" in stan_konta=}') print(f'{"Duda" in stan_konta=}') for klucz in stan_konta: #pętla for przechodzi po kluczach słownika print(klucz) for klucz, wartosc in stan_konta.items(): # slownik.items() zwraca pary klucz-wartość print(f"{klucz} => {wartosc}") print(list(zip([1,2,3],[10,20,30]))) #sklejanie 2ch list w slownik
9a970eaf34797d251e6b26ca29e7ace9b7018854
raghavddps2/Technical-Interview-Prep-1
/BitManipulation/evenOdd.py
680
4.28125
4
""" Write a program to determine if the number is even or odd. Please don't use any modulus operator 0: 00000 1: 00001 2: 00010 3: 00011 4: 00100 5: 00101 6: 00110 7: 00111 8: 01000 9: 01001 -----> Looking at the above pattern we notice that if the least significant bit is 0 * The number turns out to be even * Otherwise the number truens out to be odd """ #Simply and with 1 and we can dtermine whether the number is even or odd def is_odd(x: int): if x and 1 == 0: return True return False a = int(input()) print("The number ",a," is ","odd" if is_odd(a) == True else "even" )
3e6ec4717874dfe8d57c3147d706be01e53917f5
bobby233/Pysysbeta
/Pyox.py
5,668
3.53125
4
# 名称:Pyox游戏 # GitHub上的作者:bobby233 # 一款OX棋游戏,内置于Pysys # 版本:0.0.1beta import random import Pysys_str as s import PSDK as p class Pyox(): """游戏主体""" def ask_diff(self): """询问难度""" while True: if s.oxout: break print('These are the difficulties:') print('1. test') print('Type "q" to quit') s.mess = input('Choose a difficulty above(type number): ') if s.mess == '1': self.test() elif s.mess == 'q': break else: print('Difficulty not found...') continue def test(self): """test难度""" s.oxout = False while True: if s.oxout == True: break print('Let us play test difficulty.') print('The computer does not want to win, just random.') print('You go first. You are "o", computer is "x", empty is "e".') hor = ' 1 2 3' li1 = '1 e e e' li2 = '2 e e e' li3 = '3 e e e' print(hor) print(li1) print(li2) print(li3) ho = list(hor) l1 = list(li1) l2 = list(li2) l3 = list(li3) while True: s.mess = input('Please type a position(like 11): ') # 绘制 if s.mess[0] == '1': if s.mess[1] == '1': l1[2] = 'o' elif s.mess[1] == '2': l2[2] = 'o' elif s.mess[1] == '3': l3[2] = 'o' elif s.mess[0] == '2': if s.mess[1] == '1': l1[4] = 'o' elif s.mess[1] == '2': l2[4] = 'o' elif s.mess[1] == '3': l3[4] = 'o' elif s.mess[0] == '3': if s.mess[1] == '1': l1[6] = 'o' elif s.mess[1] == '2': l2[6] = 'o' elif s.mess[1] == '3': l3[6] = 'o' else: s.oxout = True break # 处理 while True: c_l = str(random.randint(1, 4)) c_h = str(random.randint(1, 4)) c_a = c_l + c_h if c_a == s.mess: continue elif c_l == '1': if c_h == '1': l1[2] = 'x' elif c_h == '2': l2[2] = 'x' elif c_h == '3': l3[2] = 'x' break elif c_l == '2': if c_h == '1': l1[4] = 'x' elif c_h == '2': l2[4] = 'x' elif c_h == '3': l3[4] = 'x' break elif c_l == '3': if c_h == '1': l1[6] = 'x' elif c_h == '2': l2[6] = 'x' elif c_h == '3': l3[6] = 'x' break # 判断谁赢了 if (l1[2] == 'o' and l1[4] == 'o' and l1[6] == 'o') or (l2[2] == 'o' and l2[4] == 'o' and l2[6] == 'o') or (l3[2] == 'o' and l3[4] == 'o' and l3[6] == 'o') or (l1[2] == 'o' and l2[2] == 'o' and l3[2] == 'o') or (l1[4] == 'o' and l2[4] == 'o' and l3[4] == 'o') or (l1[6] == 'o' and l2[6] == 'o' and l3[6] == 'o'): win = True elif (l1[2] == 'x' and l1[4] == 'x' and l1[6] == 'x') or (l2[2] == 'x' and l2[4] == 'x' and l2[6] == 'x') or (l3[2] == 'x' and l3[4] == 'x' and l3[6] == 'x') or (l1[2] == 'x' and l2[2] == 'x' and l3[2] == 'x') or (l1[4] == 'x' and l2[4] == 'x' and l3[4] == 'x') or (l1[6] == 'x' and l2[6] == 'x' and l3[6] == 'x'): lose = True else: win, lose = False, False # 处理列表到字符串 hor = ''.join(ho) li1 = ''.join(l1) li2 = ''.join(l2) li3 = ''.join(l3) # 输出 print(hor) print(li1) print(li2) print(li3) if win: print('You win!') break elif lose: print('Computer wins!') break else: continue def info(self): """信息或玩""" print('Type "q" to quit') while True: s.mess = input('Welcome to Pyox.\nDo you want to see info or play(info/play)? ') if s.mess == 'info': p.info(name='Pyox', info='This is a OX chess game.') continue elif s.mess == 'play': self.ask_diff() elif s.mess == 'q': s.oxout = True break else: print('We do not have this option...') continue def run(self): """运行""" p.wel('Pyox') self.info() self.ask_diff() p.ext('Pyox')
abe69741468621df2b18bd319de4a5c2cb234070
IsraMejia/Python100DaysOfCode
/D9-GradingProgram.py
761
4.1875
4
student_scores = { "Harry": 81, "Ron": 78, "Hermione": 99, "Draco": 74, "Neville": 62, } # 🚨 Don't change the code above 👆 print('\n\t Grading Program\n') #TODO-1: Create an empty dictionary called sudent_grades. sudent_grades = {} #TODO-2: Write your code below to add the grades to sudent_grades.👇 for student in student_scores: score = student_scores[student] #We use the Key student if score > 90: sudent_grades[student] = 'Outstanding' elif score >80: sudent_grades[student] = 'Exceeds Expectations' elif score >70: sudent_grades[student] = 'Acceptable' else: sudent_grades[student] = 'Fail' # 🚨 Don't change the code below 👇 print(f'Student grades:\n{sudent_grades}')
61bc59c1f763b8b7d96d87c3e72e337ab8610d04
zd6515843/super_chen
/PythonSelfStudy/Lession01-09/lession_09_Class.py
3,434
3.59375
4
class Dog(): def __init__(self, name, age): ''' 初始化属性name age ''' self.name = name self.age = age def sit(self): print(self.name.title() + " is now sitting.") def roll_over(self): print(self.name.title() + " rolled over.") my_dog = Dog('vis', 5) print('My dog name is ' + my_dog.name.title()) print('My dog is ' + str(my_dog.age) + " years old.") my_dog.sit() my_dog.roll_over() class Restaurant(): def __init__(self, name, type): self.name = name self.type = type def describe_restaurant(self): print("Restaurant name is " + self.name.title()) print("Restaurant type is " + self.type) def open_restaurant(self): print("Restaurant " + self.name.title() + " is openning") restautant_1 = Restaurant('jyj', '盖饭') restautant_1.describe_restaurant() restautant_1.open_restaurant() restautant_2 = Restaurant('kfc', '汉堡') restautant_3 = Restaurant('一亩三分地', '炒菜') restautant_2.describe_restaurant() restautant_3.describe_restaurant() class Car(): def __init__(self, name, type, year): self.name = name self.type = type self.year = year self.miles = 0 def get_car_info(self): print("Car info: " + self.name.title() + " " + self.type + " " + self.year) def read_car_miles(self): print("Miles of this car is " + str(self.miles)) def update_miles(self, mile): if mile >= self.miles: self.miles = mile my_car = Car('奇骏', '运动版', '2019') my_car.get_car_info() my_car.read_car_miles() my_car.miles = 20 my_car.read_car_miles() my_car.update_miles(12) my_car.read_car_miles() class Life(): def __init__(self,lifeTime=10): self.lifeTime = lifeTime def get_life_time(self): print("Life time is " + str(self.lifeTime) + " years.") ''' 子类 ''' ''' 创建子类时父类必须包含在当前文件中 并且位于子类的前面 ''' class Elic(Car): def __init__(self, name, type, year): ''' 初始化父类的属性,再初始化电动汽车的属性 ''' super().__init__(name, type, year) self.battery_size = 66 ''' 将实例用作属性 ''' self.life = Life() def describe_battery(self): print("This is a " + str(self.battery_size) + "-kWh battery.") ''' 重写父类的方法 get_car_info''' def get_car_info(self): print("Test over wirte def get_car-info()") elic_car = Elic('雷克萨斯', '运动版', '2019') elic_car.get_car_info() elic_car.describe_battery() elic_car.get_car_info() elic_car.life.get_life_time() ''' 导入类的几种方法 前提条件: car.py 中包含了 类Car() 类ElectricCar() ... 1.从一个模块中导入一个多个类 from car import Car, ElectricCar my_car = Car(self,..,..) my_car2 = ElectricCar(self,..,..) 2.导入整个模块 import car my_car = car.Car(self,..,..) my_car2 = car.ElectricCar(self,..,..) 3.导入模块中所有的类 不推荐,不知道有哪些类 from car import * ''' from collections import OrderedDict # lanuages = OrderedDict() # lanuages['jen'] = 'python' # lanuages['sarah'] = 'c' # lanuages['edward'] = 'ruby' # lanuages['phil'] = 'python' # for name,lanuage in lanuages.items(): # print(name.title() + " favorite lanuage is " + # lanuage.title() + ".")
ef1cf9dd075ac2919e96e3f751f09c564001545f
NixonZ/PythonZ
/classes.py
472
4.09375
4
#learning classes class complex: """Implementing Complex numbers""" real=0 imag=0 def __init__(this,real=0,imag=0): this.real=real this.imag=imag def __str__(this): return (str(this.real)+'+'+str(this.imag)+'i') def update(this,x,y): this.real=x this.imag=y def __add__(this,other): return complex(this.real+other.real,this.imag+other.imag) z=complex(2,3) z.update(5,6) k=complex(2,3) print(k+z)
dfc63dc906a0a3954d5e7ba0cd94a5a2dce5064b
mridubhatnagar/concepts-brushup
/functions/firstclassfunctions.py
456
4.25
4
""" Learning 1. Function can be passed as argument. 2. Returned from a function. 3. assigned to a variable. """ def square(x): return x*x #Passing function as argument def my_map(func, arg_list): result = [] for i in arg_list: result.append(func(i)) return result squares=my_map(square, [1,2,3,4,5]) print(squares) def cube(x): return x*x*x def logger(msg): def log_message(): print('Log: ', msg) return log_message f=logger('Hi') f()
dc37e762edb0d1d382a7f5142236fb71e871f5ee
oldmuster/Data_Structures_Practice
/hashmap/python/containsDuplicate.py
444
3.703125
4
#!/usr/bin/env python #coding:utf-8 """ 217. 存在重复元素 https://leetcode-cn.com/problems/contains-duplicate/ """ class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ num_dic = {} for i in nums: if i in num_dic: return True else: num_dic[i] = 1; return False
36e8daf523a9b78d6cabf697e9e1b1c4e3a69b68
aten2001/CS7646-2
/tonumber.py
588
3.84375
4
#!/usr/bin/env python import sys, string """ tonumber.py < file.txt > file.number """ def convertStringToAsciiCharacters(sentence): ascii_rep=[] for word in sentence: for char in word: ascii_rep.append(ord(char)) return ascii_rep if len(sys.argv) < 2: sys.stderr.write('Usage: sys.argv[0] \n') sys.exit(1) f = open(sys.argv[1]) for word in f.read().split(): lower = word.lower() for c in string.punctuation: lower=lower.replace(c,"") myword = convertStringToAsciiCharacters(lower) print ''.join(str(x) for x in myword)
63b5c56c62186a9fbcb1694a6f415cbe967cdbd6
Uche-Clare/python-challenge-solutions
/Imaobong Tom/Phase 1/Python Basic 1/Day 3/5.py
161
4.46875
4
from math import pi r = float(input("Enter the radius of the sphere: ")) volume = 4/3 *(pi * r ** 3) print("The volume of the sphere is ", volume, end = " cm^3")
090df6bed7aa70d83844452d2051a26a73de8d57
jieshenboy/LeetCode
/code/fibonacci.py
741
3.9375
4
class Fibonacci(object): """ 返回一个斐波那契数列 """ def __init__(self): self.fList = [0,1] #设置初始列表 self.main() def main(self): listLen = input("请输入fibonacci数列的长度(3-50):") self.checkLen(listLen) while len(self.fList) < int(listLen): self.fList.append(self.fList[-1] + self.fList[-2]) print("得到的fibonacci数列为:\n %s" %self.fList) def checkLen(self, lenth): lenList = map(str, range(3,51)) if lenth in lenList: print("长度符合标准,可以运行") else: print("不符合长度") exit() if __name__ == "__main__": f = Fibonacci()
3ad59d6d7857a210767cd26df3db18b09c79bf27
MYMSSENDOG/leetcodes
/539. Invert Binary Tree.py
1,284
3.96875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from tree_node_lib import * class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root or (not root.left and not root.right): return root else: root.right, root.left = self.invertTree(root.left), self.invertTree(root.right) return root sol = Solution() array = [4,2,7,1,3,6,9] inorder_print(sol.invertTree(makeTree(array))) """ There is a role playing game whose main content is to break dungeon with 4-character party. Each charater has one of three roles. H is healer and to clear dungeon, there should be one healer T is tanker. There should be one tanker D is dealer. There should be TWO dealer Every party should contain 1H, 1T, 2D Each person has multiple characters with different role. There are n people and role_of_characters[k] represent kth palyer's character list. rnumber fo charcters is represented by [#of healer, #of tanker, #of dealer] Ex)role_of_characters[k] = [5,3,3] means someone have 5 healer, 3 tanker, 3 dealer It's guaranteed that there is at least one way that make party """
af571651636a510c0ee95cbbb3888f58b2f3d8ab
krolique/project_euler
/solutions/034_digit_factorials.py
659
4.09375
4
# -*- coding: utf-8 -*- """ Problem #34 - Digit factorials ------------------------------ 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: as 1! = 1 and 2! = 2 are not sums they are not included. """ from math import factorial def problem(): """ Attempt to solve the problem... """ print 'problem #34' s = 0 for n in xrange(3, 99999): if sum(factorial(int(c)) for c in str(n)) == n: s += n print 'the sum of all number is: %s' % s if __name__ == "__main__": problem()
ccb5b6324a0279e277f7182f830525d049d03c5d
SimasRug/Learning_Python
/Chapter2/D1.py
181
3.703125
4
total = 0 temp = 1 for x in range(64): temp = temp * 2 total = total + temp # print(x, temp, total); total_weight = total/7000 print('total weight: ', total_weight)
b611365007feff03441dbd95f6091a1748f8ec33
adigeak/leetcode
/python/leetcode1.py
195
3.609375
4
def square(x): return x*x def map_fuc(fuc, arr): a = [] for i in arr: a.append(fuc(i)) return a x = [ i for i in range(1,6)] squares = map_fuc(square,x) print(squares)
7e74d14a819612a273378461958f8e2751083278
daniel-reich/ubiquitous-fiesta
/66xK46dhKFCe5REDg_16.py
1,401
3.96875
4
def x_and_o(board): def board_to_list(bo = board): e = [] #The 1 dimensional list that will house the other lists for a in range(3): #Just puts the board into a 2 dimensional lst l = board[a].split("|") e.append(l) return e def win(lst): #This function determines if a board is a win for X if lst[0][0] == 'X' and lst[1][0] == 'X' and lst[2][0] == 'X': return True if lst[0][1] == 'X' and lst[1][1] == 'X' and lst[2][1] == 'X': return True if lst[0][2] == 'X' and lst[1][2] == 'X' and lst[2][2] == 'X': return True if lst[0][0] == 'X' and lst[0][1] == 'X' and lst[0][2] == 'X': return True if lst[1][0] == 'X' and lst[1][1] == 'X' and lst[1][2] == 'X': return True if lst[2][0] == 'X' and lst[2][1] == 'X' and lst[2][2] == 'X': return True if lst[0][0] == 'X' and lst[1][1] == 'X' and lst[2][2] == 'X': return True if lst[0][2] == 'X' and lst[1][1] == 'X' and lst[2][0] == 'X': return True else: return False w = [] f = board_to_list() for a in range(3): #row for b in range(3): #column g = f[a][b] #This allows the board position to be restored to before the attempt f[a][b] = 'X' if f[a][b] != 'O' else '' if win(f): #If it results in a win, it will return that return [a+1,b+1] else: f[a][b] = g if w == []: return False
07774c13515b4e671be1c128e3529e19e01f0020
juarezfrench/cs-module-project-recursive-sorting
/src/sorting/sorting.py
2,001
4.25
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [0] * elements # Your code here def sort(a_index=0, b_index=0, index=0): if index >= len(merged_arr): return merged_arr else: if a_index > len(arrA) - 1: merged_arr[index] = arrB[b_index] index += 1 b_index += 1 sort(a_index, b_index, index) elif b_index > len(arrB) - 1: merged_arr[index] = arrA[a_index] index += 1 a_index += 1 sort(a_index, b_index, index) elif arrA[a_index] <= arrB[b_index]: merged_arr[index] = arrA[a_index] index += 1 a_index += 1 sort(a_index, b_index, index) else: merged_arr[index] = arrB[b_index] index += 1 b_index += 1 sort(a_index, b_index, index) sort() return merged_arr # TO-DO: implement the Merge Sort function below recursively def merge_sort(arr): # Your code here if len(arr) <= 1: return arr elif len(arr) > 2: dividing_index = (len(arr) - 1) // 2 arr1 = arr[0:dividing_index] arr2 = arr[dividing_index:len(arr)] sorted_pairs1 = merge_sort(arr1) sorted_pairs2 = merge_sort(arr2) return merge(sorted_pairs1, sorted_pairs2) else: if arr[0] < arr[1]: return arr else: arr[0], arr[1] = arr[1], arr[0] return arr # STRETCH: implement the recursive logic for merge sort in a way that doesn't # utilize any extra memory # In other words, your implementation should not allocate any additional lists # or data structures; it can only re-use the memory it was given as input
54139fc5991c4c760ea8bc8b79a7530781a4c6b1
msarfati/sqlalchemy-sandbox
/01engine.py
1,277
4.375
4
#!/usr/bin/env python # Michael Sarfati -- tutorial from Mike Bayer's Introduction to SQLAlchemy # ( https://www.youtube.com/watch?v=P141KRbxVKc ) # This script explores SQL alchemy's engine basics from lessonNice import printBorder as pb pb("01: SQLAlchemy - Engine Basics") #Actual tutorial begins here. For use with an interactive from sqlalchemy import create_engine #echo enables logging of SQL statements engine = create_engine("sqlite:///some.db", echo=True) print("Engine = ", engine) #Result here acts like a cursor, and just interacts with the data. result = engine.execute( "SELECT * FROM employees") row = result.fetchone() '''Result (which is really just a cursor) will close implicitly, once the result has been placed into a variable, or printed to the screen. But you an also close it explicitly like this.''' result.close() #print(result.fetchall()) conn = engine.connect() trans = conn.begin() #conn.execute("INSERT INTO employees " #"(emp_name) VALUES (:emp_name)", emp_name="Xena Xenos") conn.execute( "UPDATE employees SET emp_wage = :emp_wage WHERE emp_name='Xena Xenos'", emp_wage=21.15) trans.commit() conn.close() #Using with to connect, and right-away execute a statement with engine.begin() as conn: conn.execute("SELECT * FROM employees")
b3c567bf469ca098942eed6d06d50bec1c3ebacb
SelmTalha/sinav_calisma
/VizeÇalışma(python)/Örnekler/format.py
122
3.8125
4
#Formatlama islemini yapiniz ! a=int(input("Bir sayi :")) b=int(input("Bir sayi :")) print("{} + {} = {}".format(a,b,a+b))
7fd7ec66a3f7aebb33b0386671332dd5b945e090
nataliegarate/python_ds
/lists/list_of_products.py
212
3.875
4
def findProduct(arr): products = [] product = 1 for x in arr: product *= x for num in arr: products.append(int(product/num)) return products print(findProduct([1, 2, 3, 4]))
7dee8ad7c8afcf16b70112335397e95eb072a79d
awillats/SkillsWorkshop2017
/Week01/Problem04/cbalusek_04.py
502
3.984375
4
""" Created on Fri Jul 21 11:20:45 2017 The goal of this program is to find the largest palindromic number formed by two three digit numbers It can be modified slightly to produce a list of palindromes and the integers that generate them. @author: cbalusek3 """ nList = range(999,900,-1) test = 0 i = 0 for n1 in nList: for n2 in nList: prod = n1*n2 if str(prod) == str(prod)[::-1]: print(prod, n1 , n2) i = 1 break if i == 1: break
d1b25583246d2f16b3f47e65003ec56c7dd646a1
entcs/Moba
/rulez/rolls.py
440
3.578125
4
import math,random sides=20 dices=10 roll=0 r1=0 rolls=[0]*dices count=1000 for tnr in range(count): for nr in range(dices): roll=0 for nr1 in range(nr+1): r1=int(random.random()*sides)+1 if r1>roll: roll=r1 rolls[nr]+=roll want=5 sides=20 dices=5 for want in [5,10,12,14,15,16,17,18,19,20]: print 'roll',want,'+',1-math.pow(want-1,dices)/math.pow(sides,dices)
bc7f4304b24f6d593524eeb391c60fc43caeb368
LXCuup/Pythoncode
/pizza_materials.py
219
3.6875
4
prompt = "Please add materials of your pizza:" prompt += "\n Enter 'quit' when you are finishend. " materials = " " while materials != 'quit': materials = raw_input(prompt) if materials != 'quit': print materials
2f020b0ac05bedc72cce5eefbbb6032f53801dc0
etherion-1337/Data_Structure_Algo_UCSD
/Course_1_Algorithmic_Toolbox/week2_algorithmic_warmup/1_fibonacci_number/fibonacci.py
745
3.890625
4
# Uses python3 def calc_fib(n): """ Slowest. Use Fibonacci definition """ if (n <= 1): return n return calc_fib(n - 1) + calc_fib(n - 2) def calc_fib_algo(n): """ Faster algo. Use human like algo to calculate """ if n <= 1: return n else: prev = 0 curr = 1 for i in range(n - 1): prev, curr = curr, prev + curr return curr def calc_fib_fast(n): """ Directly use maths formula """ if n <= 1: return n else: fib_p = ((1+5**0.5)/2)**n fib_m = ((1-5**0.5)/2)**n fib = (fib_p - fib_m)/(5**0.5) return int(fib) n = int(input()) #print(calc_fib(n)) #print(calc_fib_algo(n)) print(calc_fib_fast(n))
6957c0246d4d087d53ddb179b73a4c67b611e6f9
bkalcho/python-crash-course
/cubes.py
192
3.8125
4
# Author: Bojan G. Kalicanin # Date: 28-Sep-2016 # Make a list of the first 10 cubes cubes = [] for value in range(1, 11): cube = value ** 3 cubes.append(cube) for cube in cubes: print(cube)
f2670121af366216a68c8050d7bd77bd28cdb4f9
danielfk11/calculadora
/main.py
3,446
3.875
4
from tkinter import * from typing import Match root = Tk() root.title("Calculadora") root.config(background='grey') e = Entry(root, width=35, borderwidth=5) e.grid(row=0, column=0, columnspan=3, padx=10, pady=10) #e.insert(0, "") # DEFINIR AS FUNCOES def button_click(number): current = e.get() e.delete(0, END) e.insert(0, str(current) + str(number)) def button_clear(): e.delete(0, END) def button_igual(): second_number = e.get() e.delete(0, END) if math == "adicionar": e.insert(0, f_num + int(second_number)) if math == "subtrair": e.insert(0, f_num - int(second_number)) if math == "dividir": e.insert(0, f_num / int(second_number)) if math == "multiplicar": e.insert(0, f_num * int(second_number)) def button_sub(): first_number = e.get() global f_num global math math = "subtrair" f_num = int(first_number) e.delete(0, END) def button_multip(): first_number = e.get() global f_num global math math = "multiplicar" f_num = int(first_number) e.delete(0, END) def button_divd(): first_number = e.get() global f_num global math math = "dividir" f_num = int(first_number) e.delete(0, END) def button_adicionar(): first_number = e.get() global f_num global math math = "adicionar" f_num = int(first_number) e.delete(0, END) button_1 = Button(root, text="1", padx=40, pady=20, command=lambda: button_click(1)) button_2 = Button(root, text="2", padx=40, pady=20, command=lambda: button_click(2)) button_3 = Button(root, text="3", padx=40, pady=20, command=lambda: button_click(3)) button_4 = Button(root, text="4", padx=40, pady=20, command=lambda: button_click(4)) button_5 = Button(root, text="5", padx=40, pady=20, command=lambda: button_click(5)) button_6 = Button(root, text="6", padx=40, pady=20, command=lambda: button_click(6)) button_7 = Button(root, text="7", padx=40, pady=20, command=lambda: button_click(7)) button_8 = Button(root, text="8", padx=40, pady=20, command=lambda: button_click(8)) button_9 = Button(root, text="9", padx=40, pady=20, command=lambda: button_click(9)) button_0 = Button(root, text="0", padx=40, pady=20, command=lambda: button_click(0)) button_soma = Button(root, text="+", padx=40, pady=20, command=button_adicionar) button_menos = Button(root, text="-", padx=40, pady=20, command=button_sub) button_multi = Button(root, text="x", padx=40, pady=20, command=button_multip) button_div = Button(root, text="÷", padx=40, pady=20, command=button_divd) button_igual = Button(root, text="=", padx=80, pady=20, command=button_igual) button_limpar = Button(root, text="Limpar", padx=80, pady=20, command=button_clear) button_1.grid(row= 3, column=0) button_2.grid(row= 3, column=1) button_3.grid(row= 3, column=2) button_4.grid(row=2 , column=0) button_5.grid(row=2 , column=1) button_6.grid(row=2, column=2) button_7.grid(row=1, column=0) button_8.grid(row=1 , column=1) button_9.grid(row=1, column=2) button_0.grid(row=4 , column=0) button_soma.grid(row=1, column=3) button_div.grid(row=2, column=3) button_multi.grid(row= 3, column=3) button_menos.grid(row=4, column=3) button_limpar.grid(row=5, column=0, columnspan=2) button_igual.grid(row=5, column=2, columnspan=4) root.mainloop()
cb1ccf8e53e0ff30b1ffdb810bf33af1913f9a30
Fahmiady11/trapezoid-recrusive
/190411100127_muhammad fahmia ady susilo.py
534
3.984375
4
def rumus(x): return 1/(1+x**2) def trapezoid(x, y, z): integerasi = rumus(x)+rumus(y) h=(y-x)/z i=1 while i<z : integerasi = integerasi+(2*rumus(x+i*h)) i+=1 integerasi =integerasi * (h)/2 return integerasi print("RUMUS : 1/(1+x**2)") batasBawah = int(input("Masukkan batas bawah :")) batasAtas = int(input("masukkan batas atas :")) Interval = int(input("masukkan interval :")) result = trapezoid(batasBawah,batasAtas, Interval) print("hasil integrasi metode trapezoid :%0.6f" % (result))
a15c7d53249a5f94dda3afc4bc215e80afb556c6
jasonim/learn-python3
/basic/my_list.py
271
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- people = ['Jason', 'xiaoming', 'Bob'] print(people, len(people)) print (people[-1]) # print people[-4] out of range people.insert(1, 'Jack') print(people) print(people.pop()) s = ['python', 'java', people, 'c'] print (s)
440fa96338349f1161e738b50862342c619b355f
iamanx17/dslearn
/Binary Tree/binarytree.py
580
3.703125
4
class Node: def __init__(self, data): self.data=data self.left=None self.right=None def takeinput(): data=int(input()) if data==-1: return root=Node(data) root.left=takeinput() root.right=takeinput() return root def printdata(root): if root is None: return print(root.data, end=':') if root.left is not None: print('L', root.left.data , end=',' ) if root.right is not None: print('R', root.right.data) print() printdata(root.left) printdata(root.right)
ab8709c5a3e889792c1ba8a26448a31085be6421
rramdin/adventofcode
/src/2017/advent2.py
1,976
3.78125
4
#!/usr/bin/python import sys import io # The spreadsheet consists of rows of apparently-random numbers. To make sure # the recovery process is on the right track, they need you to calculate the # spreadsheet's checksum. For each row, determine the difference between the # largest value and the smallest value; the checksum is the sum of all of these # differences. # # For example, given the following spreadsheet: # # 5 1 9 5 # 7 5 3 # 2 4 6 8 # # - The first row's largest and smallest values are 9 and 1, and their # difference is 8. # - The second row's largest and smallest values are 7 and 3, and their # difference is 4. # - The third row's difference is 6. # # In this example, the spreadsheet's checksum would be 8 + 4 + 6 = 18. def calculateChecksum(f): checksum = 0 for l in f: splt = l.split() low = None high = None for d in splt: d = int(d) if low == None: low = d high = d elif d < low: low = d elif d > high: high = d checksum += high - low return checksum def calculateChecksum2(f): checksum = 0 for l in f: splt = l.split() splt = [int(x) for x in splt] result = None for i in range(len(splt)): for j in range(len(splt)): if i == j: continue if splt[i] % splt[j] == 0: result = splt[i] / splt[j] break if result is not None: break if result is None: raise Exception("Invalid input") checksum += result return checksum if __name__ == '__main__': if len(sys.argv) != 2: print 'usage: %s <file name>' % sys.argv[0] sys.exit(1) fname = sys.argv[1] with open(fname, 'r') as f: result = calculateChecksum(f) print 'result = %d' % result with open(fname, 'r') as f: result = calculateChecksum2(f) print 'result2 = %d' % result
83e3bf146462ca5e1ae44ed841c57fb60d75499d
szhua/PythonLearn
/Unit2/Lesson15.py
2,065
4.09375
4
#Python的多线程: import threading ,time ,random #在子线程中进行轮询操作 def loop(): #显示当前线程的名字 print("current thread name: %s"%threading.current_thread().name) n = 0 while n<5: print("thread %s ==> %s"%(threading.current_thread().name,n)) n+=1 time.sleep(1) print("child thread is finished !!") pass if __name__ == '__main__': #打印主线程的名字 print("main tread name %s"%threading.current_thread().name) #创建子线程 t =threading.Thread(target=loop,name="LoopThread") t.start() #执行其他的线程 t.join() pass "线程同步" def change_it(n): # 先存后取,结果应该为0: global balance balance = balance + n balance = balance - n balance = 0 lock =threading.Lock() def run_thread(n): for i in range(100): lock.acquire() try: print("current thread",threading.current_thread().name) change_it(n) finally: lock.release() t1 = threading.Thread(target=run_thread, args=(5,)) t2 = threading.Thread(target=run_thread, args=(8,)) t1.start() t2.start() t1.join() t2.join() print(balance) """ 当多个线程同时执行lock.acquire()时,只有一个线程能成功地获取锁,然后继续执行代码,其他线程就继续等待直到获得锁为止。 获得锁的线程用完后一定要释放锁,否则那些苦苦等待锁的线程将永远等待下去,成为死线程。 ##所以我们用try...finally来确保锁一定会被释放。 锁的好处就是确保了某段关键代码只能由一个线程从头到尾完整地执行,坏处当然也很多,首先是阻止了多线程并发执行, 包含锁的某段代码实际上只能以单线程模式执行,效率就大大地下降了。其次,由于可以存在多个锁,不同的线程持有不同的锁, 并试图获取对方持有的锁时,可能会造成死锁,导致多个线程全部挂起,既不能执行,也无法结束,只能靠操作系统强制终止。 """
05fded1c54d25cdae5ec7b85fad3a7a2cd3259b1
ypliu/leetcode-python
/src/126_word_ladder_ii/126_word_ladder_ii_BiBfs.py
1,624
3.59375
4
from collections import defaultdict import string class Solution: def findLadders(self, beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: List[List[str]] """ if endWord not in wordList or not endWord or not beginWord: return [] word_list = set(wordList) forward, backward = {beginWord}, {endWord} direction = 1 parents = defaultdict(set) while forward and backward: if len(forward) > len(backward): forward, backward = backward, forward direction *= -1 foward_next = set() word_list -= forward for word in forward: for i in range(len(word)): first, second = word[:i], word[i+1:] for ch in string.ascii_lowercase: combined_word = first + ch + second if combined_word in word_list: foward_next.add(combined_word) if direction == 1: parents[combined_word].add(word) else: parents[word].add(combined_word) if foward_next & backward: results = [[endWord]] while results[0][0] != beginWord: results = [ [parent] + result for result in results for parent in parents[result[0]] ] return results forward = foward_next return []
320368cbefe509de819e26fe97ed004993d7d266
llraphael/algorithm_problems
/array/FindAllDuplicatesInArray.py
1,005
4.0625
4
""" Find all the duplicates in an array. Since 1 <= a[i] <= n and n is the length of the array, if there is no duplicate, the array should contain every number from 1 to n and we can make the correspondance between the value and its place in the array as (val, val - 1). Thus, the general idea is to check each element in the array and put the element to its corresponding place. If the corresponding place already has the right value, a duplicate exists, the current element should be put to -1 to avoid over count. If not, just swap the current element and the element in the corresponding position. """ class Solution(object): def findDuplicates(self, nums): """ :type nums: List[int] :rtype: List[int] """ res = [] i = 0 while i < len(nums): if nums[i] != i + 1 and nums[i] != -1: index = nums[i] - 1 if nums[index] == nums[i]: res.append(nums[i]) nums[i] = -1 else: nums[i], nums[index] = nums[index], nums[i] i = i - 1 i = i + 1 return res
cdf4ce0acf4af7d19d4e75f7645fd44c970b008b
JaeyoonChun/git-practice
/WhatDate.py
1,670
3.828125
4
def input_date(): year = int(input("__년도를 입력하시오:")) month = int(input("__월을 입력하시오:")) day = int(input("__일을 입력하시오:")) return year, month, day def get_day_name(input_year, input_month, input_day): day_sum = 0 monthly_numOfDay=(31,28,31,30,31,30,31,31,30,31,30,31) day_name=("일요일","월요일","화요일","수요일","목요일","금요일","토요일") leap_cnt = ((input_year-1)//4) - ((input_year-1)//100) + ((input_year-1)//400) normal_cnt = (input_year-1) - leap_cnt day_sum = (leap_cnt * 366) + (normal_cnt * 365) if not is_leap(input_year): for m in range(1, input_month): day_sum += monthly_numOfDay[m-1] else: for m in range(1, input_month): if m != 2: day_sum += monthly_numOfDay[m-1] else: day_sum += 29 day_sum += input_day idx = day_sum%7 return day_name[idx] def is_leap(input_year): if input_year%4 == 0: if input_year%400 == 0: return True elif input_year%100!=0: return True else: return False else: return False if __name__ == "__main__": year, month, day = input_date() day_name = get_day_name(year, month, day) print(day_name) if is_leap(year) == True: print("입력하신 %s은 윤년입니다" %year) print("git diff : 수정사항 입력") print("git diff : 두번째 수정사항 입력") print("git diff : 마지막 수정사항 입력") print("git diff : 진짜 마지막 으을 다시 수정해보자")
5952eef87814a720ee631230498c14e53bf07d02
marchon/nanoservice
/nanoservice/config.py
1,515
3.5
4
""" Read configuration for a service from a json file """ import io import re import json from .client import Client class DotDict(dict): """ Access a dictionary like an object """ def __getattr__(self, key): return self[key] def __setattr__(self, key, value): self[key] = value def load(filepath=None, filecontent=None, clients=True, rename=True): """ Read the json file located at `filepath` If `filecontent` is specified, its content will be json decoded and loaded instead. The `clients` arg is a binary flag which specifies whether the endpoints present in config (`filecontent`), should be used to create `Client` objects. Usage: config.load(filepath=None, filecontent=None): Provide either a filepath or a json string """ conf = DotDict() # Read json configuration assert filepath or filecontent if not filecontent: with io.FileIO(filepath) as fh: filecontent = fh.read().decode('utf-8') configs = json.loads(filecontent) # Update the conf items (Create clients if necessary) for key, value in configs.items(): conf[key] = value if clients and isinstance(value, str) and \ re.match('inproc:|ipc:|tcp:', value) and '.client' in key: conf[key] = Client(value) if rename: if key.endswith('.client'): new_key = key.replace('.client', '') conf[new_key] = conf.pop(key) return conf
69f79fabfc885ded53fdcf434e5bca5335cec0df
infinitepassion/Simulations
/Projects/Shell Project/cmd_pkg/mv.py
462
3.71875
4
import sys import os import shutil """ @Name: mv @Description: Used to rename a file @Params: cmd(list) - the file to rename """ def mv(cmd): os.system('touch output.txt') if len(cmd)==3: if os.path.isfile(cmd[1]): # copy the file and then remove original file shutil.copyfile(cmd[1], cmd[2]) os.remove(cmd[1]) else : print ("mv: cannot stat'"), print(cmd[1]), print("': No such file or directory") else: print "Invalid syntax" return
857695d8e23d23d8713ef8325316501250e621a1
BjornChrisnach/Python_6hour_course
/Intermediate/map_function.py
241
3.6875
4
# map function nr3 li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def func(x): return x**x # newList = [] # for x in li: # newList.append(func(x)) # print(newList) # print(list(map(func, li))) print([func(x) for x in li if x % 2 == 0])
da7f4b62871ce3351c9da3e7590f73b293a81a42
fabiannoda/PythonTutorial
/Sintaxis Basica/excepciones2.py
868
4
4
''' def divide(): try: op1=float(input()) op2=float(input()) print(str(op1/op2)) except ValueError: print("Es bobo o que") except ZeroDivisionError: print("Es bobo o solo se hace") finally: print("se hizo") divide() ''' ''' def evaluaEdad(edad): if edad<0: raise TypeError("NO sea maricon") if edad<20: return "eres muy joven" elif edad<40: return "Eres joven" elif edad<65: return "Eres mafuro" elif edad<100: return "Cuidate..." print(evaluaEdad(15)) ''' import math def calcula(num1): if num1<0: raise ValueError("El numero no puede ser negativo") else: return math.sqrt(num1) op1=int(input()) try: print(calcula(op1)) except ValueError as ErrorDeNumeroNegativo: print(ErrorDeNumeroNegativo)
e986c5ff8f039aeb792866991d380fc9844e24fe
zil93rus/Python_lessons_basic-master
/lesson01/home_work/hw01_easy.py
2,012
4.15625
4
__author__ = 'Ваши Ф.И.О.' # Задача-1: Дано произвольное целое число (число заранее неизвестно). # Вывести поочередно цифры исходного числа (порядок вывода цифр неважен). # Подсказки: # * постарайтесь решить задачу с применением арифметики и цикла while; # * при желании решите задачу с применением цикла for. import random number = str(random.randint(100,10000)) print(number) i = 0 while i < len(number): print(number[i]) i += 1 print("cycle while is done") for i in number: print(i) print("cycle for is done") i = 0 while number != 0: x = int(number) % 10 print(x) number = int(number) // 10 print("var3") # код пишем тут... # Задача-2: Исходные значения двух переменных запросить у пользователя. # Поменять значения переменных местами. Вывести новые значения на экран. # Подсказка: # * постарайтесь сделать решение через дополнительную переменную # или через арифметические действия # Не нужно решать задачу так: # print("a = ", b, "b = ", a) - это неправильное решение! a = input("please enter a: ") b = input("please enter b: ") print("a = ", a, "b = ", b) #c = a #a = b #b = c a, b = b, a print("a = ", a, "b = ", b) # Задача-3: Запросите у пользователя его возраст. # Если ему есть 18 лет, выведите: "Доступ разрешен", # иначе "Извините, пользование данным ресурсом только с 18 лет" age = int(input("How old are you: ")) if age < 18: print("Sorry!") else: print("Hello, acces allowed")
d126ffd0cc7300caa6e505fd741cdc8d118c8021
optionalg/programming-introduction
/Aula 09/Aula9-Extra-6.py
447
3.671875
4
""" Aula 9 Exercícios Extras 6 Autor: Lucien Constantino """ def get_number(): while True: number = int(input("Digite um número: ")) if number < 0: print("Número inválido") else: return number n = get_number() count = 0 number_count = 10 while count < n: line = "" for i in range(0, number_count): line += "{0} ".format(i) print(line) number_count -= 1 count += 1
8d397c054ed70fe040b5cc3d376f254f15a9a78a
zaidajani/Hacktoberfest_2021-1
/Data Ekstrakulikuler.py
1,486
3.96875
4
#Cetak judul program (OUTPUT) print("---------------DAFTAR EKSTRAKULIKULER SMPN 1 CITEUREUP---------------") ekstrakulikuler = ["1.Pramuka","2.Paskibra","3.PMR", "4.Futsal", "5.Volly", "6.Tata boga", "7.Vokal"] print("Ada apa saja? seperti :") for eks in ekstrakulikuler: print (eks) #Mencetak output dengan format menjumlahkan variabel ekstrakulikuler yang ada didalam [] print ("Total ekstrakulikuler: ada {}".format(len(ekstrakulikuler))) cari = input("Pilih ekstrakulikuler utama : ") #iterasi a = 0 terpilih = False while a < len(ekstrakulikuler): if cari in ekstrakulikuler[a]: terpilih = True break a=a+1 #Input eskul=[] a = 1 berhenti = False print("---------------BIODATA SISWA/SISWI PENDAFTAR EKSTRAKULIKULER---------------") input("Nama : ") input("Kelas : ") input("Nomer Hp : ") #Mengisi pilihan eskul while(not berhenti): eskul_pilih = input("\nPilih eskul yang diinginkan ke-{}: ".format(a)) eskul.append(eskul_pilih) #iterasi a += 1 tanya = input("Mau tambah ekstrakulikuler lagi? (ya/tidak): ") if(tanya == "tidak"): berhenti = True # Cetak Semua ekstrakulikuler print ("-----" * 10) print ("Kamu memimilih {} ekstrakulikuler :".format(len(eskul))) #iterasi for school in eskul: print ("- {}".format(school)) print("\n---------------SELAMAT BERGABUNG DI EKSTRAKULIKULER---------------") print(" SEMOGA NYAMAN, DAN TETAP RAJIN")
18b79befee42bc43967b760c53874beae9bbda09
Taeg92/Problem_solving
/Programmers/Level2/프린터/프린터.py
700
3.609375
4
def solution(priorities, location): answer = 0 val = priorities[location] priorities[location] = 0 while priorities: temp = priorities.pop(0) if priorities: if temp == 0: if val >= max(priorities): answer += 1 return answer else: priorities.append(temp) else: if temp >= val and temp >= max(priorities) : answer += 1 else: priorities.append(temp) else: return answer+1 priorities = [1, 1, 9, 1, 1, 1] location = 0 print(solution(priorities, location))
ed5f7816d9c97f2bf3d77416aa5043e7db80dac8
AdamRajoBenson/Rajo-
/binstr.py
112
3.671875
4
w=input() y=0 for i in w: if((i=='0')or(i=='1')): y=y+1 if(y==len(w)): print("yes") else: print("no")
6fd6d12905167467c27fdd2cfb2eeff1ffa92edd
robbyvan/-
/配列/35_Search Insert Position.py
418
3.515625
4
# 35. Search Insert Position # 类似34, 这里high取len(nums), 因为只用访问nums[mid]. # 如果mid >= target, 更新high, 否则更新low class Solution: def searchInsert(self, nums, target): if not nums: return 0 low, high = 0, len(nums) while low < high: mid = low + (high - low) / 2 if nums[mid] >= target: high = mid else: low = mid + 1 return low
6949c4adbb6b15d95df094e5892c7976b66e09ce
dyf102/LC-daily
/dp/python/shortest-path-visiting-all-nodes.py
1,070
3.984375
4
from collections import defaultdict, deque from typing import List def shortestPathLength(graph: List[List[int]]) -> int: """LC 847 Time complexity: O(N*2^N) Space: O(N*2^N) A pure BFS solution. It uses bit covery to store the status. Args: graph (List[List[int]]): [description] Returns: int: [description] """ n = len(graph) target = (2 ** n) - 1 queue = deque([(1 << i, i) for i in range(n)]) seen = [[0] * (2 ** n) for _ in range(n)] step = 0 while len(queue) > 0: current = len(queue) for i in range(current): s, ending = queue.popleft() if seen[ending][s] == 1: continue # Since it's bfs, we can assure the first is shortest if s == target: return step seen[ending][s] = 1 for nxt in graph[ending]: next_s = s |(1 << nxt) queue.append((next_s, nxt)) step += 1 if __name__ == "__main__": print(shortestPathLength([[1],[0,2,4],[1,3,4],[2],[1,2]]))
d4fd1a12e587680c804d21c6f5afbebb2bc5e58c
gourik/Machine-Learning-
/list_comprehension.py
757
4.375
4
# -*- coding: utf-8 -*- """ Created on Tue May 25 11:46:14 2021 @author: Gouri """ #List comprehension provides a concise way to create lists. It contains brackects which consist of # an expression followed by a for clause, then zero or more for or if clauses. The expressions can be # anything i.e we can add any objects in to lists. list1=[] def lst_square(lst): for i in lst: list1.append(i*i) return list1 lst_square([1,2,3,5,6,8]) #list comprehension:first parameter is:expression want to be returned and next is for clause: lst=[1,2,3,5,6,8] [i*i for i in lst] #if we want to square only even numbers: [i*i for i in lst if i%2==0] #if we want to square only odd numbers: [i*i for i in lst if i%2!=0]
e10dccdebccbd050c2016605bf26239ad633a45d
annasedlar/algorithms_practice
/sum_of_digits_of_giant_exponents.py
268
3.921875
4
# 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. # What is the sum of the digits of the number 2^1000? x = 2**1000 print x; y = str(x); print type(y); # print len(y); sum_digits = 0; for digits in y: sum_digits += int(digits); print sum_digits;
459218992665d84ac185404dcda0f1087677c16d
pizza2u/Python
/exemplos_basicos/python/basico_e_if.py
789
3.96875
4
nome = input("Seu nome: ") #-> input serve para pegar o dado escrito pelo usuário idade = int(input("Sua idade por favor: ")) curso = input ("Escreva seu curso: ") if idade > 30: #-> segue a mesma lógica de c e c++ : condição SE print("Você é velho") elif idade < 20 : print("Não tao novo") elif idade < 16: print("Você é novo") print ('Oi',nome, '.Sua idade é :', idade , '.Está no curso de ', curso) #-> Imprime os dados obtidos nota1 = int(input("Primeira nota: ")) #-> INT antes do INPUT: converse o número somente para inteiro nota2 = int(input ("Segunda nota: ")) nota3 = nota1 + nota2 #-> nota 3 é o resultado da soma entre as notas inseridas print('{} / {} = '.format(nota3,2)) #-> função para divisão print(nota3 / 2) #->imprime a média(nota 3)
f0b4a5f0b3e9f9fb2c644273ca4de44807625aab
Delictum/diploma-training
/3 course/Program design and programming languages/Python/LR3(1).py
1,828
4.25
4
import math ''' # {pow(x, 2) * log10(x), 1 <= x <= 2 # y ={1, x < 1 # {pow(e, 2 * x) * cos(5) * x, x > 2 print('Задание 1.') x = float(input('Введите x: ')) if (x < 1): y = 1 elif (x > 2): y = math.pow(math.e, 2 * x) * math.cos(5) * x else: y = pow(x, 2) * math.log10(x) print('y = ', y) #Написать программу, которая определяет максимальное #значение для двух различных вещественных чисел. print('Задание 2.') print('Введите два числа для нахождения максимального из них.') a = float(input('Первое число: ')) b = float(input('Второе число: ')) if (a > b): print('Первое число больше, оно = ', a) else: print('Второе число больше, оно = ', b) ''' #Дана точка на плоскости с координатами (х, у). #Составить программу, которая выдает одно из сообщений: #"Да", "Нет", "На границе" в зависимости от того, #лежит ли точка внутри заштрихованной области, #вне заштрихованной области или на ее границе print('Задание 3.') print('Введите координаты x и y.') x = float(input('x: ')) y = float(input('y: ')) if (((x == 3 or x == -3) and y == 3) or ((x == math.pi * math.pow(3, 2) or (x == -(math.pi * math.pow(3, 2))) and (y == math.pi * math.pow(3, 2))))): print('На границе') elif (((x < 3 or x > -3) and y < 3) or ((x < math.pi * math.pow(3, 2) or (x > -(math.pi * math.pow(3, 2))) and (y < math.pi * math.pow(3, 2))))): print('Да') else: print('Нет')
7a598bcfc5fe8451058c145b3eedc2cd2ea532c9
AkashPatel18/Basic
/video 6.2/Q3.py
276
3.96875
4
def factorial(n): if n ==0: print("1") elif n<0: print("fact is not posibble") if n == 1: return n else: return n*factorial(n-1) n = int(input()) if n ==0: print("1") elif n<0: print("np") print(factorial(n))
cd5ce443a78a0eef6897412970e2a9768150f2b6
Zhanar24/AWS
/Python Class/.idea/Python Class_OOP-ATM.py
3,639
3.890625
4
# class ATM: # bal = 250 #bonus # lim = 500 # def __init__(self, balance): # #Attribute # #self.bal = balance # self.bal += balance # # print("This is your balance: {}".format(balance)) # print("Your balance is : {}".format(balance)) # # Getter method - gets value out of Class/object # def show_balance(self): # print("This is your balance: {}".format(self.bal)) # # Setter method - sets value # def deposit(self, amount): # self.bal += amount # print("${} was deposited".format(amount)) # def withdrawal(self, amount): # if amount > self.bal: # print("You don't have enough suffient") # elif amount > self.lim: # print("You exceed") # else: # self.bal -= amount # print("${} was withdrawal".format(amount)) # # # # chase = ATM(20000) # chase.show_balance() # chase.bal = 100000 # chase.withdrawal(600) # chase.show_balance() # chase.deposit(100) # chase.show_balance() # chase.withdrawal(2000) #or 1000 for not negative # chase.show_balance() # class ATM: # __bal = 250 # __lim = 500 # # def __init__(self, balance): # # Attribute # self.__bal += balance # print("Your deposit amount is: {}".format(balance)) # # # Getter method - gets value out of Class/object # def show_balance(self): # print("This is your balance: {}".format(self.__bal)) # # # Setter method - sets value # def deposit(self, amount): # self.__bal += amount # print("${} was deposited".format(amount)) # # # Setter # def withdrawal(self, amount): # if amount > self.__bal: # print("You do not have sufficient funds!") # elif amount > self.__lim: # print("Withdrawal amount exceeds your daily limit") # else: # self.__bal -= amount # print("${} was withdrawn".format(amount)) # class Bank(ATM, CurrencyExchange): # def __int__(self, balance, limit): # ATM.__init__(self, balance, limit) # # def loan(self): # print("Yes , we do provide loans") # # chase = ATM(20000) # chase.show_balance() # chase.withdrawal(600) #it doesn't give money make less then 600 make 500 # chase.show_balance() # # #Bank account class ATM: __bal = 0 __lim = 500 def __init__(self, balance, limit): # Attribute self.__bal += balance self.__lim = limit print("Your deposit amount is: {}".format(balance)) # Getter method - gets value out of Class/object def show_balance(self): print("This is your balance: {}".format(self.__bal)) # Setter method - sets value def deposit(self, amount): self.__bal += amount print("${} was deposited".format(amount)) # Setter def withdrawal(self, amount): if amount > self.__bal: print("You do not have sufficient funds!") elif amount > self.__lim: print("Withdrawal amount exceeds your daily limit") else: self.__bal -= amount print("${} was withdrawn".format(amount)) class CurrencyExchange: def transfer_money(self): print("Yes, we do transfer money") class Bank(ATM, CurrencyExchange): def __init__(self, balance, limit): ATM.__init__(self, balance, limit) def loan(self): print("Yes, we do provide loans") # Bank account bof = Bank(10000, 5000) bof.show_balance() bof.deposit(2000) bof.show_balance() bof.loan() bof.transfer_money()
f4f96548f0eb74e6904ce8b81b01a2a9c99c2386
vkuberan/100-days-of-code-source
/day-6/python/arra-of-odd-rows-even-columns.py
285
3.796875
4
import numpy sampleArray = numpy.array([[3 ,6, 9, 12], [15 ,18, 21, 24], [27 ,30, 33, 36], [39 ,42, 45, 48], [51 ,54, 57, 60]]) print("Printing Input Array") print(sampleArray) print("\n Printing array of odd rows and even columns") newArray = sampleArray[::2, 1::2] print(newArray)