blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
4daa3cf70e5b150ee86291279540409b7ba40b83
CowSai4/Python_CSP_Files
/turtle/1.1/r_p_s.py
3,474
4.03125
4
import random print('Welcome to rock, paper, and scissors') print('Your answer must have the first letter be uppercase') player_choice = input('Rock, Paper, or Scissors?') computer_choice = random.choice(['Rock','Paper','Scissors']) if player_choice == 'Rock' and computer_choice == 'Paper': print("You lost!") print('Your choice',player_choice, 'vs',computer_choice) elif player_choice == 'Rock' and computer_choice == 'Scissors': print("You Won!") print('Your choice',player_choice, 'vs',computer_choice) elif player_choice == 'Rock' and computer_choice == 'Rock': print("It's at tie!") print('Your choice',player_choice, 'vs',computer_choice) elif player_choice == 'Paper' and computer_choice == 'Rock': print("You Won!") print('Your choice',player_choice, 'vs',computer_choice) elif player_choice == 'Paper' and computer_choice == 'Scissors': print("You lost!") print('Your choice',player_choice, 'vs',computer_choice) elif player_choice == 'Scissors' and computer_choice == 'Rock': print("You lost!") print('Your choice',player_choice, 'vs',computer_choice) elif player_choice == 'Scissors' and computer_choice == 'Paper': print("You Won!") print('Your choice',player_choice, 'vs',computer_choice) elif player_choice == 'Paper' and computer_choice == 'Paper': print("It's at tie!") print('Your choice',player_choice, 'vs',computer_choice) elif player_choice == 'Scissors' and computer_choice == 'Scissors': print("It's at tie!") print('Your choice',player_choice, 'vs',computer_choice) play_again = input('Do you want to play again?') if play_again == 'yes': rounds = int(input('How many rounds do you want to play?')) rounds = rounds + 1 rounds = rounds / 2 x = 0 while(x < rounds): player_choice = input('Rock, Paper, or Scissors?') computer_choice = random.choice(['Rock','Paper','Scissors']) if player_choice == 'Rock' and computer_choice == 'Paper': print("You lost!") print('Your choice',player_choice, 'vs',computer_choice) elif player_choice == 'Rock' and computer_choice == 'Scissors': print("You Won!") print('Your choice',player_choice, 'vs',computer_choice) elif player_choice == 'Rock' and computer_choice == 'Rock': print("It's at tie!") print('Your choice',player_choice, 'vs',computer_choice) elif player_choice == 'Paper' and computer_choice == 'Rock': print("You Won!") print('Your choice',player_choice, 'vs',computer_choice) elif player_choice == 'Paper' and computer_choice == 'Scissors': print("You lost!") print('Your choice',player_choice, 'vs',computer_choice) elif player_choice == 'Scissors' and computer_choice == 'Rock': print("You lost!") print('Your choice',player_choice, 'vs',computer_choice) elif player_choice == 'Scissors' and computer_choice == 'Paper': print("You Won!") print('Your choice',player_choice, 'vs',computer_choice) elif player_choice == 'Paper' and computer_choice == 'Paper': print("It's at tie!") print('Your choice',player_choice, 'vs',computer_choice) elif player_choice == 'Scissors' and computer_choice == 'Scissors': print("It's at tie!") print('Your choice',player_choice, 'vs',computer_choice) x += 1
4256fac8016484e6cd8560c57b52e969366ed854
henchhing-limbu/Interview-Questions
/Dynamic-Programming/min_path_sum.py
988
4.09375
4
""" Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. Input: [ [1,3,1], [1,5,1], [4,2,1] ] Output: 7 Explanation: Because the path 1→3→1→1→1 minimizes the sum. """ def min_path_sum(grid): if not grid or not grid[0]: return 0 row, col = len(grid), len(grid[0]) # Update the last row. They don't have option to choose for i in range(col - 2, -1, -1): grid[row-1][i] += grid[row-1][i+1] # Update the last column. They don't have option to choose for i in range(row - 2, -1, -1): grid[i][col-1] += grid[i+1][col-1] # go through remaining position in the grid and choose min from down or # cell sum. for i in range(row - 2, -1, -1): for j in range(col - 2, -1, -1): grid[i][j] += min(grid[i+1][j], grid[i][j+1]) return grid[0][0] print(min_path_sum([[1, 3, 1], [1, 5, 1], [4, 2, 1]]))
742e69b80df2573b5ff0fd992cc71247f1a88774
andreupomar/python
/Ejercicio 2/Celsius a Farenheit.py
357
4.125
4
#Andreu Pomar Cabot #Práctica 2: Hacer un programa para convertir Celsius a Farenheit print ("Este programa convierte una temperatura en grados centígrados a Farenheit.\n") C= float(input ("Introduzca la temperatura en ºC que desea convertir a Farenheit \n")) F = C*(9//5)+32 print ("\n %f ºC son %f ºF" % (C, F)) input ("Presione Enter para cerrar el programa")
05a2a5f526af8253522b8d69ae30568f419a233f
SonramSirirat/data-science-programming
/Quiz/Quiz_2C-Q12_640631037.py
418
3.734375
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 16 2021 @author: sonram_sirirat """ # Quiz 12: Full Adder carryIn, A, B = input("Enter three digits: ").split() carryIn = int(carryIn) A = int(A) B = int(B) def fullAdder(carryIn, A, B): Sum = (A or B) Sum = carryIn or Sum carryOut = Sum or (A or B) or (A and B) print("Sum = ", Sum) print("Carry Out = ", carryOut) fullAdder(A, B, carryIn)
501ddbb9f0c39118358ac2801394c91519174e33
Mittenss2010/PythonPractice
/tests/测试-数字在记录中.py
86
3.625
4
temp = [1,3,5,7] for i in range(10): if i not in temp: print(i)
4c5d4e12729a7c658704aeb824eaa25573b04912
jnepal/OReilly-Python-Beyond-the-Basics-OOP
/2.Inheritance and polymorphism/assignment.py
1,087
3.8125
4
import abc from datetime import datetime class WriteFile: __metaclass__ = abc.ABCMeta def __init__(self, filename): self.filename = filename @abc.abstractmethod def write(self): return def write_line(self, text): # with will automatically run cleanup routine i.e close the file with open(self.filename, 'a') as file: file.write(text + '\n') class DelimFile(WriteFile): def __init__(self, filename, delimiter): super().__init__(filename) self.delimiter = delimiter def write(self, list): line = self.delimiter.join(list) self.write_line(line) class LogFile(WriteFile): def write(self, line): date = datetime.now() date_string = date.strftime('%Y-%m0-%d %H:%M') self.write_line('{0} {1}'.format(date_string, line)) logFile = LogFile('log.txt') delimFile = DelimFile('text.csv', ',') logFile.write('This is a log message') logFile.write('This is another log message') delimFile.write(['a', 'b', 'c', 'd']) delimFile.write(['1', '2', '3', '4'])
e108cb855f1d4e69d877ceda2d2847eae7e61263
bawNg/pyPickup
/plural.py
2,009
3.703125
4
#!/usr/bin/env python import re en_rules = """\ ^(sheep|deer|fish|moose|aircraft|series|haiku)$ ($) \1 [ml]ouse$ ouse$ ice child$ $ ren booth$ $ s foot$ oot$ eet ooth$ ooth$ eeth l[eo]af$ af$ aves sis$ sis$ ses ^(hu|ro)man$ $ s man$ man$ men ^lowlife$ $ s ife$ ife$ ives eau$ $ x ^[dp]elf$ $ s lf$ lf$ lves [sxz]$ $ es [^aeioudgkprt]h$ $ es (qu|[^aeiou])y$ y$ ies $ $ s""" def rules(language): lines = en_rules.splitlines() if language != "en": lines = file('plural-rules.%s' % language) for line in lines: print line pattern, search, replace = line.split() yield lambda word: re.search(pattern, word) and re.sub(search, replace, word) def plural(noun, language='en'): """returns the plural form of a noun""" for applyRule in rules(language): result = applyRule(noun) if result: return result def pluralize(n, word): return "%s %s" % (n, plural(word) if n > 1 else word) def pluralized(n, word): return plural(word) if n > 1 else word
4969f5112fcbc980ada4fe1c134f90b71a87e87b
ralevn/Python_scripts
/PyCharm_projects_2020/Fundamentals/Nested_Loops/Combinations.py
518
3.71875
4
""" Напишете програма, която изчислява колко решения в естествените числа (включително и нулата) има уравнението: x1 + x2 + x3 = n Числото n е цяло число и се въвежда от конзолата. """ n = int(input()) counter = 0 for x1 in range(25): for x2 in range(25): for x3 in range(25): if x1 + x2 + x3 == n: counter += 1 print(counter)
fe5870820248bd795b78a08d1bed8e913fd78335
angel-robinson/carrion-chancafe-trabajo06
/carrion/condicional_multiple/multiple02.py
988
3.734375
4
import os #boleta de venta #declaracion de variabes nombre,cant_producto="",0.0 precio=0.0 #input nombre=os.sys.argv[1] cant_producto=int(os.sys.argv[2]) precio=float(os.sys.argv[3]) #procesing precio_total=round(cant_producto*precio) #output print("###############################") print("# BOLETA DE VENTA ") print("#") print("# cliente :",nombre) print("#NOMBRE DEL PRODUCTO:",cant_producto) print("# PRECIO PRODUCTO :",precio) print("costo total s/. :",precio_total) print("###############################") #condicional simple #el cliente se gana un paneton si supera el precio total #inicio_if if(precio_total>50): print("felicidades,ha ganado un paneton") #fin_if #si el precio total esmenor que s/.50 se imprime:"si se lleva mas productos le regalamos un paneton" #inicio_if if(precio_total<50): print("si se lleva mas productos le regalamos un paneton") #fin_if #inicio_if if(precio_total==50): print("casi logra llevarse un paneton") #fin_if
2e580a0782a806c88c26b870ca811f7aecb51bf2
hardhary/PythonByExample
/Challenge_087.py
390
4.59375
5
#087 Ask the user to type in a word and then display it backwards on separate lines. For instance, if they type in “Hello” it should display as shown below: def backwards(): word = input('Enter a word: ') length = len(word) num = 1 for i in word: position = length - num letter = word[position] print(letter) num = num + 1 backwards()
ed866ebe3bd7021aeb7ae6aa50c5e411688fca6c
kipland-m/python-snippets
/PyCalculator.py
1,168
3.875
4
# 02/21/18 import random import time import statistics import sys print("Welcome to Kip's Python Calculator!\n") time.sleep(.5) CalcFunction = input("""Please choose a function\n 1. Addition\n 2. Subtraction\n 3. Multiplication\n 4. Division\n 5. Quit\n Please enter a number: """) if CalcFunction == "1": AdditionX = int(input("\nPlease enter your first number: ")) AdditionY = int(input("\nPlease enter your second number: " )) print("\nYour answer is: ",AdditionX + AdditionY,"\n") if CalcFunction == "2": SubtractionX = int(input("\nPlease enter your first number: ")) SubtractionY = int(input("\nPlease enter your second number: " )) print("\nYour answer is: ",SubtractionX - SubtractionY,"\n") if CalcFunction == "3": MultiplyX = int(input("\nPlease enter your first number: ")) MultiplyY = int(input("\nPlease enter your second number: " )) print("\nYour answer is: ",MultiplyX * MultiplyY,"\n") if CalcFunction == "4": DivideX = int(input("\nPlease enter your first number: ")) DivideY = int(input("\nPlease enter your second number: " )) print("\nYour answer is: ",DivideX / DivideY,"\n") if CalcFunction == "5": sys.exit()
a38739c2fa2c242811821ac1232993c8abf52047
billdonghp/Python
/Person.py
787
3.890625
4
''' 封装人员信息 Person类 ''' class Person: #属性 name = "林阿华" age = 20 rmb = 50.0 #构造方法 外界创建类的实例时调用 #构选方法是初始化实例属性的最佳时机 def __init__(self,name,age,rmb): print("老子被创建了") self.name = name self.age = age self.rmb = rmb # def __str__(self): return "{name:%s,age:%d,rmb:%s}"%(self.name,self.age,format(self.rmb,".2f")) #方法或函数 #self 类的实例 #自我介绍方法 def tell(self): print("我是%s,我%d岁了,我有%s元"%(self.name,self.age,format(self.rmb,".2f"))) if __name__ =='__main__': p = Person("易中天",50,100000.0) p.tell() print(p)
c1c5aac871e3e655e4e4405165508fb75965ff16
ybsdegit/Life_Process_Study
/StudyPacticePython/Base_Python/python_base/进程和线程/多线程.py
722
3.65625
4
#!/usr/bin/env python # encoding: utf-8 # -*- coding: utf-8 -*- # @contact: ybsdeyx@foxmail.com # @software: PyCharm # @time: 2019/3/7 14:17 # @author: Paulson●Wier # @file: 多线程.py # @desc: import time ,threading # 新线程执行的代码: def loop(): print('Thread %s is running...' % threading.current_thread().name) n = 0 while n < 5: n +=1 print('Thread %s >>> %s '% (threading.current_thread().name,n)) time.sleep(1) print('Thread %s ended...' %threading.current_thread().name) print('Thread %s running1...' %threading.current_thread().name) t = threading.Thread(target=loop,name='LoopThread') t.start() t.join() print('thread %s ended.' %threading.current_thread().name)
22ea55ffa5ecdabf6f4d4706cfadfd934b07894a
sirrah23/AddressBook
/authentication/test/jwtmanager-test.py
1,974
3.640625
4
"""Tests for any JWT related logic. """ from authentication.jwt.jwtmanager import JWTManager from authentication.user.user import FakeUserManager import unittest class CreateJWTTest(unittest.TestCase): def test_creates_a_new_JWT(self): """Test that a JWT is created successfully in the case where valid credentials are provided. """ jwtm = JWTManager(userManager=FakeUserManager(validCredFlag=True), secret='secret') newToken = jwtm.createNewJWT('myUser', 'myPassword') assert isinstance(newToken, str) assert len(newToken) > 0 def test_fails_to_create_new_JWT(self): """Test that the JWT creation process fails in the case where invalid credentials are provided. """ with self.assertRaises(ValueError): jwtm = JWTManager(userManager=FakeUserManager(validCredFlag=False), secret='secret') newToken = jwtm.createNewJWT('myUser', 'myPassword') class DecodeJWTTest(unittest.TestCase): def test_decode_an_existing_JWT(self): """Test that a JWT can be decoded successfully. """ jwtm = JWTManager(userManager=FakeUserManager(validCredFlag=True), secret='secret') newToken = jwtm.createNewJWT('myUser', 'myPassword') payload = jwtm.decodeJWT(newToken) assert 'user_id' in payload assert payload['username'] == 'myUser' def test_decode_an_exisiting_JWT_Incorrectly(self): """Test that a JWT cannot be decoded when you, say, use the wrong secret key. """ with self.assertRaises(ValueError): jwtmOne = JWTManager(userManager=FakeUserManager(validCredFlag=True), secret='secret1') jwtmTwo = JWTManager(userManager=FakeUserManager(validCredFlag=True), secret='secret2') newToken = jwtmOne.createNewJWT('myUser', 'myPassword') payload = jwtmTwo.decodeJWT(newToken) if __name__ == '__main__': unittest.main()
b5aee79b07e7bb0d5318cad15c2733ae7a427cb3
ParsaAlizadeh/PentagoAI
/welcome.py
549
3.71875
4
import tkinter as tk name = None def setName(): global name name = e1.get() root.destroy() def gui(): global root, e1 root = tk.Tk() root.geometry("300x100") root.title("PentagoWelcome") l1 = tk.Label(root, text="Your name:") e1 = tk.Entry(root) b1 = tk.Button(root, text="Start!", command=setName) l1.place(x=10, y=10, width=100, height=30) e1.place(x=110, y=10, width=180, height=30) b1.place(x=100, y=50, width=100, height=30) root.mainloop() def getName(): gui() return name
bbfc8f5db504213a97c389ea0532c46810742af4
elena0624/leetcode_practice
/LL_Intersection_of_Two_Linked_Lists.py
1,927
3.8125
4
# My solution- Brute force TLE not sure if correct # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: a_list=[] while headA: a_list.append(headA) headA=headA.next while headB: if headB in a_list: return headB else: headB=headB.next return None #%% # My solution- accepted # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: tempA=headA tempB=headB while tempA and tempB: tempA=tempA.next tempB=tempB.next headC=headA headD=headB if tempA or tempB:# 不一樣長 tempC=tempA if tempA else tempB headC=headA if tempA else headB headD=headB if tempA else headA while tempC: tempC=tempC.next headC=headC.next while headC!=headD: headC=headC.next headD=headD.next return headC #%% Elegant answer class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: pA = headA pB = headB while pA != pB: pA = headB if pA is None else pA.next pB = headA if pB is None else pB.next return pA # Note: In the case lists do not intersect, the pointers for A and B # will still line up in the 2nd iteration, just that here won't be # a common node down the list and both will reach their respective ends # at the same time. So pA will be NULL in that case.
8c99030cbb484bd43f5f97bcd113935bc343a4ab
SilversRL-Yuan/CC150_Python
/Chapter2/linkedlist.py
2,147
4.0625
4
class Node: """docstring for Node.""" def __init__(self, data = None, next = None): self.data = data self.next = next class LinkedList: """This LinkedList has AddNode, DelNode, InsertNode in_place Qsort and GetLeng methods.""" def __init__(self): #self.current_node = Node() self.head = Node() self.current_node = Node() #self.tail = Node() def __str__(self): """Return a str(list) that contains data in order.""" data_list = [] indexing_node = self.head while indexing_node: data_list.append(indexing_node.data) indexing_node = indexing_node.next return str(data_list) def AddNode(self, data): new_node = Node(data, None) if self.head.data: # if not empty self.current_node.next = new_node# make old tail node point to new node self.current_node = self.current_node.next else: self.head = new_node self.current_node = self.head def DelNode(self, data): '''Delete the node with data.''' indexing_node = self.head while indexing_node.next: if indexing_node.next.data == data: indexing_node.next = indexing_node.next.next break indexing_node = indexing_node.next else: print('No data found!') raise ValueError(data) def InsertNode(self, data, data_new): '''Insert one node after the node with data.''' indexing_node = self.head while indexing_node.next: # if not last one if indexing_node.data == data: new_node = Node(data_new, None) new_node.next = indexing_node.next indexing_node.next = new_node break indexing_node = indexing_node.next else: print('No data found!') raise ValueError(data) def GetLeng(self): indexing_node = self.head i = 1 while indexing_node.next: i += 1 indexing_node = indexing_node.next return i def Reverse(self): '''Reverse the Single LinkedList''' node = self.head node_list = [node] while node.next: node_list.append(node.next) node = node.next self.head = node while len(node_list) > 0: node.next = node_list.pop() node = node.next node.next = None # test #ll = LinkedList() #ll.AddNode(3) #ll.AddNode(7) #ll.AddNode(5) #ll.InsertNode(3, 2)
1c001a97d232693e4a9b68993f45534af28afc92
22-Pig/temp
/python/chap1/even.py
96
3.734375
4
x = eval(input("请输入一个整数:")) if x % 2 == 0: print("YES") else: print("NO")
4128fc4717eba99a3b6216890c486f3883945faa
phanitejakesha/LeetCode
/Linked_List/reverseLinkedList.py
547
3.765625
4
#Leetcode Question Number 92 #Reverse Linked List class Solution: def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ li =[] temp = head temp1 = head while temp!=None: li.append(temp.val) temp =temp.next reverse = li[:m-1]+li[m-1:n][::-1]+li[n:] while temp1!=None: temp1.val = reverse.pop(0) temp1=temp1.next return head
40d0a483a56e78358986397caa81bd7a684fb52e
sanderheieren/in1000
/oblig1/dato2.py
637
3.90625
4
# Programmet skal stille bruker om to ulike datoer og sjekke om datoene kommer kronologisk # 1, skal lese inn to ulike datoer fra bruker, heltall for dag og måned dato = input('Skriv inn en dato: (DD/MM)\n') forsteDag = int(dato.split('/')[0]) forsteMnd = int(dato.split('/')[1]) nyDato = input('Skriv inn en ny dato: (DD/MM)\n') andreDag = int(nyDato.split('/')[0]) andreMnd = int(nyDato.split('/')[1]) if (forsteMnd < andreMnd or (forsteMnd == andreMnd and forsteDag < andreDag)): print('Riktig rekkefølge!') elif (forsteMnd == andreMnd and forsteDag == andreDag): print('Samme dato!') else: print('Feil rekkefølge!')
25259c3ddd6519c753fbf952839582bc5022a304
SebastianThomas1/coding_challenges
/codility/17_dynamic_programming/number_solitaire.py
2,993
3.5625
4
# Sebastian Thomas (coding at sebastianthomas dot de) # https://app.codility.com/programmers/lessons/17-dynamic_programming/number_solitaire/ # # NumberSolitaire # # A game for one player is played on a board consisting of N consecutive # squares, numbered from 0 to N − 1. There is a number written on each # square. A non-empty array A of N integers contains the numbers written # on the squares. Moreover, some squares can be marked during the game. # # At the beginning of the game, there is a pebble on square number 0 and # this is the only square on the board which is marked. The goal of the # game is to move the pebble to square number N − 1. # # During each turn we throw a six-sided die, with numbers from 1 to 6 on # its faces, and consider the number K, which shows on the upper face # after the die comes to rest. Then we move the pebble standing on # square number I to square number I + K, providing that square number # I + K exists. If square number I + K does not exist, we throw the die # again until we obtain a valid move. Finally, we mark square number # I + K. # # After the game finishes (when the pebble is standing on square number # N − 1), we calculate the result. The result of the game is the sum of # the numbers written on all marked squares. # # For example, given the following array: # A[0] = 1 # A[1] = -2 # A[2] = 0 # A[3] = 9 # A[4] = -1 # A[5] = -2 # one possible game could be as follows: # - the pebble is on square number 0, which is marked; # - we throw 3; the pebble moves from square number 0 to square number # 3; we mark square number 3; # - we throw 5; the pebble does not move, since there is no square # number 8 on the board; # - we throw 2; the pebble moves to square number 5; we mark this # square and the game ends. # The marked squares are 0, 3 and 5, so the result of the game is # 1 + 9 + (−2) = 8. This is the maximal possible result that can be # achieved on this board. # # Write a function: # def solution(A) # that, given a non-empty array A of N integers, returns the maximal # result that can be achieved on the board represented by array A. # # For example, given the array # A[0] = 1 # A[1] = -2 # A[2] = 0 # A[3] = 9 # A[4] = -1 # A[5] = -2 # the function should return 8, as explained above. # # Write an efficient algorithm for the following assumptions: # - N is an integer within the range [2..100,000]; # - each element of array A is an integer within the range # [−10,000..10,000]. def solution(a): max_sums = [a[0]] for idx in range(1, min(len(a), 6)): max_sums.append(max(max_sums[idx - throw] + a[idx] for throw in range(1, 7) if idx >= throw)) for idx in range(6, len(a)): max_sums.append(max(max_sums[-throw] + a[idx] for throw in range(1, 7))) del max_sums[0] return max_sums[-1] if __name__ == '__main__': print(solution([1, -2, 0, 9, -1, -2])) # 8
d6ec217622f0e160e267cdda37a2bdb10f41908d
DongHyukShin93/BigData
/python/python04/Python04_04_FormatFun02_신동혁.py
179
3.90625
4
#Python04_04_FormatFun02_신동혁 a="My name is {}.".format("Shin") b="{2}×{1}= {0}".format(11,2,11*2) print(a) print(b) c="{a}×{b}= {c}".format(a=11,b=11*2,c=2) print(c)
8143415fca7ca69c5b153a786814d516f1431085
Alexvi011/CYPHugoPV
/libro/problemas_resueltos/capitulo3/problema3_9.py
164
3.75
4
N=int(input("Ingrese un numero entero positivo: ")) I=1 SERIE=0 while(I<=N): SERIE+=(I)**(I) print(SERIE) I+=1 print(f"La suma de la serie es:{SERIE}")
7a652794292a97331f961c0062b729a5290426a3
soniaarora/Algorithms-Practice
/Solved in Python/LeetCode/arrays/maxSubArray.py
446
3.609375
4
class maxSubArray(object): def main(self): print(self.maxSubArray([4,-2,0,-1,2,7])) def maxSubArray(self, array): dp = [] dp.append(array[0]) maxVal = dp[0] for i in range(1,len(array)): val = array[i] + dp[i-1] if dp[i-1] > 0 else 0 dp.append(val) maxVal = max(maxVal, dp[i]) return maxVal if __name__=="__main__": maxSubArray().main()
49d380fa5b2840d7a3358938e26969bbf55bda06
arifiorino/Shapes-A-Puzzle-Game
/Python Generator/GenerateLevel.py
7,531
3.640625
4
import random,math,json def randomDirection(): direction=[0,0] direction[random.randint(0,1)]=random.choice([-1,1]) return direction def distanceTo(p1,p2): return math.sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2) def randomSquareWithTendency(squaresPos, tendencySquarePos,smallest=1.0,power=3): # print("got:",squaresPos,"tending towards:",tendencySquarePos) probabilities=[distanceTo(squarePos,tendencySquarePos) for squarePos in squaresPos] largest=max(probabilities) probabilities=[largest-x+smallest for x in probabilities] #Flip because more distance is less probability probabilities=[x**power for x in probabilities] #Stretch data # print(probabilities) # print("max:",probabilities.index(max(probabilities)),max(probabilities),squaresPos[probabilities.index(max(probabilities))]) r=random.random()*sum(probabilities) for i in range(len(probabilities)): if sum(probabilities[:i+1])>r: # print("picked:",i,probabilities[i],squaresPos[i]) # input() return squaresPos[i] def randomAdjacentSquareWithTendency(squarePos, tendencySquarePos,squares2D=None): sides=[[squarePos[0],squarePos[1]-1],[squarePos[0]+1,squarePos[1]],[squarePos[0],squarePos[1]+1],[squarePos[0]-1,squarePos[1]]] newSquarePos=randomSquareWithTendency(sides,tendencySquarePos) if not squares2D is None: width,height=len(squares2D[0]),len(squares2D) while (not newSquarePos[0] in range(width)) or (not newSquarePos[1] in range(height)) or squares2D[newSquarePos[1]][newSquarePos[0]]!=0: # print(not newSquarePos[0] in range(width), not newSquarePos[1] in range(height), squares2D[newSquarePos[1]][newSquarePos[0]]!=0) # print(squares2D[newSquarePos[1]][newSquarePos[0]]) sides.remove(newSquarePos) if len(sides)<=0: return None newSquarePos=randomSquareWithTendency(sides,tendencySquarePos) return newSquarePos def slightRandom(number,d=1): return round(number+(random.random()*2*d)-d) def addVectors(v1,v2): return [v1[0]+v2[0],v1[1]+v2[1]] def subtractVectors(v1,v2): return [v1[0]-v2[0],v1[1]-v2[1]] def randomZeroSquare2D(squares, tendency=False): width,height=len(squares[0]),len(squares) possiblePos=[] for y in range(height): for x in range(width): if squares[y][x]==0: possiblePos.append([x,y]) square=None while square is None or squares[square[1]][square[0]]!=0: if tendency: square=randomSquareWithTendency(possiblePos,[width/2,height/2],.1,4) # print("picked:",square) else: square=[random.randint(0,len(squares[0])-1),random.randint(0,len(squares)-1)] return square def randomSquare2D(squares, tendency=False): width,height=len(squares[0]),len(squares) possiblePos=[] for y in range(height): for x in range(width): if squares[y][x]!=0: possiblePos.append([x,y]) square=None while square is None or squares[square[1]][square[0]]==0: if tendency: square=randomSquareWithTendency(possiblePos,[width/2,height/2],1,3) # print("picked:",square) else: square=[random.randint(0,len(squares[0])-1),random.randint(0,len(squares)-1)] return square def output2DBoolArray(squaresOn,on="■ ",off=" ",start=""): print(start) for y in range(len(squaresOn)): for x in range(len(squaresOn[0])): if squaresOn[y][x]: print(on,end="") else: print(off,end="") print() def output2DArray(squares,start=""): print(start) for y in range(len(squares)): for x in range(len(squares[0])): print(squares[y][x],end="") print() def squares2DToSquaresPos(array2D): squaresPos=[] for y in range(len(array2D)): for x in range(len(array2D[0])): if array2D[y][x]!=0: squaresPos.append([x,y]) return squaresPos def squares2DToSquares(squares2D): squares=[] for row in squares2D: squares.extend(row) return squares def mean(array): return sum(array)/len(array) def meanSquare(squares2D): squaresPos=squares2DToSquaresPos(squares2D) return [mean([s[0] for s in squaresPos]),mean([s[1] for s in squaresPos])] def generateLevelSquares(levelWidth, levelHeight): backgroundWidth, backgroundHeight= round(levelWidth * .6), round(levelWidth * .6) if levelWidth%2 != backgroundWidth%2: backgroundWidth-=1 backgroundSquares2D=[[0 for x in range(backgroundWidth)] for y in range(backgroundHeight)] numSquares=round(backgroundWidth*backgroundHeight*(math.pi/4)*.8) print("Number of squares:",numSquares) numRandomSquares=max(slightRandom(numSquares/8,1.5),1) #(1 in 8)+-2 are random print("Number of random squares:",numRandomSquares) numPieces= round(numSquares/3) print("Number of pieces:",numPieces) piecesSquaresPos=[[] for pieceI in range(numPieces)] for pieceI in range(numPieces): rSquare=randomZeroSquare2D(backgroundSquares2D, True)#.4 backgroundSquares2D[rSquare[1]][rSquare[0]]=pieceI+1 piecesSquaresPos[pieceI].append(rSquare) while sum([len(pieceSquaresPos) for pieceSquaresPos in piecesSquaresPos])<numSquares: numberOfSquaresForPieceI=[] for pieceI in range(numPieces): count=0 for y in range(backgroundHeight): for x in range(backgroundWidth): if backgroundSquares2D[y][x]==pieceI+1: count+=1 numberOfSquaresForPieceI.append(count) # print(numberOfSquaresForPieceI) piecesToChooseFrom=[pieceI for pieceI in range(numPieces) if numberOfSquaresForPieceI[pieceI]<=mean(numberOfSquaresForPieceI)+1.5 and numberOfSquaresForPieceI[pieceI]<5] # print(piecesToChooseFrom) chosenPieceI=random.choice(piecesToChooseFrom) # print("Chose piece:",chosenPieceI+1) s=randomSquareWithTendency(piecesSquaresPos[chosenPieceI],[backgroundWidth/2,backgroundHeight/2]) newSquare=randomAdjacentSquareWithTendency(s,[backgroundWidth/2,backgroundHeight/2],backgroundSquares2D) count=0 while newSquare is None and count<10000: s=randomSquareWithTendency(piecesSquaresPos[chosenPieceI],[backgroundWidth/2,backgroundHeight/2]) newSquare=randomAdjacentSquareWithTendency(s,[backgroundWidth/2,backgroundHeight/2],backgroundSquares2D) count+=1 if count>=10000: newSquare=randomZeroSquare2D(backgroundSquares2D, True) # print("Creating new start:",chosenPieceI+1,newSquare) piecesSquaresPos[chosenPieceI].append(newSquare) backgroundSquares2D[newSquare[1]][newSquare[0]]=chosenPieceI+1 output2DArray(backgroundSquares2D) for randomSquareI in range(numRandomSquares): randomSquarePos=randomSquare2D(backgroundSquares2D)#,True boardString=json.dumps(backgroundSquares2D) if boardString.count(str(backgroundSquares2D[randomSquarePos[1]][randomSquarePos[0]]))!=1: #If it's not the last one left backgroundSquares2D[randomSquarePos[1]][randomSquarePos[0]]=random.randint(0,numPieces-1) print("Random Square at:",randomSquarePos[0],",",randomSquarePos[1]) output2DArray(backgroundSquares2D) return backgroundSquares2D # generateLevelSquares(6,8)
85fd1447be3af3d12fa9cf0df585073bbecddde5
Raun551/pythontraining
/marks_func.py
457
3.703125
4
def marks(a): while a >= 0 and a <=100: if a >= 95: print("Passed With Disctinction") break elif a < 95 and a >= 75: print("Passed With First Class") break elif a < 75 and a >= 40: print("Passed with Second Class") break else: print("You have failed.Study hard next time") break a = eval(input("Enter the marks: ")) marks(a)
dd3dc28dc9c9173739223003afcbb5cbc6a9cb89
mehdimashayekhi/codeChallenge-Interview-Practice
/bricks Game.py
443
3.546875
4
#https://www.hackerrank.com/challenges/play-game/problem def bricksGame(arr): # # Write your code here. # n=len(arr) dp=[0 for _ in range(n)] curSum=0 for i in range(n-1,-1,-1): curSum+=arr[i] if i>=n-3: dp[i]=curSum else: dp[i] = curSum-dp[i+1] dp[i] = max(dp[i], curSum-dp[i+2]) dp[i] = max(dp[i], curSum-dp[i+3]) return dp[0]
70dc2ad03e0e0e9dfabc75e80deb852262136dd5
amyfang3/PokemonRed_TextAdventure
/items.py
2,769
3.5625
4
class Item(): # The base class for all items def __init__(self, name, description): self.name = name self.description = description def __str__(self): return self.name ############## # HP Potions # ############## class HPPotion(Item): def __init__(self, name, description, value): self.value = value super().__init__(name, description) class Potion(HPPotion): def __init__(self): super().__init__(name = "Potion", description = "Heals a Pokemon by 20 HP", value = 20) class SuperPotion(HPPotion): def __init__(self): super().__init__(name = "Super Potion", description = "Heals a Pokemon by 50 HP", value = 50) class MoomooMilk(HPPotion): def __init__(self): super().__init__(name = "Moomoo milk", description = "Heals a Pokemon by 100 HP", value = 100) class HyperPotion(HPPotion): def __init__(self): super().__init__(name = "Hyper Potion", description = "Heals a Pokemon by 200 HP", value = 200) ############# # PokeBalls # ############# class PokeBall(Item): def __init__(self, name, description, catchRate, buy_price, sell_price): self.catchRateMultiplier = catchRate self.buy_price = buy_price self.sell_price = sell_price super().__init__(name, description) class RegularBall(PokeBall): def __init__(self): super().__init__(name = "PokeBall", description = "A BALL thrown at wild Pokemon to catch them.", catchRate = 1, buy_price = 200, sell_price = 100) class GreatBall(PokeBall): def __init__(self): super().__init__(name = "Great Ball", description = "A BALL thrown at wild Pokemon to catch them. More effective than a PokeBall.", catchRate = 1.5, buy_price = 600, sell_price = 300) class UltraBall(PokeBall): def __init__(self): super().__init__(name = "Ultra Ball", description = "A BALL thrown at wild Pokemon to catch them. More effective than a Great Ball.", catchRate = 2, buy_price = 1200, sell_price = 600) class MasterBall(PokeBall): def __init__(self): super().__init__(name = "Master Ball", description = "A BALL that captures any wild Pokemon without fail.", catchRate = 255, buy_price = None, sell_price = None)
70b0f37baf9f998ef030572328f348dcc72992e1
juanmaMacGyverCode/kataStringCalculatorPython
/StringCalculator.py
5,090
3.9375
4
class StringCalculator: def __init__(self): pass def add(self, text): self.errors = "" text = self.__treatment_of_custom_separators(text) self.__find_errors(text) if len(self.errors) > 0: return self.errors return self.__to_do_add(text) def __to_find_negative_numbers(self, text): numbersOnList = self.__change_text_with_list(text, "\n") negativeNumbers = "" for number in numbersOnList: try: if number != "" and (number[0] == "-" or self.__is_numeric_or_float(number)) and float(number) < 0: raise ValueError("El nombre no está completo") except ValueError: negativeNumbers += number + "," negativeNumbers = negativeNumbers[0:len(negativeNumbers)-1] if len(negativeNumbers) > 0: self.__phrase_self_error("Negative not allowed : " + negativeNumbers + ".") def __phrase_self_error(self, error): if len(self.errors) > 0: self.errors += "\n" + error else: self.errors += error def __treatment_of_custom_separators(self, text): haveTwoSlash = text.find("//") == 0 if haveTwoSlash: if text[len(text) - 1] == "\n": return "0" splitTheCustomExpresion = text.split("\n") separator = splitTheCustomExpresion[0][2:] phraseWithoutSeparator = splitTheCustomExpresion[1].split(separator) import re for count in range(0, len(phraseWithoutSeparator)): if phraseWithoutSeparator[count] != "" and (self.__is_numeric_or_float(phraseWithoutSeparator[count]) == None or self.__is_numeric_or_float(phraseWithoutSeparator[count]).group() != phraseWithoutSeparator[count]): fragmento = re.search("[0-9]+([.][0-9]+)?", phraseWithoutSeparator[count]).group() if re.search("[0-9]+([.][0-9]+)?", phraseWithoutSeparator[count][0]) == None: fragmentoErroneo = splitTheCustomExpresion[1][splitTheCustomExpresion[1].find(fragmento)-1] self.errors += "'" + separator + "' expected but '" + fragmentoErroneo + "' found at position " + str(splitTheCustomExpresion[1].find(fragmento)-1) + "." else: caracteresAnterioresCorrectos = self.__is_numeric_or_float(phraseWithoutSeparator[count]).group() posicionError = re.search(caracteresAnterioresCorrectos, splitTheCustomExpresion[1]).end() self.errors += "'" + separator + "' expected but '" + splitTheCustomExpresion[1][posicionError] + "' found at position " + str(posicionError) + "." text = splitTheCustomExpresion[1].replace(separator, ",") return text return text def __to_do_add(self, text): numbers = self.__change_text_with_list(text, "\n") if self.__are_there_many_numbers(numbers): return self.__addAllNumbers(numbers) if self.__is_numeric_or_float(text): return text else: return "0" def __find_errors(self, text): if len(text) > 0: self.__to_find_negative_numbers(text) self.__error_number_expected(text) self.__error_final_separator(text) def __error_final_separator(self, text): if len(text) > 1 and (text[len(text) - 1] == "," or text[len(text) - 1] == "\n"): self.__phrase_self_error("Number expected but EOF found.") def __error_number_expected(self, text): mapErrors = {} mapErrors = self.__find_patterns(",\n", text, mapErrors) mapErrors = self.__find_patterns("\n,", text, mapErrors) mapErrors = self.__find_patterns(",,", text, mapErrors) mapErrors = self.__find_patterns("\n\n", text, mapErrors) errorPhrase = "" if len(mapErrors) > 0: for error in mapErrors: self.__phrase_self_error("Number expected but '" + self.__checkIfNewline(mapErrors[error][1]) + "' found at position " + str(error + 1) + ".") return errorPhrase def __find_patterns(self, pattern, text, mapErrors): import re for match in re.finditer(pattern, text): start = match.start() group = match.group() mapErrors[start] = group return mapErrors def __checkIfNewline(self, character): if character == "\n": return "\\n" return character def __change_text_with_list(self, text, pattern): text = text.replace(pattern, ",") return text.split(",") def __are_there_many_numbers(self, numbers): return len(numbers) > 1 def __is_numeric_or_float(self, text): import re return re.match("[0-9]+[.][0-9]+|[0-9]+", text) def __addAllNumbers(self, numbers): import functools import operator return str(functools.reduce(lambda a, b: float(a)+float(b), numbers))
d4e1ab2c6137a2d5b750203219b67b15c0bdbd60
SimaSheibani/Assignments_Northeastern_University
/fever_diagnosis_system/fevre_diagnosis_system.py
3,512
3.703125
4
def main(): def ask_headach(): aching_bone = input("Do you have aching bones or aching joints? \ (y/n)\n") while (aching_bone == "y") or (aching_bone == "n"): if (aching_bone == "y"): print("Possibilities include viral infection.") break else: rash = input("Do you have a rash? (y/n)\n") if (rash == "y"): print("Insufficient information to list possibilities.") break else: sore_throat = input("Do you have a sore throat? (y/n)\n") if (sore_throat == "y"): print("Possibilities include a throat infection.") break else: back_pain = input("Do you have back pain just \ above the waist with chills and fever? (y/n)\n") if (back_pain == "y"): print("Possibilities include kidney infection.") break else: pain_urination = input("Do you have pain \ urinating or are urinating more often? (y/n)\n") if (pain_urination == "y"): print("Posiibilities include a urinary \ tranct infection.") break else: sun_condition = input("Have you spent the day \ in the sun or in hot conditions? (y/n)\n") if (sun_condition == "y"): print("Possiblities sunstroke or heat \ exhaustion.") break else: print("insufficient information to list \ possibilities.") break coughing = input("are you couphing? (y/n)\n") while (coughing == "y") or (coughing == "n"): if (coughing == "y"): short_of_breath = input("Are you short of breath or wheezing or \ couphing up phlegm? (y/n)\n") if (short_of_breath == "y"): print("Possibilities include pneumonia or infection of \ airways") break else: headach = input("Do you have a headache? (y/n)\n") if (headach == "y"): print("Possibilities include viral infection") break else: ask_headach() break else: headach = input("Do you have a headache? (y/n)\n") if (headach == "y"): nasea = input("Are you experiencing any of the following: \ pain when bending your head forward, nausea or vomiting, bright light \ hurting your eyes, drowsiness or confusion? (y/n)\n") if (nasea == "y"): print("Possibilities include meningitis.") break else: diarrhea = input("Are you vomiting or had diarrhea? \ (y/n)\n") if (diarrhea == "y"): print("Posibilities include digestive tract \ infection.") break else: ask_headach() break else: ask_headach() break main()
1f9e7c9ab616d1fdbf42d12bc3d84b082ccfc8d6
kki4485/haedal
/test.py
403
3.5625
4
class student: def __init__(self,name,age): self.name=name self.age=age def info(self): print(f'이름: {self.name}') print(f'나이: {self.age}') print() student1=student('김주희',22) student2=student('박주희',25) student3=student('최주희',21) student4=student('이주희',23) student1.info() student2.info() student3.info() student4.info()
f5b70d3c6afb18923ef9ffb51b4bf5221ed50f1e
2892931976/my-python-code
/51BLOG/geturl3.py
1,615
3.5
4
#!/bin/env python # -*- coding:utf-8 -*- import requests from bs4 import BeautifulSoup class get_urldic: #获取搜索关键字 def get_url(self): urlList = [] first_url = 'http://blog.51cto.com/search/result?q=' after_url = '&type=&page=' try: search = input("Please input search name:") page = int(input("Please input page:")) except Exception as e: print('Input error:',e) exit() for num in range(1,page+1): url = first_url + search + after_url + str(num) urlList.append(url) print("Please wait....") return urlList,search #获取网页文件 def get_html(self,urlList): response_list = [] for r_num in urlList: request = requests.get(r_num) response = request.content response_list.append(response) return response_list #获取blog_name和blog_url def get_soup(self,html_doc): result = {} for g_num in html_doc: soup = BeautifulSoup(g_num,'html.parser') context = soup.find_all('a',class_='m-1-4 fl') for i in context: title=i.get_text() result[title.strip()]=i['href'] return result if __name__ == '__main__': blog = get_urldic() urllist, search = blog.get_url() html_doc = blog.get_html(urllist) result = blog.get_soup(html_doc) for k,v in result.items(): print('search blog_name is:%s,blog_url is:%s' % (k,v))
74fa416726164c71a8006eef2b05e596c3e240a6
termuxuser01/books
/modern_python_cookbook/chapter_3/part_4.py
1,128
3.5625
4
import shutil import textwrap, itertools #use shutil.get_terminal_size to get the size of the terminal windows for sizing matters and output formatting def maketable(cols): #if it fails to get terminal size or the output is passed to something that isn't a terminal(eg a file) it will have a default fallback terms_size = shutil.get_terminal_size(fallback=(80, 24)) #compute the size of the terminal window and divide it by the number of columns colsize = (terms_size.columns // len(cols)) - 3 if colsize < 1: raise ValueError('Column too small') return '\n'.join(map(' | '.join, itertools.zip_longest(*[ [s.ljust(colsize) for s in textwrap.wrap(col, colsize)] for col in cols ], fillvalue=' '*colsize))) #now it is possible to print any text and adapt it to the terminal window being used COLUMNS = 5 TEXT = ['Lorem ipsum dolor sit amet, consectetuer adipiscing elit. ' 'Aenean commodo ligula eget dolor. Aenean massa. ' 'Cum sociis natoque penatibus et magnis dis parturient montes, ' 'nascetur ridiculus mus'] * COLUMNS print(maketable(TEXT))
7b430ee52a681a0679968cd790c7a21f91874d88
Livane9/Uniguajira-BD
/ejercicios/ejerciciosin2.py
460
3.828125
4
def numeroPrimonoPrimo(numero): numeroPrimo="es primo" numeroNo="no es primo" contador=0 for x in range(1,numero+1): if numero%x==0: contador=contador+1 if contador==2: print(f"El numero: {numeroPrimo}") else: print(f"El numero: {numeroNo}") def leerNumero(): numero=int(input("Ingrese un numero:")) numeroPrimonoPrimo(numero) def main(): leerNumero() if __name__ =="__main__": main()
2ad4389ebbce0b7ba942e4e4bd440251512c7dcd
RebovichA/PythonPractice
/ex1.py
1,795
4.25
4
########################################################################################################################################### # Found : # Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that # they will turn 100 years old. # # Extras: # Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. # (Hint: order of operations exists in Python) # Print out that many copies of the previous message on separate lines. (Hint: the string "\n is the same as pressing the ENTER button) ########################################################################################################################################### #! /bin/bash Python #originalAssignment(): name = input("Hello How Young Are You? : \n") age = input("What Is Your Age? : \n") age = int(age) #calc 100 year = 2018+(100-age) msg= (("Hello {} You will be 100 years old int the year {}").format(name.title(),year)) print (msg) ########################################################################################################################################## ## extra add on 1 ########################################################################################################################################## repeat=int(input("How many copies of the message would you like?: ")) print (msg*repeat) ########################################################################################################################################## ## extra add on 2 ########################################################################################################################################## print (repeat*(msg+ "/n")
f860000e04fa0245e04120ca41185a822fd25720
Pranathi-07/PythonDeepLearningICP1
/ICP1/hello_world.py
74
3.625
4
word = list(input()) del word[3:5] str1 = ''.join(word)[::-1] print(str1)
3dcbc0ad5b9160952d7fe5a189d03ff12d4a5f0d
darthsuogles/phissenschaft
/algo/leetcode_53.py
353
3.625
4
''' Maximum subarray ''' def maxSubArray(nums): if not nums: return 0 curr_max = nums[0] curr = nums[0] for a in nums[1:]: if curr < 0: curr = 0 curr += a curr_max = max(curr, curr_max) return curr_max maxSubArray([-2,1,-3,4,-1,2,1,-5,4]) maxSubArray([-1,-1,-1,-1]) maxSubArray([-1,-1,0,-1])
a0b3d577b824e2d4e3f202ee990b41c9604e949b
MadSkittles/leetcode
/121.py
337
3.703125
4
class Solution: def maxProfit(self, prices): res, min_ = 0, float('inf') for p in prices: res = max(res, p - min_) min_ = min(min_, p) return res if __name__ == '__main__': solution = Solution() print(solution.maxProfit([7,8])) print(solution.maxProfit([7, 6, 4, 3, 1]))
e4cdcfc9a0a2c6f796624b9f59300a669ba731c3
IgorShelest/AlgorithmRepo
/Sorting/Average/Comparison_Sorting/Bubble_Sort/PyCharm/Insertion_Sort.py
513
4.03125
4
""" Insertion Sort """ def insertion_sort(unsorted_list): """Insertion Sort""" for loop_iter in range(1, len(unsorted_list)): unsorted_elem = unsorted_list[loop_iter] elem_iter = loop_iter - 1 while elem_iter >= 0: if unsorted_list[elem_iter] > unsorted_elem: unsorted_list[elem_iter + 1] = unsorted_list[elem_iter] elem_iter -= 1 else: break unsorted_list[elem_iter + 1] = unsorted_elem
460294640053241e3eda432930f332b8b19a0269
theoctober19th/ds-algorithms
/tests/data_structures/test_doubly_linked_list.py
2,440
3.578125
4
import unittest from data_structures.doubly_linked_list import DoublyLinkedList class TestDoublyLinkedList(unittest.TestCase): def setUp(self): self.items = DoublyLinkedList() # test for empty linked list def test_empty_list(self): self.assertEqual(self.items.head, None) self.assertEqual(self.items.tail, None) # Tests forbidden operations like removal in a empty linked list def test_forbidden_operations_on_empty_linked_list(self): self.assertEqual(self.items.size, 0) with self.assertRaises(RuntimeError): self.items.remove_back() with self.assertRaises(RuntimeError): self.items.remove_front() def test_delete_nonexistent_item(self): self.items.insert_back('A') self.items.insert_front('B') with self.assertRaises(RuntimeError): self.items.remove('Z') def test_insert_back(self): self.items.insert_back('Z') self.assertEqual(self.items.size, 1) self.assertEqual(self.items.remove_back(), 'Z') self.items.insert_back('Y') self.items.insert_back('T') self.items.insert_back('E') self.assertEqual(self.items.remove_front(), 'Y') def test_insert_front(self): self.items.insert_front('A') self.assertEqual(self.items.size, 1) self.assertEqual(self.items.remove_front(), 'A') self.items.insert_front('B') self.items.insert_front('C') self.items.insert_front('D') self.assertEqual(self.items.remove_back(), "B") self.assertEqual(self.items.remove_front(), "D") def test_remove(self): with self.assertRaises(RuntimeError): self.items.remove('T') self.items.insert_front('T') self.items.insert_back('R') self.items.insert_after('R', 'Y') self.items.remove('R') self.assertEqual(self.items.size, 2) self.assertEqual(self.items.remove_back(), 'Y') self.assertEqual(self.items.size, 1) self.items.remove_front() self.assertEqual(self.items.size, 0) with self.assertRaises(RuntimeError): self.items.remove_front() # when only one node is there def test_single_node_case(self): self.items.insert_front(1) self.items.remove_front() self.assertEqual(self.items.head, self.items.tail) if __name__ == "__main__": unittest.main()
bad321741211228620460cf3a255e0598300b6b4
Courage-GL/FileCode
/Python/month01/day13/exercise01.py
1,872
4.40625
4
""" 练习2:创建图形管理器 1. 记录多种图形(圆形、矩形....) 2. 提供计算总面积的方法. 满足: 开闭原则 测试: 创建图形管理器,存储多个图形对象。 通过图形管理器,调用计算总面积方法. 三大特征 封装:创建GraphicManger、Circle、Rectangle 继承:创建Graphic类隔离GraphicManger与Circle、Rectangle的变化 多态:Circle、Rectangle通过重写get_area方法实现具体的面积计算逻辑 设计原则 开闭原则:增加了新图形,图形管理器不变 单一职责:GraphicManger 负责 管理所有图形 Circle 负责 圆形计算面积 Rectangle 负责 矩形计算面积 依赖倒置:GraphicManger调用Graphic 而不调用Circle、Rectangle 组合复用:组合关系连接了GraphicManger与具体图形 """ class GraphicManger: def __init__(self): self.__all_graphic = [] def add_graphic(self, graphic): if isinstance(graphic, Graphic): self.__all_graphic.append(graphic) def calcualte_total_area(self): total_area = 0 for item in self.__all_graphic: # 先确定了使用方法 total_area += item.get_area() return total_area class Graphic: def get_area(self): pass # -------------------------- class Circle(Graphic): def __init__(self, r): self.r = r def get_area(self): return self.r ** 2 * 3.14 class Rectangle(Graphic): def __init__(self, l, w): self.l = l self.w = w def get_area(self): return self.l * self.w manager = GraphicManger() manager.add_graphic(Circle(5)) manager.add_graphic(Rectangle(2, 3)) print(manager.calcualte_total_area())
797b79ae4a8bbc93465ac8be8caa58f61b846f44
nariba/Euler
/problem1.py
158
3.890625
4
#!/usr/local/bin/python3.4 sum = 0 num = 1000 for i in range(0, num): if i % 3 == 0 or i % 5 == 0 : sum += i print(i, sum) print(sum)
e4a6a29fd47ab8ae65316eab6322a364f9282889
Sarefx/College-Courses
/Intelligent Systems/P1 - Guessing Game in Python/Program1_NK.py
1,415
4
4
import random correctGuessedNumbers = list() wrongGuessedNumbers = list() userResponse = 'Y' while userResponse == 'Y': x = random.randint(1,100) print(f"Try to guess a number between 1 and 100. What is your guess?") wrongNumber = True while wrongNumber: userTestNum = input() try: userNum = int(userTestNum) if userNum == x: print("Great job you guessed the number.") wrongNumber = False correctGuessedNumbers.append(x) else: print(f"You didnt guess the number.") wrongGuessedNumbers.append(userNum) wrongNumber = True if userNum > x: print("Your number is too high.") elif userNum < x: print("Your number is too low.") print("Try again.") except ValueError: #Handle the exception print('This is not an integer. Please enter an integer.') print("Do you wish to continue? Y/N") userResponse = input() print("You quited the game. Here are your statistics:") print(f"You correctly guessed {len(correctGuessedNumbers)} numbers.") print(f"Your correct guesses were {correctGuessedNumbers}.") print(f"Your wrong guesses were {wrongGuessedNumbers}.") print("The program now terminates.")
47068feedeac863a2e035068fa923444631a0ace
freebz/Learning-Python
/ch14/ex13-17.py
1,772
3.703125
4
# 딕셔너리 뷰 반복 객체 D = dict(a=1, b=2, c=3) D # {'a': 1, 'b': 2, 'c': 3} K = D.keys() # 3.X에서 리스트가 아닌 뷰 객체 K # dict_keys(['a', 'b', 'c']) next(K) # 뷰 자체는 반복자가 아님 # TypeError: 'dict_keys' object is not an iterator I = iter(K) # 뷰 반복 객체는 반복자를 제공하며 next(I) # 반복자는 수동으로 사용될 수 있지만, # 'a' # len()과 인덱싱은 지원하지 않음 next(I) # 'b' for k in D.keys(): print(k, end=' ') # 모든 반복 상황에서 자동으로 사용 # a b c K = D.keys() list(K) # 필요 시 강제로 실제 리스트를 생성할 수 있음 # ['a', 'b', 'c'] V = D.values() # values() 뷰도 items() 뷰와 마찬가지 V # dict_values([1, 2, 3]) list(V) # 출력 또는 인덱싱을 위해 list()가 필요 # [1, 2, 3] V[0] # TypeError: 'dict_values' object does not support indexing list(V)[0] # 1 list(D.items()) # [('a', 1), ('b', 2), ('c', 3)] for (k, v) in D.items(): print(k, v, end=' ') # a 1 b 2 c 3 D # 딕셔너리는 여전히 반복자를 생성하며, # {'a': 1, 'b': 2, 'c': 3} # 반복될 때마다 다음 키를 반환함 I = iter(D) next(I) # 'a' next(I) # 'b' for key in D: print(key, end=' ') # 여전히 반복을 위해 keys()를 호출할 필요가 없지만, # keys는 3.X에서 반복 객체 # a b c D # {'a': 1, 'b': 2, 'c': 3} for k in sorted(D.keys()): print(k, D[k], end=' ') # a 1 b 2 c 3 for k in sorted(D): print(k, D[k], end=' ') # '가장 좋은' 키 정렬 방법 # a 1 b 2 c 3
c1ef939685a1810d0ae49211c70a331d76c06160
DavidWD783/SQL-practice
/db3.py
712
3.515625
4
# Import packages import pandas as pd import numpy as np from sqlalchemy import create_engine # Create engine to to send queries to database engine = create_engine('sqlite:///Chinook_Sqlite.sqlite') # # Inspect tables in the database table_names = engine.table_names() print(table_names) # Create connection to engine con = engine.connect() # Use rs to send queries to database rs = con.execute("SELECT Title, COUNT(*) FROM Employee WHERE Title NOT LIKE 'Sales%' GROUP BY Title;") # Turn rs object into DataFrame df = pd.DataFrame(rs.fetchall()) # Set the column headers to the table headers df.columns = rs.keys() # Close the connection con.close() # Print the header of the dataframe print(df.head())
e511dfb7a419d74e3c5e9aa1630e705895033ea1
LotanLevy/snake_game
/policies/Memorize_Feature.py
4,452
3.984375
4
class Memorize_Feture: def update_rewards(self, state, reward): """ Learn the board representation in order to learn the different objects rewards :param state: state :param reward: reward :return: """ board, head = state head_pos, direction = head if self.last_board is not None: value = self.last_board[head_pos[0], head_pos[1]] if value not in self.rewards: self.rewards[value] = set() self.rewards[value].add(reward) self.last_board = board def is_obstacle(self, board_value, good_fruit = False): """ Checks if the object in the given board_value is an obstacle :param board_value: the object board representation :param good_fruit: true in order to check if we are on a good fruit :return: true/false if we are on a obstacle """ if board_value not in self.rewards or ZERO in self.rewards[board_value]: return False if good_fruit: return list(self.rewards[board_value])[0] > 0 return list(self.rewards[board_value])[0] < 0 def is_board_edge(self, board, x, y, direction): """ Checks if we are on board edge :param board: board :param x: vertical position :param y: horizontal position :param direction: direction :return: true/false if we are on board edge """ if direction == 'N' and x == 0: return True if direction == 'S' and x == board.shape[0]-1: return True if direction == 'E' and y == board.shape[1]-1: return True if direction == 'W' and y == 0: return True return False def has_fruit_in_direction(self, state, direction): """ Checks if in the given direction there is a good-fruit :param state: state :param direction: direction :return: true/false and the position, if true """ board, head = state cur_pos, head_direction = head while not self.is_board_edge(board, cur_pos[0], cur_pos[1], direction): cur_pos = cur_pos.move(direction) board_value = board[cur_pos[0], cur_pos[1]] if self.is_obstacle(board_value, True): return True, cur_pos return False, -1 def dist(self, cur_pos, new_pos): """ Calculates euclidean distance :param cur_pos: cur_pos :param new_pos: new_pos :return: euclidean distance """ return np.sqrt(np.power(cur_pos[0] - new_pos[0], 2) + np.power(cur_pos[1] - new_pos[1], 2)) def build_state_vec(self, new_state): """ Creates feature vector according to the given state and action :param new_state: :param action: :return: feature vector """ features_for_pos = [] board, head = new_state head_pos, direction = head # 3 feature for danger for right, left and forward steps for action in bp.Policy.ACTIONS: next_direction = bp.Policy.TURNS[direction][action] next_pos = head_pos.move(next_direction) board_value = board[next_pos[0], next_pos[1]] features_for_pos.append(int(self.is_obstacle(board_value))) # 4 feature for directions features_for_pos.append(int(direction == 'N')) features_for_pos.append(int(direction == 'S')) features_for_pos.append(int(direction == 'W')) features_for_pos.append(int(direction == 'E')) # 4 feature for good fruit in specific direction directions = ['N', 'S', 'W', 'E'] closest_pos = None dist = None best_direction = None for d in directions: has_fruit, pos = self.has_fruit_in_direction(new_state, d) if has_fruit: new_dist = self.dist(head_pos, pos) if closest_pos is None or self.dist(head_pos, pos) < dist: closest_pos = pos dist = new_dist best_direction = d for d in directions: if best_direction is not None and best_direction == d: features_for_pos.append(1) else: features_for_pos.append(0) return np.reshape(np.array(features_for_pos), (1,11))
c1c1da6088670e39c56e0806c7071fee58a89eed
imclab/motorsport-yaml
/python/racing_yaml_creator.py
3,951
3.6875
4
# This script takes a CSV with the Wikipedia API url, # grabs the race aliases from the Wikipedia content, # and creates a YAML file # Import CSV and convert it to a 2-D array array = [] import csv with open('nascar-nationwide-no-aliases.csv', 'rb') as csv_input: initial_csv = csv.reader(csv_input) next(initial_csv) for row in initial_csv: array.append(row) # Getting the race event name aliases import urllib2 for i in range (0, len(array)): # URL of the Wikipedia article content API # is stored in the 4th column of the CSV file wiki_url = array[i][3] # This is for postseason races # wiki_url = array[i][4] opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] infile = opener.open(wiki_url) scraped = infile.read() # I only want the text between the following strings first_string = "Previous names" last_string = "}}" # This is for IndyCar # last_string = "Most" index1 = scraped.find(first_string) + len(first_string) # Removing all the crap in the front head_removed = scraped[index1:] index2 = head_removed.find(last_string) # Removing all the crap in the rear tail_removed = head_removed[0:index2] # "Normalization" rules; order is important! # These rules are for Nascar Sprint Cup final_string = tail_removed.replace("&lt;", "") final_string = final_string.replace("'''", "") final_string = final_string.replace("[[", "") final_string = final_string.replace("]]", "") final_string = final_string.replace("p&gt;", "") final_string = final_string.replace(" br&gt; ", "") final_string = final_string.replace("br&gt; ", "") final_string = final_string.replace(" br&gt;", "") final_string = final_string.replace("br&gt;", "") final_string = final_string.replace("br /&gt;", "") final_string = final_string.replace("br/&gt;", "") final_string = final_string.replace("/small&gt;", "") final_string = final_string.replace("small&gt;", "") final_string = final_string.replace("&amp;", "&") final_string = final_string.replace("|\n", "") final_string = final_string.replace("| ", "") final_string = final_string.replace(" ", " ") # Additional rules for Nascar Camping final_string = final_string.replace("BR&gt;", "") # Additional rules for IndyCar final_string = final_string.replace("''", "") final_string = final_string.replace("/u&gt;", " ") final_string = final_string.replace("u&gt;", "") # Remove dates and parentheses while True: p_index1 = final_string.find("(") p_index2 = final_string.find(")") + 1 final_string = final_string.replace(final_string[p_index1:p_index2], "\n") if final_string.find("(") == -1: break # Remove equals sign final_string = final_string.replace("=", "") # Remove extra lines final_string = final_string.replace("\n \n", "\n") final_string = final_string.rstrip("\n") final_string = final_string.replace("\n\n", "\n") final_string = final_string.replace("\n\n", "\n") final_string = final_string.replace("\n\n", "\n") # Remove any beginning and ending white space final_string = final_string.lstrip(" ") final_string = final_string.rstrip(" ") # Storing the aliases in the array array[i][3] = final_string # This is for postseason # array[i][4] = final_string # Outputting in YAML format for row in array: print '-' + '\n' + '\t' + 'name: ' + row[0] print '\t' 'series: ' + row[1] print '\t' 'track: ' + row[2] print '\t' 'aliases:' aliases = row[3].split('\n') for row in aliases: print '\t\t' + row # For postseason # for row in array: # print '-' + '\n' + '\t' + 'name: ' + row[0] # print '\t' 'series: ' + row[1] # print '\t' 'track: ' + row[2] # print '\t' 'postseason: true' # print '\t' 'aliases:' # aliases = row[4].split('\n') # for row in aliases: # print '\t\t' + row
1f476328d6c053b22c19207d325985fca0f50ad7
diego-90/progAvanzada
/ejercicio9.py
309
3.734375
4
dinero = int(input('introduzca la cantidad de dinero depositada en el primer año $:')) interes =(dinero * 0.04) suma1=dinero+interes print('primer año',suma1) interes2=suma1*0.04 suma2=suma1+interes2 print('segundo año', suma2) interes3=suma2*0.04 suma3=suma2+interes3 print('tercer año',suma3)
608e92193e4b3e0ea5b28d25fada9aa86807c73e
ZoranPandovski/al-go-rithms
/math/factorial/python/factorial.py
163
4.1875
4
def factorial(n): if n <= 1: return 1 else: return n * factorial(n-1) number = int(input("Enter a number: ")) print("Result {}".format(factorial(number)))
072f887102fd4eeed756c9198702e2450d55632c
lasse-steinnes/more-UiO-courses
/Høst2017/matinf/Innlevering1/inn1_oppg1_differens.py
1,771
3.5625
4
###### Oppgave 1. ## a) # x(n+2) + bx(n+1) + cXn = 0 kan skrives om # Vi har da """ x0 = 1 x1 = 2 n = 100 x_list = [] x_list.append(x0) x_list.append(x1) for i in range(n+1): x = 2*x_list[i+1] + 2*x_list[i] x_list.append(x) x_list2to100 = x_list[2:101] print("------------------") print(" n Xn") print("------------------") for i in range(n-1): print("%3g %10.4e" % (i+2, x_list2to100[i])) print("-------------------") # print(x_list[2:100]) """ ## b) from math import sqrt x0 = 1 x1 = 1-sqrt(3) n = 100 x_list = [] x_list.append(x0) x_list.append(x1) for i in range(n+1): x = 2*x_list[i+1] + 2*x_list[i] x_list.append(x) x_list2to100 = x_list[2:101] """ print("------------------") print(" n Xn") print("------------------") for i in range(n-1): print("%3g %10.4e" % (i+2, x_list2to100[i])) print("-------------------") """ ##c) # Se beregning ## d) Kan kjøre en testfunksjon her ## Vise det grafisk med en tabell x_exactlist = [] e_list = [] for i in range(n+1): xn_exact = (1 - sqrt(3))**i x_exactlist.append(xn_exact) difference_ = abs(float(x_exactlist[i]) - float(x_list[i])) e_list.append(difference_) x_exactlist2to100 = x_exactlist[2:101] e_list2to100 = e_list[2:101] #print(x_exactlist2to100) Test # print(e_list2to100) Test print("------------------------------------------------------") print(" n Xnum Xexact error") print("------------------------------------------------------") for i in range(n-1): print("%3g %15.4e %15.4e %15.4e" % (i+2, x_list2to100[i],\ x_exactlist2to100[i], e_list2to100[i])) print("-------------------------------------------------------") ## Bestemme avrundingsenheten(round off unit) # Se notat i foredrag om dette
006dbde6286e97266970bb9e6acfba927a76c630
AngelEmil/3ra-Practica---Condicionales-
/Ejercicio 4.py
284
4.15625
4
# 4. Pedir un número por pantalla y decir si está entre 10 y 15 o no. N = int(input("digite otro numero ")) if N < 15 and N > 10: print ("El numero esta entre estos dos numero 10 y 15") else: N < 10 and N > 15 print ("no esta entre los numeros 10 y 15")
cdd7e60f351bd874a9dba28d3d118e31b7c392ce
dfkigs/helloworld
/python/basic/abstract/recursion.py
373
4.125
4
#!/usr/bin/python def factorial(n): if n < 1: return 0 elif n == 1: return 1 else: return n*factorial(n-1) n = input("Input N:") def power(x,n): if n < 1: return 0 elif n == 1: return x else: return power(x,n-1)*x def power2(x,n): result = 1 for i in range(n): result *= x return result print factorial(n) print power(5,n) print power2(5,n)
5f02cb5b2b8b0ccf0848a5af634dba436dbc8e83
yuki67/PaintBasics
/Figure/Figure.py
6,458
3.703125
4
from itertools import chain from math import ceil, pi, sin, cos from typing import List, Callable, Iterable class Figure(object): """ 図形の基底クラス """ def __iter__(self) -> Iterable: pass class Point(Figure): """ 図形を扱うときの基本となる点 """ def __init__(self, x: float, y: float, rgb: List[int]=None) -> None: """ 座標が(x,y)で色がrgbの点を返す """ self.x = x self.y = y if rgb is not None: rgb[0] = int(rgb[0]) rgb[1] = int(rgb[1]) rgb[2] = int(rgb[2]) self.rgb = rgb def __repr__(self): return "Point(%s, %s, %s)" % (self.x, self.y, self.rgb) def interpolate(self, b, r: float): """ selfとbをr:(1-r)に内分する点を返す(0<r<1) """ # r = 0 で self # r = 1 で b x = (b.x - self.x) * r + self.x y = (b.y - self.y) * r + self.y rgb = [0, 0, 0] if self.rgb is not None: rgb[0] = (b.rgb[0] - self.rgb[0]) * r + self.rgb[0] rgb[1] = (b.rgb[1] - self.rgb[1]) * r + self.rgb[1] rgb[2] = (b.rgb[2] - self.rgb[2]) * r + self.rgb[2] return Point(x, y, rgb) class Line(Figure): """ 線分 """ def __init__(self, a: Point, b: Point) -> None: self.a = a self.b = b self.stopper = max(abs(self.a.x - self.b.x), abs(self.a.y - self.b.y)) def __repr__(self): return "Line(%s, %s)" % (self.a.__repr__(), self.b.__repr__()) def __iter__(self) -> Iterable[Point]: if self.stopper == 0: return (i for i in range(0)) else: return (Point.interpolate(self.a, self.b, i / self.stopper) for i in range(int(self.stopper) + 1)) class Polygon(Figure): """ 多角形 """ def __init__(self, points: List[Point]) -> None: self.points = points self.stopper = len(points) def __iter__(self) -> Iterable[Line]: return (Line(self.points[i - 1], self.points[i]) for i in range(self.stopper)) class Ellipse(Figure): """ 楕円 """ def __init__(self, center: Point, a: float, b: float) -> None: # 全体の色はcenter.rgbで指定される self.center = center self.a = a self.b = b self.x_range = ceil((a ** 2 + b ** 2) ** -0.5 * a ** 2) self.y_range = ceil((a ** 2 + b ** 2) ** -0.5 * b ** 2) self.y = lambda x: b * (1 - (x / a) ** 2) ** 0.5 self.x = lambda y: a * (1 - (y / b) ** 2) ** 0.5 def __iter__(self) -> Iterable[Point]: return chain((Point(self.center.x + x, self.center.y + self.y(x), self.center.rgb) for x in range(-self.x_range, self.x_range)), (Point(self.center.x + x, self.center.y - self.y(x), self.center.rgb) for x in range(-self.x_range, self.x_range)), (Point(self.center.x + self.x(y), self.center.y + y, self.center.rgb) for y in range(-self.y_range, self.y_range)), (Point(self.center.x - self.x(y), self.center.y + y, self.center.rgb) for y in range(-self.y_range, self.y_range))) class Circle(Ellipse): """ 円 """ def __init__(self, center: Point, r: float) -> None: super().__init__(center, r, r) class Diamond(Figure): """ ダイヤモンドパターン """ def __init__(self, center: Point, r: float, n: int, color: Callable[[float], List[int]]=lambda t: [0, 0, 0] ) -> None: self.circle = lambda: circular_points(center, r, n, color) def __iter__(self) -> Iterable(Line): return (Line(p, q) for p in self.circle() for q in self.circle()) class ColorArray(Figure, list): """ 色配列 """ def __init__(self, width: int, height: int) -> None: """ [255, 255, 255](白)に初期化された横width, 縦heightの色配列を返す """ array = [] for y in range(height): array.append(ColorArray(0, 0)) for x in range(width): array[-1].append(Point(x, y, [255, 255, 255])) super().__init__(array) def __iter__(self) -> Iterable[Iterable[Point]]: return list.__iter__(self) def resize(self, width: int): """ 幅をwidthに縮小して返す """ return self.from_source(width, len(self[0]), len(self), lambda x, y: self[int(y)][int(x)].rgb) @staticmethod def from_image(filename: str, width: int): """ 画像から色配列を作って返す widthは出来上がる色配列の幅 """ from PIL import Image image = Image.open(filename) w, h = image.size return ColorArray.from_source(width, w, h, lambda x, y: image.getpixel((int(x), int(y)))) @staticmethod def from_source(width: int, source_width: int, source_height: int, sampler: Callable[[int, int], List[int]]): """ samplerを使って幅widthの色配列を作って返す """ height = width / source_width * source_height diff_x = (source_width - 1) / (width - 1) diff_y = (source_height - 1) / (height - 1) y = n = 0 array = ColorArray(0, 0) while y <= source_height: x = m = 0 array.append(ColorArray(0, 0)) while x <= source_width: array[-1].append(Point(m, n, list(sampler(x, y)))) x += diff_x m += 1 y += diff_y n += 1 return array def circular_points(center: Point, r: float, n: int, color: Callable[[float], List[int]]=lambda t: [0, 0, 0] ) -> Iterable[Point]: """ 円周上の点へのイテレータを返す """ return (Point(r * cos(2 * pi * i / n) + center.x, r * sin(2 * pi * i / n) + center.y, color(i / n)) for i in range(n))
a95bd64ba549ec4d3c247176f685ebbb88d2b0f5
geudet/Logbook
/EX25.py
264
3.6875
4
a = [66.25, 333, 333, 1, 1234.5] #insert "-1" at index 2 #add "333" at the end of list a.insert(2, -1) a.append(333) print(a) #the first index of "333" print(a.index(333)) #remove "333" a.remove(333) print(a) #sort the list a.sort() print(a)
9e04f7a539031955d46cdb728e4acb965b40efa7
MathisBD/ReversePy
/tests/fibo_multiple.py
414
4.125
4
# Python Program to find position of n\'th multiple # of a mumber k in Fibonacci Series def findPosition(k, n): f1 = 0 f2 = 1 i = 2 while i != 0: f3 = f1 + f2 f1 = f2 f2 = f3 if f2 % k == 0: return n * i i += 1 return # Multiple no. n = 5 # Number of whose multiple we are finding k = 5345 print("Position of %d\'th multiple of %d in the Fibonacci Series is %d" % (n, k, findPosition(k,n)))
3f414d2dcf8f410f1e467e9e1a26d9f82f78fe16
OrangeB0lt/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/5-text_indentation.py
610
3.9375
4
#!/usr/bin/python3 """ Indents text after speific character anotherline and anotherline! """ def text_indentation(text): """ Indents text at specific characters . ? : """ if not isinstance(text, str): raise TypeError("text must be a string") temp = list(text) for idx in range(0, len(temp)): try: if temp[idx] == '.' or temp[idx] == '?' or temp[x] == ':': temp.insert(idx + 1, "\n") except: continue temp = "".join(temp).split('\n') for idx in temp: print(idx.strip()) print()
dc754f772d8f4ba92fad2186439121b62cc5581a
b1ck0/python_coding_problems
/Recursion/001_bisection_search.py
1,348
3.5
4
def search(element, array: list): """ :param element: some element :param array: sorted list :return: element in list """ if len(array) == 0 or element == '' or element is None: return False if len(array) == 1: return element == array[0] n = len(array) mid = n // 2 if element == array[mid]: return True elif element < array[mid]: return search(element, array[:mid]) else: return search(element, array[mid:]) if __name__ == "__main__": from nose.tools import assert_equal class TestClass(object): def test(self, sol): assert_equal(sol('a', ''), False) assert_equal(sol('u', 'llmrtwy'), False) assert_equal(sol('e', 'ceeijlpvv'), True) assert_equal(sol('w', 'aehirww'), True) assert_equal(sol('d', 'cdfgiiilnpprvwxxzz'), True) assert_equal(sol('g', 'bdefffgklmooqrwx'), True) assert_equal(sol('f', 'cefgijlmoorrtttxyy'), True) assert_equal(sol('u', 'lmosstuuvv'), True) assert_equal(sol('x', 'bcddefghijnppqruy'), False) assert_equal(sol('p', 'acddeghkkpqsuxy'), True) assert_equal(sol(5, [1, 2, 3, 4, 5, 6]), True) assert_equal(sol(10, [1, 2, 3, 4, 5, 6]), False) print('ALL TEST CASES PASSED') # Run Tests t = TestClass() t.test(search)
fa8e7e88d851dc933406c4c601fa23dadc4ff81a
GrestiBed/python
/tort.py
443
3.703125
4
from math import ceil,floor pikkus = input("Sisesta pikkus tükkides: ") laius = input("Sisesta laius tükkides: ") h = input("Sisesta kõrgus tükkides: ") tk_pakis = input("Mitu tükki on ühes pakis: ") def pakke(): tk_arv = int(pikkus) * int(laius) * int(h) pakk_arv = tk_arv / int(tk_pakis) #print("Sul on vaja " + str(round(pakk_arv + 0.49)) + " pakki") print("Sul on vaja " + str(floor(pakk_arv)) + " pakki") pakke()
0fe3e31a9c299536ac6d2c6e78ea60474a79dd65
j-mano/Ai
/Lab_1/AIfinaldraft.py
6,318
3.53125
4
# Authurs: Joachim Johnson and Jonas Åsander # Course: DT112G, artifical intelegens # Task 1: Tower of Hanoi Problem # Storage Parameters numbofdisks = 6 start = [0] * numbofdisks # Start value. goal = [2] * numbofdisks # Goal state to reach. ''' ---------------------------------------------------------------------------------------------------------------- ''' def Main(): # Initial start parameters. # Nollställer vektorena om man ska köra den en gång till currentState = [] vistied = [] # All visited states. comeFrom = [] run_Program = True currentState.append(start) # Loop values. c = 0 while run_Program == True: # General Loop that run the program. # Checking if the goal state is reacht or not c +=1 # Sparar de nya placeringar currentState.extend(New_state(currentState[0])) # Utgå ifrån den som står först i currentState. vistied.append(currentState[0]) # Sparar den som vi besökte. # currentState.reverse() # Aktivate if you want deep search othewise it breath search. comeFrom.append(The_Way_To_Go(vistied[len(vistied) - 1], New_state(vistied[len(vistied) - 1]))) # Tar bort överlapande som annars ställer till problem n = 0 # NOLLSTÄLLER INFÖR LOOPEN i = 0 while (i < len(vistied)): # Går igenom vistied som öka varje gång vi har gått igrnom CurrentState. if n >= len(currentState): i = i + 1 n = 0 elif vistied[i] == currentState[n]: # Ifall vi hittar två lika så tas den bort ifrån currentState. del currentState[n] else: n += 1 if Check_Goal(vistied[len(vistied) - 1], goal) == True: run_Program = False A=PrintoutGoalValues(c,comeFrom) A.reverse() return A break ''' ---------------------------------------------------------------------------------------------------------------- ''' def New_state(state): # Tar fram alla möjliga sätt man kan flytta diskarna på New = [state.copy()] # Kopierar State så den ej ändras Disk_place = [] for i in range(0, len(state)): A = Check_Disk(state, i) # Kollar vilka diskar som går o flytta på. if A == True: # Om platsen är flytbar gör då detta. Disk_place.extend([i]) # Lagra platsen som är flyttbar. for i in range(len(Disk_place)): # Kollar om man kan lägga de flytbara diskarna någonstans samt flyttar på dem. New[0] = state.copy() New.append(Move_disk_one_step(New[0], Disk_place, i)) # Flyttar diskarna ett steg åt "höger". New[0] = state.copy() New.append(Move_disk_two_step(New[0], Disk_place, i)) # Flyttar diskarna två steg åt "höger". New = NoneRemover(New) # Tar bort alla None värden. del New[0] # Tar bort det första värdet. return New ''' ---------------------------------------------------------------------------------------------------------------- ''' def Move_disk_one_step(state, Disk_place, i): a = [] state[Disk_place[i]] = (state[Disk_place[i]] + 1) % 3 if Check_Disk(state, Disk_place[i]) == True: a.extend(state) return a ''' ---------------------------------------------------------------------------------------------------------------- ''' def Move_disk_two_step(state, Disk_place, i): a = [] state[Disk_place[i]] = (state[Disk_place[i]] + 2) % 3 if Check_Disk(state, Disk_place[i]) == True: a.extend(state) return a ''' ---------------------------------------------------------------------------------------------------------------- ''' def Check_Disk(state, i): returnvalue = True if i == len(state) - 1: return True for n in range(i, len(state) - 1): if state[i] == state[n + 1]: returnvalue = False return returnvalue ''' ---------------------------------------------------------------------------------------------------------------- ''' def Check_Goal(state, goal): # Check if the goal state is reacht. if state == goal: return True else: return False ''' ---------------------------------------------------------------------------------------------------------------- ''' def The_Way_To_Go(vistied, currentState): comeFrom = [currentState, vistied] return comeFrom ''' ---------------------------------------------------------------------------------------------------------------- ''' def Find_Way_Home(comeFrom): way_home = [goal.copy()] i = 0 n = 0 while (way_home[-1:] != [start]): if [comeFrom[i][0][n]] == way_home[-1:]: way_home.append(comeFrom[i][-1]) i = 0 n = 0 elif n >= len(comeFrom[i][0]) - 1: i += 1 n = 0 else: n +=1 return way_home ''' ---------------------------------------------------------------------------------------------------------------- ''' def NoneRemover(state): # Tar bort alla None värden. while state.count(None) != 0: state.remove(None) return state ''' ---------------------------------------------------------------------------------------------------------------- ''' def PrintoutGoalValues(c,comeFrom): print('startvalues: ' + start + ' has been reacht and ended the search') print('Number of calculations: ',c - 1) return(Find_Way_Home(comeFrom))
5bc63f4fde2c98d6f566435255705221efd14554
yenlinh2803/TensorFlow_GCP_Specialization
/4.Feature_Engineering/lab_done/a_features.py
4,317
4.125
4
#!/usr/bin/env python # coding: utf-8 # # Trying out features # **Learning Objectives:** # * Improve the accuracy of a model by adding new features with the appropriate representation # The data is based on 1990 census data from California. This data is at the city block level, so these features reflect the total number of rooms in that block, or the total number of people who live on that block, respectively. # ## Set Up # In this first cell, we'll load the necessary libraries. # In[1]: import math import shutil import numpy as np import pandas as pd import tensorflow as tf print(tf.__version__) tf.logging.set_verbosity(tf.logging.INFO) pd.options.display.max_rows = 10 pd.options.display.float_format = '{:.1f}'.format # Next, we'll load our data set. # In[2]: df = pd.read_csv("https://storage.googleapis.com/ml_universities/california_housing_train.csv", sep=",") # ## Examine and split the data # # It's a good idea to get to know your data a little bit before you work with it. # # We'll print out a quick summary of a few useful statistics on each column. # # This will include things like mean, standard deviation, max, min, and various quantiles. # In[3]: df.head() # In[4]: df.describe() # Now, split the data into two parts -- training and evaluation. # In[6]: np.random.seed(seed=1) #makes result reproducible msk = np.random.rand(len(df)) < 0.8 traindf = df[msk] evaldf = df[~msk] # In[7]: print(len(traindf)) print(len(evaldf)) # ## Training and Evaluation # # In this exercise, we'll be trying to predict **median_house_value** It will be our label (sometimes also called a target). # # We'll modify the feature_cols and input function to represent the features you want to use. # # Hint: Some of the features in the dataframe aren't directly correlated with median_house_value (e.g. total_rooms) but can you think of a column to divide it by that we would expect to be correlated with median_house_value? # In[8]: def add_more_features(df): df['avg_rooms_per_house'] = df['total_rooms'] / df['households'] #expect positive correlation df['avg_persons_per_room'] = df['population'] / df['total_rooms'] #expect negative correlation return df # In[9]: # Create pandas input function def make_input_fn(df, num_epochs): return tf.estimator.inputs.pandas_input_fn( x = add_more_features(df), y = df['median_house_value'] / 100000, # will talk about why later in the course batch_size = 128, num_epochs = num_epochs, shuffle = True, queue_capacity = 1000, num_threads = 1 ) # In[10]: # Define your feature columns def create_feature_cols(): return [ tf.feature_column.numeric_column('housing_median_age'), tf.feature_column.bucketized_column(tf.feature_column.numeric_column('latitude'), boundaries = np.arange(32.0, 42, 1).tolist()), tf.feature_column.numeric_column('avg_rooms_per_house'), tf.feature_column.numeric_column('avg_persons_per_room'), tf.feature_column.numeric_column('median_income') ] # In[13]: # Create estimator train and evaluate function def train_and_evaluate(output_dir, num_train_steps): # TODO: Create tf.estimator.LinearRegressor, train_spec, eval_spec, and train_and_evaluate using your feature columns estimator = tf.estimator.LinearRegressor(model_dir = output_dir, feature_columns = create_feature_cols()) train_spec = tf.estimator.TrainSpec(input_fn = make_input_fn(traindf, None), max_steps = num_train_steps) eval_spec = tf.estimator.EvalSpec(input_fn = make_input_fn(evaldf, 1), steps = None, start_delay_secs = 1, # start evaluating after N seconds, throttle_secs = 5) # evaluate every N seconds tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) # In[14]: # Launch tensorboard from google.datalab.ml import TensorBoard OUTDIR = './trained_model' TensorBoard().start(OUTDIR) # In[12]: OUTDIR = './trained_model' # In[15]: # Run the model shutil.rmtree(OUTDIR, ignore_errors = True) # start fresh each time tf.summary.FileWriterCache.clear() # ensure filewriter cache is clear for TensorBoard events file train_and_evaluate(OUTDIR, 2000) # In[ ]:
3f67bee9c75d63e328174c42fdb7bdc808f368bc
diakunwadee/demo-learn-git
/Excelrecoder.py
527
3.515625
4
from openpyxl import Workbook excelfile = Workbook() row = excelfile.active row.append(['Product','Amount','Price']) product = '' while product!= 's': product = input("Enter Product Name: ") if product!= 's': amount = int(input("Enter Amount: ")) price = int(input("Price: ")) row.append([product, amount, price]) else: break filename = input("Enter file name: ") filename = filename + ".xlsx" excelfile.save(filename) print("Excel Saved: ", filename) #code from uncleengineer
b1c164a644a038a041f2f7d6e5ae51ecb8c5262a
julianferres/Notebook-Python
/Pyhton/Strings/applications.py
849
3.796875
4
def prefixFunction(s): """Devuelve un array pi, donde pi[i] coincide con el mayor prefijo propio que ademas es sufijo de s[0...i]""" n = len(s) pi = [0 for _ in range(n)] for i in range(1,n): j = pi[i-1] while(j>0 and s[i]!=s[j]): j = pi[j-1] if(s[i]==s[j]): j+=1 pi[i] = j return pi def numOccurencesPrefix(s): """Cuenta el numero de apariciones de cada prefijo de s en s""" pi = prefixFunction(s) n = len(s) ans = [0 for i in range(n+1)] for i in range(n): ans[pi[i]]+=1 i = n-1 while(i>0): ans[pi[i-1]] += ans[i] i-=1 for i in range(n+1): ans[i]+=1 return ans def numDifferentSubstring(s): """Dada una string s, cuenta la cantidad de substrings diferentes que contiene. O(|s|^2)""" ans = 1; n = len(s) for i in range(1,n): pimax = max(prefixFunction(s[:i+1][::-1])) ans += i+1-pimax return ans
4e9aba8dcd05cdface72eb0ccd17f53b17f4d26e
BognaGondek/VirtualReality
/symulator/animal/fox.py
2,715
3.609375
4
from symulator.animal.animal import Animal class Fox(Animal): def __init__(self, world): super().__init__(world) self.set_organizm() def outside_effect(self, org): self.world.pygame.current_text.append("Fox attacks " + org.name + ".") org.aliveness = False def set_organizm(self): self.name = "fox" self.strength = 3 self.initiative = 7 def choose_animal(self): child = Fox(self.world) return child def action(self): self.location.current_position.move() self.good_smell() x = self.location.current_position.cell.row y = self.location.current_position.cell.column self.world.pygame.current_text.append("Moves to: " + f'({x}, {y}).') super(Animal, self).action() def good_smell(self): smelled = [0 for i in range(0, 4)] self.world.pygame.current_text.append("Fox smells his surroundings.") while (self.world.class_map.get_organism(self.location.current_position) is not None and (self.world.class_map.get_organism(self.location.current_position).strength > self.strength)): self.__remember_danger(smelled, self.location) self.__prepare_to_smell_again() self.location.current_position.move() if self.check_if_trapped(smelled): self.world.pygame.current_text.append("Fox realised he is trapped.") self.__prepare_to_smell_again() break def __prepare_to_smell_again(self): x = self.location.previous_position.cell.row y = self.location.previous_position.cell.column self.location.current_position.cell.set_cell(x, y) def __remember_danger(self, smelled, location): c_x = location.current_position.cell.row c_y = location.current_position.cell.column p_x = location.previous_position.cell.row p_y = location.previous_position.cell.column if c_x == p_x + 1 or not self.location.current_position.check_validity_of_movement(p_x + 1, self.world.n): smelled[0] = 1 if c_x == p_x - 1 or not self.location.current_position.check_validity_of_movement(p_x - 1, self.world.n): smelled[1] = 1 if c_y == p_y + 1 or not self.location.current_position.check_validity_of_movement(p_y + 1, self.world.m): smelled[2] = 1 if c_y == p_y - 1 or not self.location.current_position.check_validity_of_movement(p_y - 1, self.world.m): smelled[3] = 1 @staticmethod def check_if_trapped(smelled): for number in smelled: if number == 0: return False return True
a8417674a57d053717ccb2e47d0e3937d45a9dd8
aman23ks/Python-practice
/practice_day5.py
11,988
4.4375
4
# # Scope # # The variable is only available from inside the region from where it is created.This is called as scope. # # Local Scope # # A variable created inside a function belongs to the local scope of that function, and can only be used inside that function. # # def myfunc(): # # x = 300 # # print(x) # # myfunc() # # Function Inside Function # # As explained in the example above, the variable x is not available outside the function, but it is available for any function inside the function: # # def myfunc(): # # x = 20 # # def myfunc2(): # # print(x) # # return myfunc2() # # myfunc() # # Global Scope # # A variable created in the main body of the Python code is a global variable and belongs to the global scope. # # Global variables are available from within any scope, global and local. # # x = 300 # # def myfunc(): # # print(x) # # myfunc() # # print(x) # # Naming Variables # # If you operate with the same variable name inside and outside of a function, Python will treat them as two separate variables, one available in the global scope (outside the function) and one available in the local scope (inside the function): # # x = 300 # # def myfunc(): # # x = 200 # # print(x) # # myfunc() # # print(x) # # Global Keyword # # If you need to create a global variable, but are stuck in the local scope, you can use the global keyword. # # The global keyword makes the variable global. # # def myfunc(): # # global x # # x = 300 # # print(x) # # myfunc() # # print(x) # # Also, use the global keyword if you want to make a change to a global variable inside a function. # # x = 200 # # def myfunc(): # # global x # # x = 100 # # print(x) # # myfunc() # # print(x) # # What is a Module? # # Consider a module to be the same as a code library. # # A file containing a set of functions you want to include in your application. # # Create a Module # # To create a module just save the code you want in a file with the file extension .py: # # Example # # Save this code in a file named mymodule.py # # def greeting(name): # # print("Hello, " + name) # # import mymodule # # Use a Module # # Now we can use the module we just created, by using the import statement: # # Example # # Import the module named mymodule, and call the greeting function: # # mymodule.greeting("Jonathan") # # Variables in Module # # The module can contain functions, as already described, but also variables of all types(arrays, dictionaries, objects etc): # # Example # # Save this code in the file mymodule.py # # person1 = { # # "name": "John", # # "age": 36, # # "country": "Norway" # # } # # Example # # Import the module named mymodule, and access the person1 dictionary: # # a = mymodule.person1["age"] # # print(a) # # Naming a Module # # You can name the module file whatever you like, but it must have the file extension .py # # Re-naming a Module # # You can create an alias when you import a module, by using the as keyword: # # Example # # Create an alias for mymodule called mx: # # a = mx.person1["age"] # # print(a) # # Built-in Modules # # There are several built-in modules in Python, which you can import whenever you like. # # Example # # Import and use the platform module: # # import platform # # x = platform.system() # # print(x) # # Using the dir() Function # # There is a built-in function to list all the function names (or variable names) in a module. The dir() function: # # import platform # # x = dir(platform) # # print(x) # # Import From Module # # You can choose to import only parts from a module, by using the from keyword. # # Example # # The module named mymodule has one function and one dictionary: # # def greeting(name): # # print("Hello, " + name) # # person1 = { # # "name": "John", # # "age": 36, # # "country": "Norway" # # } # # Example # # Import only the person1 dictionary from the module: # # from mymodule import person1 # # print (person1["age"]) # # Note: When importing using the from keyword, do not use the module name when referring to elements in the module. Example: person1["age"], not mymodule.person1["age"] # # Python Dates # # A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects. # # import datetime # # x = datetime.datetime.now() # # print(x) # # Date Output # # When we execute the code from the example above the result will be: # # 2020-11-03 20:59:19.961373 # # The date contains year, month, day, hour, minute, second, and microsecond. # # The datetime module has many methods to return information about the date object. # # Here are a few examples, you will learn more about them later in this chapter: # # import datetime # # x = datetime.datetime.now() # # print(x.second) # # Creating Date Objects # # To create a date, we can use the datetime() class (constructor) of the datetime module. # # The datetime() class requires three parameters to create a date: year, month, day. # # import datetime # # x = datetime.datetime(2020, 5, 17) # # print(x) # # The datetime() class also takes parameters for time and timezone(hour, minute, second, microsecond, tzone), but they are optional, and has a default value of 0, (None for timezone). # # The strftime() Method # # The datetime object has a method for formatting date objects into readable strings. # # The method is called strftime(), and takes one parameter, format, to specify the format of the returned string: # # Example # # Display the name of the month: # # import datetime # # x = datetime.datetime(2018, 6, 1) # # print(x.strftime("%B")) # # Directive Description Example # # %a Weekday, short version Wed # # %A Weekday, full version Wednesday # # %w Weekday as a number 0-6, 0 is Sunday 3 # # %d Day of month 01-31 31 # # %b Month name, short version Dec # # %B Month name, full version December # # %m Month as a number 01-12 12 # # %y Year, short version, without century 18 # # %Y Year, full version 2018 # # %H Hour 00-23 17 # # %I Hour 00-12 05 # # %p AM/PM PM # # %M Minute 00-59 41 # # %S Second 00-59 08 # # %f Microsecond 000000-999999 548513 # # %z UTC offset + 0100 # # %Z Timezone CST # # %j Day number of year 001-366 365 # # %U Week number of year, Sunday as the first day of week, 00-53 52 # # %W Week number of year, Monday as the first day of week, 00-53 52 # # %c Local version of date and time Mon Dec 31 17: 41: 00 2018 # # %x Local version of date 12/31/18 # # %X Local version of time 17: 41: 00 # # % % A % character % # # Python Math # # Python has a set of built-in math functions, including an extensive math module, that allows you to perform mathematical tasks on numbers. # # Built-in Math Functions # # The min() and max() functions can be used to find the lowest or highest value in an iterable: # # x = min(5, 10, 25) # # y = max(5, 10, 25) # # print(x) # # print(y) # # The abs() function returns the absolute (positive) value of the specified number: # # x = abs(-7.25) # # print(x) # # The pow(x, y) function returns the value of x to the power of y (xy). # # x = pow(4, 3) # # print(x) # # The Math Module # # Python has also a built-in module called math, which extends the list of mathematical functions. # # To use it, you must import the math module: # # import math # # When you have imported the math module, you can start using methods and constants of the module. # # The math.sqrt() method for example, returns the square root of a number: # # import math # # x = math.sqrt(64) # # print(x) # # The math.ceil() method rounds a number upwards to its nearest integer, and the math.floor() method rounds a number downwards to its nearest integer, and returns the result: # # import math # # x = math.ceil(1.4) # # y = math.floor(1.4) # # print(x, y) # # The math.pi constant, returns the value of PI(3.14...): # # import math # # x = math.pi # # print(x) # # PYTHON JSON # # JSON is a syntax for storing and exchanging data. # # JSON is text, written with JavaScript object notation. # # JSON in Python # # Python has a built-in package called json, which can be used to work with JSON data. # # import json # # Parse Json - Convert from JSON to python # # import json # # # some JSON # # x = '{"name":"Aman","age":30,"city":"Newyork"}' # # # parse JSON # # y = json.loads(x) # # print(y["age"]) # # Convert from Python to JSON # # If you have a Python object, you can convert it into a JSON string by using the json.dumps() method. # # import json # # x = { # # "name": "aman", # # "age": 30, # # "city": "New York", # # } # # y = json.dumps(x) # # print(y) # # You can convert Python objects of the following types, into JSON strings: # # dict # # list # # tuple # # string # # int # # float # # True # # False # # None # # import json # # print(json.dumps({"name": "John", "age": 30})) # # print(json.dumps(["apple", "bananas"])) # # print(json.dumps(("apple", "bananas"))) # # print(json.dumps("hello")) # # print(json.dumps(42)) # # print(json.dumps(31.76)) # # print(json.dumps(True)) # # print(json.dumps(False)) # # print(json.dumps(None)) # # When you convert from Python to JSON, Python objects are converted into the JSON(JavaScript) equivalent: # # Python JSON # # dict Object # # list Array # # tuple Array # # str String # # int Number # # float Number # # True true # # False false # # None null # # import json # # x = { # # "name": "John", # # "age": 30, # # "married": True, # # "divorced": False, # # "children": ("Ann", "Billy"), # # "pets": None, # # "cars": [ # # {"model": "BMW 230", "mpg": 27.5}, # # {"model": "Ford Edge", "mpg": 24.1} # # ] # # } # # print(json.dumps(x)) # # Format the Result # # The example above prints a JSON string, but it is not very easy to read, with no indentations and line breaks. # # The json.dumps() method has parameters to make it easier to read the result: # import json # x = { # "name": "John", # "age": 30, # "married": True, # "divorced": False, # "children": ("Ann", "Billy"), # "pets": None, # "cars": [ # {"model": "BMW 230", "mpg": 27.5}, # {"model": "Ford Edge", "mpg": 24.1} # ] # } # # print(json.dumps(x, indent=4)) # # You can also define the separators, default value is (", ", ": "), which means using a comma and a space to separate each object, and a colon and a space to separate keys from values: # # json.dumps(x, indent=4, separators=(". ", " = ")) # # Order the Result # # The json.dumps() method has parameters to order the keys in the result: # print(json.dumps(x, indent=4, sort_keys=True))
ccde44ee53b44088a6be9eea7a3d81fed7772dd9
Ivanochko/lab-works-python
/Else/bonus2/11ex.py
146
3.609375
4
array = input("Введіть потрібні елементи: ").split(' ') string = "" for ele in array: string += str(ele) print(string)
a5364a0755ace61ac7de0a8b8c720e0ffd3207e2
bobmayuze/RPI_Education_Material
/CSCI_1100/Week_4/Lab_3/Check_Point_1.py
884
4.25
4
# Author: Yuze Ma # Date: Sept, 19th, 2016 # This code is made for Lab 3, Checkpoint 1 """ This program experiments with the use of functions and also learning error checking. """ # Import math module to actvate the function import math ## Function returns the length of a line ## starting at (x1,y1) and ending at (x2,y2) def line_length(x1,y1,x2,y2): length = (x1-x2)**2 + (y1-y2)**2 length = math.sqrt(length) return length # Initialize all variables needed and input variables initial_x = 10 initial_y = 10 next_x = float(input("The next x value ==> ")) next_y = float(input("The next y value ==> ")) total_length = line_length(initial_x, initial_y, next_x, next_y) # output the resulets print("The line has moved from ({0:d},{1:d}) ".format(initial_x, initial_y),"to (", next_x, ",", next_y,")", sep = '') print("Total length traveled is",round(total_length))
fc7c54a70eb0f2a7be80af1da3b7e21575ff453c
igortereshchenko/amis_python
/km72/Gavrylenko_Olexandr/4/task3.py
372
4.09375
4
first_number = int(input('Enter 1st number:')) second_number = int(input('Enter 2nd number:')) third_number = int(input('Enter 3rd number:')) if first_number<second_number and third_number: print(first_number) elif second_number<first_number and third_number: print(second_number) elif third_number<first_number and second_number: print(third_number)
28c78a8b8de0c70a0304e58b9fe3618e25ee00dd
Hironobu-Kawaguchi/atcoder
/atcoder/abc187_c.py
552
3.515625
4
# https://atcoder.jp/contests/abc187/tasks/abc187_c n = int(input()) s = set() for i in range(n): s.add(input()) ans = 'satisfiable' for x in s: if ('!'+x) in s: ans = x break print(ans) # from collections import defaultdict # n = int(input()) # d = defaultdict(int) # for i in range(n): # s = input() # if s[0] == '!': # d[s[1:]] |= 1 # else: # d[s] |= 2 # ans = 'satisfiable' # for k,v in d.items(): # if v==3: # ans = k # break # print(ans)
010f61596c0f23e652d209d20a91728bb0ae1949
kalikrit/python
/weights.py
4,046
3.921875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Weights Manager description: split given weights list by number of platforms programming language: Python (3.4.0) author: Konstantin Kononenko (Moscow, Russia) email: kali-krit@mail.ru date: 29.09.2015 version: 1.1.7 """ def gen_all_subsets(given_set): """ function generates all possible subsets of the given set return set """ subsets = [()] for item in given_set: for subset in subsets: subsets = subsets + [tuple(subset) + (item,)] return set(subsets) def select_subset_for_platform(given_set, weights_per_platform): """ finds all subsets which sums to weights_per_platform return list """ subsets = gen_all_subsets(given_set) candidates = [] for subset in subsets: if sum(subset) <= weights_per_platform: candidates.append(subset) max_result = 0 selected_set = [] for candidate in candidates: if sum(candidate) > max_result: max_result = sum(candidate) selected_set = candidate return selected_set def exclude_set(from_set, given_set): """ helper function that substracts set from set return list """ from_set = list(from_set) given_set = list(given_set) result = [] for item in from_set[:]: if item in given_set[:]: from_set.remove(item) given_set.remove(item) else: result.append(item) return result def main(weights_list = [], num_of_platforms = 2, match_sum = 100): """ main function manage list of weights by number of platforms prints subsets for each platform by default num_of_platforms is 2 also prints whether there are subsets sums to match_sum (by default 100) """ # checking whether weights_list is not empty if len(weights_list) < 1: print('weights list should be set of natural numbers') return # checking whether weights_list length is greater than number of platforms if len(weights_list) < num_of_platforms: print('weights list should be greater than number of platforms') return # checking whether weights_list is not too long if len(weights_list) > 15: print("the programm is not optimized for such a long list") print("computation will take a long time") return print("managing ", weights_list, " by ", num_of_platforms, " platforms...") weights_per_platform = float(sum(weights_list)) / num_of_platforms print('weights per platform: ', weights_per_platform) print() weights_copy = weights_list[:] iter = 1 while iter < num_of_platforms: temp = select_subset_for_platform(weights_copy, weights_per_platform) print(temp, sum(temp)) weights_copy = exclude_set(weights_copy, temp) iter += 1 print(tuple(weights_copy), sum(weights_copy)) print() match = False all_subsets = gen_all_subsets(weights_list) for subset in all_subsets: if sum(subset) == match_sum: match = True print("this subset sums to ", match_sum, ' : ', subset) if not match: print('there are no subsets which sums to', match_sum) if __name__ == "__main__": print() print("enter list of natural numbers separated by '<space>'") user_input = input() # check user input: just select all positive numbers weights_list = [] for item in user_input.split(' '): try: num = int(item) if num > 0: weights_list.append(num) except Exception: pass print() #weights_list = (1,1,2,3,5) #weights_list = (1,3,2,3) #weights_list = (5,5,4,4,5,4) #main(weights_list, 3) #weights_list = (1,5,7,12) #weights_list = (10,20,2,80,30,15,3,15,18,8) #weights_list = (11,15,26,7,1,2,16,27,12,5,8,10,22,20,30) #main(weights_list, 4, 200) main(weights_list)
1374e4db560cc4f1a62d7536db055cf1a5c953c4
TanyaZhao/leetcode
/23_merge_k_sorted_lists.py
2,174
3.828125
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): # merge one by one => time limit exceeded def mergeKLists_one_by_one(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ if lists: cur_list = lists[0] if len(lists) > 1: for i in range(1, len(lists)): cur_list = self.mergeTwoLists(cur_list, lists[i]) return cur_list else: cur_list = ListNode(0) return cur_list.next # merge by devide and conquer def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ amount = len(lists) interval = 1 while amount > interval: for i in range(0, amount-interval, 2*interval): lists[i] = self.mergeTwoLists(lists[i], lists[i+interval]) interval *= 2 return lists[0] if amount > 0 else lists def creat_list(self, list): p_head = ListNode(None) p = p_head for i in list: p_node = ListNode(i) p.next = p_node p = p.next return p_head.next def print_list(self, p): print_list=[] if p: while p.next: print_list.append(str(p.val) + "->") p = p.next print_list.append(str(p.val)) print("".join(print_list)) else: print(p) def mergeTwoLists(self, p, q): head = None if not p: return q if not q: return p if p.val < q.val: head = p head.next = self.mergeTwoLists(p.next, q) else: head = q head.next = self.mergeTwoLists(p, q.next) return head solution = Solution() lists = [[1],[1],[-1],[-2],[6]] # lists = [] lists_node = [] for l in lists: lists_node.append(solution.creat_list(l)) merged_list = solution.mergeKLists(lists_node) solution.print_list(merged_list)
d4cff794127a2f34c9928151928b745aef25cbaa
clenioborgesx/Codigos
/Desafios/primoraiz.py
439
3.90625
4
num = int(input('Digite um numero: ')) raiz = (num**0.5) if num==2 or num==3: print("Primo") else: for i in range(1,int(raiz),1): pMod = num%i print(f"{i},{raiz},{num}") if pMod == 0: Composto+=1 else: primo+=1 if composto>1: print('Composto') else: print("Primo")
6f2b9b67d3442f0203f868a22948da1189bffbad
Repliika/Python-translator
/translate_script.py
707
3.71875
4
from translate import Translator #using 2 letter ISO or RFC306 to translate, can be switched out for other languages translator = Translator(to_lang="fr") try: with open('./text.txt', mode='r') as english_text: text = english_text.read() translation = translator.translate(text) #prints out what it is going to write into new translation file print(translation) #writes to new file with open('./text_French.txt', mode='w') as french_text: french_text.write(translation) #file must be called text otherwise it will error letting you know it cannot find it except FileNotFoundError as e: print("cannot locate the 'text' file")
1ecf5bfced0b2790e58f7f2b6c0b55e5430f16c1
VividLiu/LeeCode_Practice
/377_Combination_Sum_IV/combinationSum.py
2,155
3.703125
4
""" Solution: The straight forward solution: backtracking Ex. nums = [1,2,3], target = 4 The expanded backtracking tree is: root / | \ 1 2 3 / | \ / | / 1 2 3 1 2 1 | | 1 1 | 1 """ class Solution2(object): def combinationSum4(self, nums, target): """ :type nums : List[int] :type target: int :rtype : int """ res = [0] self.bt(nums, target, 0, res) return res[0] #the backtracking helper function to calculate how many ways to get the sum as target # @param nums : List[int], integers that can be used in the combination # @param target: int, target sum # @param cursum: int, current accumulating sum in this branch # @param res : int, the number ways accepted until current branch def bt(self, nums, target, cursum, res): if cursum > target: #reject return None elif cursum == target: #accept res[0] += 1 else: #generating next level of candidates for x in nums: self.bt(nums, target, cursum+x, res) return None """ Solution: Dynamic Programming Given a target t, and nums array, S(nums, t); how can we find the subproblem to construct the dp formula. If we pick nums[i] as the first one in the combination to reach t, then the next subproblem would be S(nums, t-nums[i]). Thus, S(nums, t) = sum( S(nums, t-nums[i]) where 0 <= i < len(nums) and nums[i] <= t) """ class Solution(object): def combinationSum4(self, nums, target): """ :type nums : List[int] :type target: int :rtype : int """ #initialzie dp array dp = [0] * (target + 1) #edge case dp[0] = 1 #fill the array bottom-up for i in xrange(1, len(dp)): dp[i] = sum( dp[i-nums[j]] for j in xrange(0, len(nums)) if nums[j] <= i) return dp[-1] """ test """ myTest = Solution() print myTest.combinationSum4([1,2,3], 4) print myTest.combinationSum4([1,3,5], 7)
8c6cad1cc80b57977534c17108251261d0f38202
lancerdancer/leetcode_practice
/code/bfs_and_topological_sort/210_course_schedule_ii.py
2,175
4.21875
4
""" https://leetcode.com/problems/course-schedule-ii/ There are a total of n courses you have to take, labeled from 0 to n-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses. There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array. Example 1: Input: 2, [[1,0]] Output: [0,1] Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1] . Example 2: Input: 4, [[1,0],[2,0],[3,1],[3,2]] Output: [0,1,2,3] or [0,2,1,3] Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3] . Note: The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented. You may assume that there are no duplicate edges in the input prerequisites. """ class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: n = numCourses node_neighbors = {x: [] for x in range(n)} node_indegree = {x: 0 for x in range(n)} for pair in prerequisites: node_neighbors[pair[1]].append(pair[0]) node_indegree[pair[0]] += 1 order = [] start_nodes = [key for key, value in node_indegree.items() if value == 0] q = collections.deque(start_nodes) while q: node = q.popleft() order.append(node) for neighbor in node_neighbors[node]: node_indegree[neighbor] -= 1 if node_indegree[neighbor] == 0: q.append(neighbor) if len(order) == n: return order return []
7bcef6537ab6d3c500e9b59e4d6844ec5b84efea
MHLUNATIC/Python
/study/demo3/反射.py
851
4.1875
4
# python中的反射功能是由以下四个内置函数提供:hasattr、getattr、setattr、delattr, # 四个函数分别用于对对象内部执行:检查是否含有某成员、获取成员、设置成员、删除成员。 #反射是通过字符串的形式操作对象相关的成员。一切事物都是对象 class Foo: def __init__(self, name,age): self.name = name self.age = age def show(self): return "%s-%s " %(self.name,self.age) obj = Foo('alex', 18) b = 'name' # getattr(obj, b)通过b实现调用self.name # inp = input('>>>') # v = getattr(obj, inp ) # 去什么东西里面获取什么内容 # print(v) func = getattr(obj, 'show') print(func) r = func() print(r) print(hasattr(obj, 'name')) # obj.k1 # setattr(obj, 'k1', 'v1') # print(obj.k1) # obj.name # delattr(obj, 'name') # obj.name
4dbd0f7a44923ee2ebebbcd71318253152e65901
green-fox-academy/bauerjudit
/week-3/tuesday/def.py
318
3.96875
4
def is_even(num): if num % 2 == 0: return "even" else: return "odd" print(is_even(8)) def add(a, b): return a + b num = add(3, 4) print(num) name = "" def greet (): print("hello " + name + "!") name = "Tojas" great() name = "Tomi" great() great("Tojas") great("Tomi")
d82c8ab41c8a8e774033ebbd413fd65667ad93d5
daidai21/Leetcode
/Algorithms/Python3.x/860-Lemonade_Change.py
755
3.75
4
# Runtime: 152 ms, faster than 75.38% of Python3 online submissions for Lemonade Change. # Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Lemonade Change. class Solution: def lemonadeChange(self, bills: List[int]) -> bool: fives, tens = 0, 0 for bill in bills: # find change target = bill - 5 if target >= 10 and tens > 0: tens -= 1 target -= 10 if fives >= target / 5: fives -= target / 5 else: return False # add change if bill == 5: fives += 1 elif bill == 10: tens += 1 return True
08d23822d01b46c574fae70b807f1ca3b6cfb122
tpt5cu/python-tutorial
/language/python_27/threading_py/locks_py.py
4,759
3.6875
4
# https://stackoverflow.com/questions/10525185/python-threading-how-do-i-lock-a-thread # https://stackoverflow.com/questions/3384385/python-3-2-gil-good-bad - deeper exploration of GIL # http://www.dabeaz.com/python/GIL.pdf - actual presentation on GIL # https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.2.0/com.ibm.zos.v2r2.bpxbd00/rtwaip.htm - explain waitpid() # https://stackoverflow.com/questions/11295298/waiting-for-threads-of-another-process-using-waitpid - waitpid() example problem import threading, multiprocessing, time, os, logging """ Thread locks: The threading.Lock class returns a Python Lock object. There's nothing more complicated to it than that. From my standpoint as an application programmer, there are no system calls or other configuration I need to know about. This is probably happening in the source code, but I don't need to know about it. """ good_lock = threading.Lock() def print_numbers(limit, snooze, space): """ All threads that run this function are working with the same good_lock object. Threads must synchronize on the SAME lock object, not different ones! - If I forget to release the lock, it will block all other threads forever and any non-daemon threads will keep the process alive forever! Control + C cannot kill the process if this happens because 1) signal handlers can only run in the main thread 2) the main thread is blocked by an uninterruptable lock 3) since it's blocked, the main thread never gets scheduled to run any kind of signal handler """ #bad_lock = threading.Lock() logging.warning('{}: about to acquire lock...'.format(threading.current_thread().name)) good_lock.acquire() logging.warning('{}: got the lock!'.format(threading.current_thread().name)) #bad_lock.acquire() for x in range(limit): logging.warning('{}: {}{}'.format(threading.current_thread().name, space, x)) time.sleep(snooze) good_lock.release() logging.warning('{}: lock released!'.format(threading.current_thread().name)) #bad_lock.release() def thread_acquire_lock(): """ In POSIX systems (to which Linux and macOS are related), when a child process inherits from a parent process that has multiple currently executing threads, the child process only inherits from the thread that called fork(). The threads in the parent process work with the lock just fine, but the child process forces the parent process to pause indefinitely. Why? I never explicitly joined the child process to the parent process, so why does the parent process wait? There is a clue in the stack trace. The parent process always appears to be paused on os.waitpid(). This system call "suspends the calling process until the system gets status information on the child." - The child process pauses indefinitely when: - The threads in the main process acquire the lock and don't join() to the parent process main thread - The threads in the parent process join() to the parent process main thread AFTER starting the child process - The threads in the main process don't run at all, but the main thread itself acquires and never releases the lock - The child process executes fine when: - The threads in the parent process don't acquire the lock - The threads in the parent process don't run at all - The parent main thread acquires the lock, but releases it at some arbitrary point in time - The threads in the parent process join() to the parent process main thread BEFORE starting the child process This leads me to believe that the child process inherits a lock object that is currently locked. Since the child process's thread lock is never released, the child process waits indefinitely. - Here's what must be happening. The child process gets a COPY of the parent process's address space. When the child gets its copy, it inherits a threading.Lock() object that is already locked. But wouldn't that mean it also inherited the executing threads from the parent process too? """ logging.basicConfig(filename=os.path.join(os.path.dirname(__file__), 'my-log.txt'), filemode='w', format='%(asctime)s: PID: %(process)s: %(message)s') logging.warning('started parent process') t0 = threading.Thread(target=print_numbers, args=[10, 0.5, ""]) t1 = threading.Thread(target=print_numbers, args=[10, 0.2, " "]) #good_lock.acquire() p0 = multiprocessing.Process(target=print_numbers, args=[10, 0.1, " "]) #time.sleep(5) #good_lock.release() t0.start() t1.start() #t0.join() #t1.join() p0.start() #t0.join() #t1.join() if __name__ == "__main__": thread_acquire_lock()
d98036208b155a98bf3814c73674a85c403aad92
rubayetalamnse/Random-Projects-With-Python
/6.guess-rubayet's current weight!.py
407
4.03125
4
weight = 58 your_gusess = int(input("Guess the weight! It's between 40 to 70 kg: ")) while your_gusess!= weight: if your_gusess<weight: print("try higher!") your_gusess = int(input("\nGuess the weight! It's between 40 to 70kg : ")) else: print("try lower!") your_gusess = int(input("\nGuess the weight! It's between 40 to 70kg : ")) print("my weight is revealed!")
eec4fb5727732280cd29f2bdb5c213968431e52b
harry-sparta/eng_48_coop_monster_inc
/monster_inc_run.py
1,162
3.828125
4
# Monster Inc Run file from monster_inc_class import * # Code to set user's monster name and skills monster_name = input('Give a name for a monster: ') monster_skills = input('Enter skills for the monster (separate each skill with a comma): ').strip().split(',') user_monster = Monster(monster_name, monster_skills) # Code to execute monster's name print('#########################MONSTER##INC#########################') print('\nMONSTER NAME: ', user_monster.name.upper()) print('--------------------------------------------------------------') print('MONSTER ATTRIBUTES') print('--------------------------------------------------------------') counter = 1 for skill in monster_skills: print(' SKILL', counter,': ', skill) counter += 1 print('--------------------------------------------------------------') print('MONSTER BEHAVIORS') print('--------------------------------------------------------------') print(' SLEEPING STYLE: ', user_monster.sleep()) print(' EATING STYLE: ', user_monster.eat()) print(' SCARE ATTACK: ', user_monster.scare_attack()) print('\n#########################MONSTER##INC#########################')
7cc9321430e4122779b01953755fa85486ebe3b6
sddaphal/Neural_Networks_for_Computer_Vision
/Codes/Digits_Classification/Data_Preprocessing/datasets_preparing.py
12,300
3.609375
4
# File: datasets_preparing.py # Description: Neural Networks for computer vision in autonomous vehicles and robotics # Environment: PyCharm and Anaconda environment # # MIT License # Copyright (c) 2018 Valentyn N Sichkar # github.com/sichkar-valentyn # # Reference to: # Valentyn N Sichkar. Neural Networks for computer vision in autonomous vehicles and robotics // GitHub platform. DOI: 10.5281/zenodo.1317904 # Preparing datasets for further using # Plotting first 100 examples of images with digits from 10 different classes # Pre-processing loaded MNIST datasets for further using in classifier # Saving datasets into file """Importing library for object serialization which we'll use for saving and loading serialized models""" import pickle # Importing other standard libraries import gzip import numpy as np import matplotlib.pyplot as plt # Creating function for loading MNIST images def load_data(file, number_of_images): # Opening file for reading in binary mode with gzip.open(file) as bytestream: bytestream.read(16) """Initially testing file with images has shape (60000 * 784) Where, 60000 - number of image samples 784 - one channel of image (28 x 28) Every image consists of 28x28 pixels with its only one channel""" # Reading data buf = bytestream.read(number_of_images * 28 * 28) # Placing data in numpy array and converting it into 'float32' type # It is used further in function 'pre_process_mnist' as it is needed to subtract float from float # And for standard deviation as it is needed to divide float by float data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32) # Reshaping data making for every image separate matrix (28, 28) data = data.reshape(number_of_images, 28, 28) # (60000, 28, 28) # Preparing array with shape for 1 channeled image # Making for every image separate matrix (28, 28, 1) array_of_image = np.zeros((number_of_images, 28, 28, 1)) # (60000, 28, 28, 1) # Assigning to array one channeled image from dataset # In this way we get normal 3-channeled images array_of_image[:, :, :, 0] = data # Returning array of loaded images from file return array_of_image # Creating function for loading MNIST labels def load_labels(file, number_of_labels): # Opening file for reading in binary mode with gzip.open(file) as bytestream: bytestream.read(8) """Initially testing file with labels has shape (60000) Where, 60000 - number of labels""" # Reading data buf = bytestream.read(number_of_labels) # Placing data in numpy array and converting it into 'int64' type labels = np.frombuffer(buf, dtype=np.uint8).astype(np.int64) # (60000, ) # Returning array of loaded labels from file return labels # Creating function for pre-processing MNIST datasets for further use in classifier def pre_process_mnist(x_train, y_train, x_test, y_test): # Normalizing whole data by dividing /255.0 x_train /= 255.0 x_test /= 255.0 # Data for testing consists of 10000 examples from testing dataset # Preparing data for training, validation and testing # Data for validation is taken with 1000 examples from training dataset in range from 59000 to 60000 batch_mask = list(range(59000, 60000)) x_validation = x_train[batch_mask] # (1000, 28, 28, 1) y_validation = y_train[batch_mask] # (1000,) # Data for training is taken with first 59000 examples from training dataset batch_mask = list(range(59000)) x_train = x_train[batch_mask] # (59000, 28, 28, 1) y_train = y_train[batch_mask] # (59000,) # Normalizing data by subtracting mean image and dividing by standard deviation # Subtracting the dataset by mean image serves to center the data. # It helps for each feature to have a similar range and gradients don't go out of control. # Calculating mean image from training dataset along the rows by specifying 'axis=0' mean_image = np.mean(x_train, axis=0) # numpy.ndarray (28, 28, 1) # Calculating standard deviation from training dataset along the rows by specifying 'axis=0' std = np.std(x_train, axis=0) # numpy.ndarray (28, 28, 1) # Taking into account that a lot of values are 0, that is why we need to replace it to 1 # In order to avoid dividing by 0 for j in range(28): for i in range(28): if std[i, j, 0] == 0: std[i, j, 0] = 1.0 # Saving calculated 'mean_image' and 'std' into 'pickle' file # We will use them when preprocess input data for classifying # We will need to subtract and divide input image for classifying # As we're doing now for training, validation and testing data dictionary = {'mean_image': mean_image, 'std': std} with open('mean_and_std.pickle', 'wb') as f_mean_std: pickle.dump(dictionary, f_mean_std) # Subtracting calculated mean image from pre-processed datasets x_train -= mean_image x_validation -= mean_image x_test -= mean_image # Dividing then every dataset by standard deviation x_train /= std x_validation /= std x_test /= std # Transposing every dataset to make channels come first x_train = x_train.transpose(0, 3, 1, 2) # (59000, 1, 28, 28) x_test = x_test.transpose(0, 3, 1, 2) # (10000, 1, 28, 28) x_validation = x_validation.transpose(0, 3, 1, 2) # (10000, 1, 28, 28) # Returning result as dictionary d_processed = {'x_train': x_train, 'y_train': y_train, 'x_validation': x_validation, 'y_validation': y_validation, 'x_test': x_test, 'y_test': y_test} # Returning dictionary return d_processed # Creating function for plotting examples from MNIST dataset def plot_mnist_examples(x_train, y_train): # Preparing labels for each class # MNIST has 10 classes from 0 to 9 labels = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] # Taking first ten different (unique) training images from training set # Going through labels and putting their indexes into list # Starting from '0' index i = 0 # Defining variable for counting total amount of examples m = 0 # Defining dictionary for storing unique label numbers and their indexes # As key there is unique label # As value there is a list with indexes of this label d_plot = {} while True: # Checking if label is already in dictionary if y_train[i] not in d_plot: d_plot[y_train[i]] = [i] m += 1 # Else if label is already in dictionary adding index to the list elif len(d_plot[y_train[i]]) < 10: d_plot[y_train[i]] += [i] m += 1 # Checking if there is already ten labels for all labels if m == 100: break # Increasing 'i' i += 1 # Preparing figures for plotting figure_1, ax = plt.subplots(nrows=10, ncols=10) # 'ax 'is as (10, 10) np array and we can call each time ax[0, 0] # Plotting first ten labels of training examples # Here we plot only matrix of image with only one channel '[:, :, 0]' # Showing image in grayscale specter by 'cmap=plt.get_cmap('gray')' for i in range(10): ax[0, i].imshow(x_train[d_plot[i][0]][:, :, 0], cmap=plt.get_cmap('gray')) ax[0, i].set_axis_off() ax[0, i].set_title(labels[i]) # Plotting 90 rest of training examples # Here we plot only matrix of image with only one channel '[:, :, 0]' # Showing image in grayscale specter by 'cmap=plt.get_cmap('gray')' for i in range(1, 10): for j in range(10): ax[i, j].imshow(x_train[d_plot[j][i]][:, :, 0], cmap=plt.get_cmap('gray')) ax[i, j].set_axis_off() # Giving the name to the window with figure figure_1.canvas.set_window_title('MNIST examples') # Showing the plots plt.show() # Creating function for plotting 35 images with random images from MNIST dataset # After images are created, we will assemble them and make animated .gif image def plot_mnist_35_images(x_train, y_train): # Making batch from training data with random data # Getting total number of training images number_of_training_images = x_train.shape[0] # Getting random batch of 'batch_size' size from total number of training images batch_size = 1000 batch_mask = np.random.choice(number_of_training_images, batch_size) # Getting training dataset according to the 'batch_mask' x_train = x_train[batch_mask] y_train = y_train[batch_mask] # Preparing labels for each class # MNIST has 10 classes from 0 to 9 labels = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] # Taking first ten different (unique) training images from training set # Going through labels and putting their indexes into list # Starting from '0' index i = 0 # Defining variable for counting total amount of examples m = 0 # Defining dictionary for storing unique label numbers and their indexes # As key there is unique label # As value there is a list with indexes of this label d_plot = {} while True: # Checking if label is already in dictionary if y_train[i] not in d_plot: d_plot[y_train[i]] = [i] m += 1 # Else if label is already in dictionary adding index to the list # In order to create 35 images we need 44 indexes of every class elif len(d_plot[y_train[i]]) < 44: d_plot[y_train[i]] += [i] m += 1 # Checking if there is already 440 indexes for all labels if m == 440: break # Increasing 'i' i += 1 # Creating 35 images by showing first image # And then deleting first line and upping data # Preparing figures for plotting figure_1, ax = plt.subplots(nrows=10, ncols=10) # 'ax 'is as (10, 10) np array and we can call each time ax[0, 0] for k in range(35): # Plotting first ten labels of training examples # Here we plot only matrix of image with only one channel '[:, :, 0]' # Showing image in grayscale specter by 'cmap=plt.get_cmap('gray')' for i in range(10): ax[0, i].imshow(x_train[d_plot[i][k]][:, :, 0], cmap=plt.get_cmap('gray')) ax[0, i].set_axis_off() ax[0, i].set_title(labels[i]) # Plotting 90 rest of training examples # Here we plot only matrix of image with only one channel '[:, :, 0]' # Showing image in grayscale specter by 'cmap=plt.get_cmap('gray')' for i in range(1, 10): for j in range(10): ax[i, j].imshow(x_train[d_plot[j][i + k]][:, :, 0], cmap=plt.get_cmap('gray')) ax[i, j].set_axis_off() # Creating unique name for the plot name_of_plot = str(k) + '_feeding_with_mnist.png' # Setting path for saving image path_for_saving_plot = 'feeding_images/' + name_of_plot # Saving plot figure_1.savefig(path_for_saving_plot) plt.close() # Plotting 100 examples of training images from 10 classes # We can't use here data after preprocessing x = load_data('datasets/train-images-idx3-ubyte.gz', 1000) # (1000, 28, 28, 1) y = load_labels('datasets/train-labels-idx1-ubyte.gz', 1000) # (1000,) # Also, making arrays as type of 'int' in order to show correctly on the plot plot_mnist_examples(x.astype('int'), y.astype('int')) # Loading whole data for preprocessing x_train = load_data('datasets/train-images-idx3-ubyte.gz', 60000) y_train = load_labels('datasets/train-labels-idx1-ubyte.gz', 60000) x_test = load_data('datasets/t10k-images-idx3-ubyte.gz', 1000) y_test = load_labels('datasets/t10k-labels-idx1-ubyte.gz', 1000) # Showing pre-processed data from dictionary data = pre_process_mnist(x_train, y_train, x_test, y_test) for i, j in data.items(): print(i + ':', j.shape) # x_train: (59000, 1, 28, 28) # y_train: (59000,) # x_validation: (1000, 1, 28, 28) # y_validation: (1000,) # x_test: (1000, 1, 28, 28) # y_test: (1000,) # Saving loaded and preprocessed data into 'pickle' file with open('data0.pickle', 'wb') as f: pickle.dump(data, f)
42b5fad842e2b32bc41b63c0f20f981b35afa8a3
juliomfreitas/onyo-bob
/powerball_backend/engine.py
511
3.59375
4
""" The powerball drawing engine """ import string import random class Engine: def generate_ticket(self): # randomize between ascii uppercase letters and digits # The parameter is the string length of the code returned randcode = lambda N: ''.join( random.choice( string.ascii_uppercase + string.digits ) for _ in range(N) ) return { 'prize_code': randcode(4), 'ticket_code': randcode(16) }
861fdbeb730127de554f257d09594f55b643f99d
amitravikumar/Guvi-Assignments
/Program10.py
246
4.21875
4
#WAP to find the power of any number number, power = map(int, input("Enter number and power: ").split()) def find_power(n,p): return n**p result = find_power(number, power) print(number, "rasied to the power ", power, " is ", result)
28cc72b168e59bc488909d3b46acaa832fbc6076
rohan9769/Python-Coding-and-Practice
/PythonObjectOrientedProgramming(Advanced)/2.Creating Objects.py
515
3.859375
4
#OOP #Making a wizard game class PlayerCharacter: def __init__(self,name,age): #Constructor Method,automatically called when instantiated that is when object is created self.name = name self.age = age def run(self): print("Running") player1 = PlayerCharacter('Roger',23) player2 = PlayerCharacter('Cindy',33) #Player 1 and Player 2 are Objects of the class PlayerCharacter print(player1.name) print(player1.age) player1.run() print(player2.name) print(player2.age) player2.run()
d496236b87a117e6184fdf91f99308141fc6ccfc
IJWh/FlippedSchool
/Find_First_and_Last_Position_of_Element_in_Sorted_Array.py
1,200
3.546875
4
# https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: def bi_search(left, right ): mid = int((left + right) / 2) if nums[left] == target: return left elif nums[right] == target: return right elif nums[mid] == target: return mid elif left >= right: return -1 elif nums[mid] < target: return bi_search(mid+1, right-1) else: return bi_search(left+1, mid-1) if len(nums) == 0: return [-1,-1] detected = bi_search(0,len(nums)-1) start = detected end = detected while start >= 0: if start >= 1 and nums[start-1] == target: start -= 1 else: break while end < len(nums): if end <= len(nums)-2 and nums[end+1] == target: end += 1 else: break return [start,end]
a552acbbb7e6a2aceecd2e2fb98e60fa54872cdb
thangarajan8/misc_python
/hackers_rank/itr_cpw.py
192
3.5625
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 28 18:06:48 2019 @author: 10541 """ from itertools import combinations_with_replacement print(list(combinations_with_replacement('12345',2)))
e61d14ce6ca50f0303c6c6e175c24ec0084654c6
wjr0102/Leetcode
/Easy/1170Compare_String_Freq.py
1,527
3.859375
4
#!/usr/local/bin # -*- coding: utf-8 -*- # @Author: Jingrou Wu # @Date: 2019-08-31 18:33:12 # @Last Modified by: Jingrou Wu # @Last Modified time: 2019-08-31 18:43:56 ''' Input: queries, words Output: The number of words with less f(frequency) than queries. Funtion: f(frequency) The frequency of the smallest character ''' class Solution(object): def numSmallerByFrequency(self, queries, words): """ :type queries: List[str] :type words: List[str] :rtype: List[int] """ freq_q = [] freq_w = [] ans = [0 for i in range(queries)] # Get the frequency of the queries for query in queries: freq_q.append(getFrequency(query)) for word in words: freq_w.append(getFrequency(word)) for i in range(queries): for j in range(words): if freq_w[j] > freq_q[i]: ans[i] += 1 return ans def getFrequency(self, word): """ Find the frequency of the smallest character. :type words: str :rtype: int """ # if word is empty then return 0 if not word: return 0 # while word is not empty ch = word[0] # choose the first character as the samllest one freq = 1 # the frequency of ch for c in word[1:]: if c < ch: ch = c freq = 1 elif c == ch: freq += 1 return freq
85652a0153f3eba83fac509a8da8176a55883a58
nishantchauhan00/GeeksForGeeks
/Companies Question/57 Stickler Thief.py
594
3.5625
4
def solver(arr, n): if n < 3: return max(arr) # we can do it by dp, but we need only two previous values # so to save space we use just two integer variables prev_before = arr[0] prev = max(arr[0], arr[1]) # previous value can be first value if its greater for i in range(2, n): curr = max(prev_before + arr[i], prev) prev_before = prev prev = curr # the last value stores the max value return prev T = int(input()) for _ in range(T): n = int(input()) arr = list(map(int, input().split())) print(solver(arr, n))
5b1b2e392828ae6d113c59154fbd70d45a3e6a97
tainenko/Leetcode2019
/leetcode/editor/en/[2034]Stock Price Fluctuation .py
4,062
3.625
4
# You are given a stream of records about a particular stock. Each record # contains a timestamp and the corresponding price of the stock at that timestamp. # # Unfortunately due to the volatile nature of the stock market, the records do # not come in order. Even worse, some records may be incorrect. Another record # with the same timestamp may appear later in the stream correcting the price of the # previous wrong record. # # Design an algorithm that: # # # Updates the price of the stock at a particular timestamp, correcting the # price from any previous records at the timestamp. # Finds the latest price of the stock based on the current records. The latest # price is the price at the latest timestamp recorded. # Finds the maximum price the stock has been based on the current records. # Finds the minimum price the stock has been based on the current records. # # # Implement the StockPrice class: # # # StockPrice() Initializes the object with no price records. # void update(int timestamp, int price) Updates the price of the stock at the # given timestamp. # int current() Returns the latest price of the stock. # int maximum() Returns the maximum price of the stock. # int minimum() Returns the minimum price of the stock. # # # # Example 1: # # # Input # ["StockPrice", "update", "update", "current", "maximum", "update", "maximum", # "update", "minimum"] # [[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []] # Output # [null, null, null, 5, 10, null, 5, null, 2] # # Explanation # StockPrice stockPrice = new StockPrice(); # stockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10] # . # stockPrice.update(2, 5); // Timestamps are [1,2] with corresponding prices [1 # 0,5]. # stockPrice.current(); // return 5, the latest timestamp is 2 with the # price being 5. # stockPrice.maximum(); // return 10, the maximum price is 10 at timestamp 1 # . # stockPrice.update(1, 3); // The previous timestamp 1 had the wrong price, so # it is updated to 3. # // Timestamps are [1,2] with corresponding prices [3 # ,5]. # stockPrice.maximum(); // return 5, the maximum price is 5 after the # correction. # stockPrice.update(4, 2); // Timestamps are [1,2,4] with corresponding prices # [3,5,2]. # stockPrice.minimum(); // return 2, the minimum price is 2 at timestamp 4. # # # # Constraints: # # # 1 <= timestamp, price <= 10⁹ # At most 10⁵ calls will be made in total to update, current, maximum, and # minimum. # current, maximum, and minimum will be called only after update has been # called at least once. # # # Related Topics Hash Table Design Heap (Priority Queue) Data Stream Ordered # Set 👍 1009 👎 54 # leetcode submit region begin(Prohibit modification and deletion) import heapq class StockPrice: def __init__(self): self.prices = dict() self.min_heap = [] self.max_heap = [] self.timestamp = 0 def update(self, timestamp: int, price: int) -> None: self.prices[timestamp] = price heapq.heappush(self.min_heap, (price, timestamp)) heapq.heappush(self.max_heap, (-price, timestamp)) self.timestamp = max(self.timestamp, timestamp) def current(self) -> int: return self.prices[self.timestamp] def maximum(self) -> int: p, t = heapq.heappop(self.max_heap) while self.prices[t] != -p: p, t = heapq.heappop(self.max_heap) heapq.heappush(self.max_heap, (p, t)) return -p def minimum(self) -> int: p, t = heapq.heappop(self.min_heap) while self.prices[t] != p: p, t = heapq.heappop(self.min_heap) heapq.heappush(self.min_heap, (p, t)) return p # Your StockPrice object will be instantiated and called as such: # obj = StockPrice() # obj.update(timestamp,price) # param_2 = obj.current() # param_3 = obj.maximum() # param_4 = obj.minimum() # leetcode submit region end(Prohibit modification and deletion)
058499366d0b9ce1aa19b536e73339455c2824a7
aditya-c/leetcode_stuff
/AlgoPractice.py
160
4.125
4
# Reverse an interger i = 123 reverse_i = int(str(i)[::-1]) print("{} is of type {}".format(reverse_i, type(reverse_i))) s = "Hello!" u = unicode(s, "utf-8")
5e53917125b152a0525e1404d09dfad644a8b94f
TerryRPatterson/Coursework
/python/test.py
246
3.90625
4
import math def isPrime(n): a = 2 b = -1 while n % 2 == 0: return False while a + b < n : b = math.sqrt(abs((a ** 2)-n)) if b.is_integer() and b > 1: return False a += 1 return True
116ac3d3aaf2409af11e813766696feb8973156f
jn7dt/aoc_2018
/Day 1/Problem 1/solution_1.py
317
3.515625
4
INPUT = 'Day 1\input_problem.txt' STARTING_FREQUENCY = 0 with open(INPUT, 'r') as f: frequency_inputs = f.readlines() frequency_changes = [float(frequency) for frequency in frequency_inputs] resulting_frequency = STARTING_FREQUENCY + sum(frequency_changes) print(f'Resulting frequency: {resulting_frequency}')
dd56a43166540d129bbfe101196f4360bc5fcf41
AP-MI-2021/lab-3-FlaviuIanchis
/main.py
4,008
3.546875
4
def crescator(l): ''' Ne afiseaza cea mai lunga subsecventa de numere crescatoare dintr-o lista de numere :param l: :return: ''' list = [] list_aux = [] i=0 while(i<len(l)-1): if (l[i]<=l[i+1]): list_aux.append(l[i]) else: list_aux.append((l[i])) list.append(list_aux) list_aux = [] i=i+1 list_aux.append(l[i]) list.append(list_aux) max = 0 poz =-1 for i in range(len(list)): if max < len(list[i]): max = len(list[i]) poz = i return list[poz] def test_crescator(): assert crescator([1,2,3,2,4]) == [1,2,3] assert crescator([6,2,3,5,2,4]) == [2,3,5] assert crescator([7,3,2,4]) == [2,4] def divizibil(l,k): ''' Ne afiseaza cea mai lunga subsecventa de numere divizibile cu un numar dat :param l: :return: ''' list = [] list_aux = [] i = 0 while (i<len(l)): if(l[i]%k==0): list_aux.append(l[i]) else: list.append(list_aux) list_aux = [] i = i+1 list.append(list_aux) max = 0 poz = -1 for i in range(len(list)): if max < len(list[i]): max = len(list[i]) poz = i return list[poz] def test_divizibil(): assert divizibil([5,10,2,3],5)==[5,10] assert divizibil([2,10,4,3,6,8],2)==[2,10,4] assert divizibil([100,10,3,6,8],2)==[100,10] def medie(l, med): ''' Ne afiseaza cea mai lunga subsecventa a caror medie nu depaseste o valoare citita :param l: :return: ''' list = [] med_aux=0 i = 0 suma = 0 while(i<len(l)): list_aux = l suma +=l[i] for j in range(i+1,len(l)): suma +=l[j] med_aux = suma/(len(l)-i+1) if (med_aux<med): print(l[i:len(l)]) list.append(l[i:len(l)]) else: while((suma>0) and (med_aux>med) and (len(list_aux)>1)): suma -= list_aux[len(list_aux)-1] list_aux=list_aux[i:len(list_aux)-1] print(len(list_aux)) if (len(list_aux)!=0): med_aux = suma/(len(list_aux)) print(suma,"",len(list_aux)) list.append(list_aux) list_aux = [] suma = 0 med_aux = 0 i +=1 max = 0 poz = -1 for i in range(len(list)): if max < len(list[i]): max = len(list[i]) poz = i return list[poz] def test_medie(): assert medie([1,2,3,1,2],3) == [1,2,3,1,2] assert medie([3,3,3,111,222],3) == [3,3,3] assert medie([111,222,3,3,3],3) == [3,3,3] def print_menu(): print('1.Citirea listei') print('2.Determina cea mai lunga subsecventa de numere crescatoare') print('3.Determina cea mai lunga subsecventa de numere divizibile cu un numar dat') print('4.Determina cea mai lunga subsecventa a caror medie nu depaseste o valoare citita') print('0.Exit') def main(): test_crescator() test_divizibil() test_medie() print_menu() while True: opt = int(input('Dati optiunea ')) if opt == 1: l = [] nr = int(input('Dati lungimea listei de numere ')) print('Introduceti elementele listei: ') for i in range(nr): el = int(input()) l.append(el) print(l) elif opt == 2: print(crescator(l)) elif opt == 3: k = int(input('Dati numarul ')) print(divizibil(l,k)) elif opt == 4: med = float(input('Dati un numar ')) print(medie(l,med)) elif opt == 0: break else: print('Optiune invalida') main()
9d9fce82ec5cff53d9cf286b0e6fb30b25fffe34
xiaomojie/LeetCode
/Hash Table/389_Find_the_Difference.py
785
3.71875
4
""" Given two strings s and t which consist of only lowercase letters. String t is generated by random shuffling string s and then add one more letter at a random position. Find the letter that was added in t. Example: Input: s = "abcd" t = "abcde" Output: e Explanation: 'e' is the letter that was added. """ import collections class Solution: def findTheDifference(self, s, t): """ :type s: str :type t: str :rtype: str """ return list((collections.Counter(t) - collections.Counter(s)).elements())[0] def findTheDifference1(self, s, t): s, t = sorted(s), sorted(t) return t[-1] if s == t[:-1] else [x[1] for x in zip(s, t) if x[0] != x[1]][0] s = "a" t = "aa" print(Solution().findTheDifference(s, t))
64246927e8e7fe56a178fc96a7195abd755e3b49
nelvinpoulose999/Pythonfiles
/oops/bankapplication.py
871
4.0625
4
class Bank: bankname='SBK' # class variable/static variable it is used for reduce memory allocations def create_account(self,accno,pname,minbalance): self.accno=accno #} self.personname=pname #} instance variable(self.accno,self.personname,etc self.balance=minbalance #} print(self.accno,self.personname,self.balance,Bank.bankname) def deposit(self,amount): self.balance+=amount print(self.personname,'account credited with',amount,'the balance amount',self.balance) def withdraw(self,amount): if amount>self.balance: print("insufficient balance") else: self.balance-=amount print('account debited with', amount, 'the balance amount', self.balance) obj = Bank() obj.create_account(1000,'Akhil',3000) obj.deposit(5000) obj.withdraw(2000)
8cde971b5dfb2fddecf3d2da0660088a267ac703
YRMYJASKA/AdventOfCode2020
/22/sol.py
1,987
3.53125
4
from copy import deepcopy def part1(decks): while len(decks[1]) > 0 and len(decks[2]) > 0: p1 = decks[1].pop(0) p2 = decks[2].pop(0) if p1 > p2: decks[1] += [p1, p2] else: decks[2] += [p2, p1] winner = 1 if len(decks[1]) == 0: winner = 2 return calcscore(decks[winner]) def calcscore(deck): return sum((i+1)*v for i, v in enumerate(deck[::-1])) def part2(decks): states = {0: {1: 0, 2: 0}} i = 1 while len(decks[1]) > 0 and len(decks[2]) > 0: # check if in previous states ds1 = calcscore(decks[1]) ds2 = calcscore(decks[2]) for _, v in states.items(): if v[1] == ds1 and v[2] == ds2: # Player 1 wins return ds1, 1 states[i] = {1: ds1, 2: ds2} i += 1 p1 = decks[1].pop(0) p2 = decks[2].pop(0) if len(decks[1]) >= p1 and len(decks[2]) >= p2: ndecks = deepcopy(decks) ndecks[1] = ndecks[1][:p1] ndecks[2] = ndecks[2][:p2] _, winner = part2(ndecks) if winner == 1: decks[1] += [p1, p2] else: decks[2] += [p2, p1] continue # Regular comparison if p1 > p2: decks[1] += [p1, p2] else: decks[2] += [p2, p1] winner = 1 if len(decks[1]) == 0: winner = 2 return calcscore(decks[winner]), winner if __name__ == "__main__": idecks = {} idecks[1] = [] idecks[2] = [] with open("input.txt", "r") as f: playerswitch = 1 for l in f: ll = l.strip() if "Player 2" in ll: playerswitch = 2 if len(ll) == 0 or "Player" in ll: continue else: idecks[playerswitch].append(int(ll)) print("Part 1:", part1(deepcopy(idecks))) print("Part 2:", part2(deepcopy(idecks))[0])
5ab4012832cf794403e9a92938e8a990a009ce72
yashwant-nagarjuna/Reflections
/duplicate_count.py
248
3.71875
4
import collections def duplicate_count(text): n = collections.Counter(text.lower()) count = 0 for i in n.values(): if i > 1: count += 1 return count result = duplicate_count("Indivisibilities") print(result)
8d0cda65fd53435929f767b42cfe4708bea1711b
hugovalef/lista1---python-brasil
/exercicio2.py
269
4.09375
4
''' n1 = int(input('digite um numero ')) print('o numero informado foi:',n1)f ''' ''' n1=int(input('digite um numero ')) print('o numero informado foi %d' %a) ''' n1 = input('digite um numero ') #n1 = int(n1) print ('o numero informado foi ', n1)
9640d1b515cefe5b273517d40619deee500ed59f
grapess/python_eleven_2019
/62.py
228
3.703125
4
def line(symbol,times) : result = "" count = 1 while count <= times: result += symbol count += 1 print(result) line('-',20) print(" Hello ") line('=',30) print(" Grapess ") line('~',40) print(" Solutions ") line('_',50)
f05847893d78a12e7b736aa6f4564dc7aea0cb61
Oracy/curso_em_video
/Exercicios/027.py
192
4
4
name = str(input('Type your full name: ')).strip() name = name.split(' ') size = len(name) first = name[0] last = name[size-1] print("""First Name: {0} Last Name: {1}""".format(first, last))