blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
ce0d80749e9edddf3e333c7e1ed391e069aa38df | LeonXZhou/ScienceQuestTeachingPrograms | /Pong Code/step3AddingaBall.py | 7,052 | 4.125 | 4 | #By Leon Zhou
import pygame as pygame #import required modules
import random as random # note we imported random not just pygame.
# The below code shows how to add a player as just a shape without
#using objects. We build on the CreatingRectangleNonObjectPlayers.py example.
# Explanation for window code is omitted
dimensions = [500,300]
screen = pygame.display.set_mode(dimensions)
backgroundColour = [0,0,0]
screen.fill(backgroundColour)
running = True
playerXPosition = 450
playerYPosition = 125
player2XPosition = 40
player2YPosition = 125
width = 10
height = 50
ballXPosition =245 #Here we initiate the properties of the ball. its position, radius, and speed.
ballYPosition = 145
ballRadius = 5
ballxSpeed = random.choice((-1,1))*random.randint(1,6)/200 # We use a random number generator to determine the speed at the beginning.
ballySpeed = random.choice((-1,1))*random.randint(1,6)/200 # the code here generates a random integer from -5 to 5 [5,6). 6 is not included!
# we then divide that number by 200 or the ball moves to fast. The 200 was arbitrary
# you can play around with it until you find a good value.
rectanglePlayer = pygame.Rect(playerXPosition,playerYPosition,width,height)
rectanglePlayer2 = pygame.Rect(player2XPosition, player2YPosition , width, height)
rectanglePlayerColour = [150,23,10] # 3 element array representing the colour of the player
ballColour = [250,250,250]
pygame.draw.rect(screen,rectanglePlayerColour,rectanglePlayer)
pygame.draw.circle(screen,ballColour,(ballXPosition,ballYPosition),ballRadius) # here we use the draw module to draw a cirle. It requires 4 arguements.
# (surface,color,position,radius)
# surface: the object we are drawing onto. in this case it is the display objects
# we saved as screen
# color: color of the rectangle
# position: a 2 element array with x and y position
# radius: the radius of the circle
pygame.display.flip()
# below is the main game loop.
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keysPressed = pygame.key.get_pressed() # Here we use the built in pygame function get_pressed() to retrieve the state of all the keys
# and save it into an array called keysPressed. Each element in keysPressed reperesents a key on
# the keyboard. If it is a 0 the key is not pressed. If it is a 1 the key is pressed.
if keysPressed[pygame.K_DOWN] and playerXPosition>0: # This if statement updates the position of the player to the left.
playerYPosition = playerYPosition+.05 # Pygame has built in constants. For example pygame.K_LEFT is 276. This means that the 276th
# element in the array returted by get_pressed() represents the left arrow key. Therefore keysPressed[pygame.K_LEFT]
# is 1 if the left arrow is pressed and 0 if the left arrow is not pressed. In the if statement we check if the
# key is pressed (Remember 1 = true and 0 = false) and if the position of the player is sitll within bounds of the
# window. If it is we update the x position of the player.
if keysPressed[pygame.K_UP] and playerXPosition<780: # This if statment moves the player to the right. It works in the same way as move left. One thing to note since
playerYPosition = playerYPosition-.05 # The x position of the rectangle is its left edge. So if we want it to stop when the right edge hits the wall
# we have to do 780 instead of 800. (the rectangle is 20 wide)
if keysPressed[pygame.K_w] and playerXPosition<780:
player2YPosition = player2YPosition-.05
if keysPressed[pygame.K_s] and playerXPosition<780:
player2YPosition = player2YPosition+.05
ballXPosition = ballXPosition+ballxSpeed # Update ball position
ballYPosition = ballYPosition+ballySpeed
rectanglePlayer = pygame.Rect(playerXPosition,playerYPosition,width,height)
rectanglePlayer2 = pygame.Rect(player2XPosition, player2YPosition, width, height)
#in the below section we animate our game.
screen.fill(backgroundColour) # Since our shape moved the first thing we do is clear the screen
pygame.draw.rect(screen,rectanglePlayerColour,rectanglePlayer) # we draw the player onto screen in its new position
pygame.draw.rect(screen,rectanglePlayerColour,rectanglePlayer2)
pygame.draw.circle(screen,ballColour,(int(ballXPosition),int(ballYPosition)),ballRadius) # note that when I give the position for circle draw
# I put each of the variables inside of a int(variable).
# this is because the circle version of draw only accepts integers
# however our ball positions are decimals
# the int() turns whatever is in the brackets to an integer (idk about
# python but other languages usually just drops the decimal numbers. some
# round though. you can test this yourself)
pygame.display.flip() # we use the flip() command to display the entire window again
|
8c75a1a2653eb651b60f520345213f2a750aae95 | Cavalcantefilipe/cs50-web-programing | /Python/loops.py | 167 | 4.03125 | 4 | for i in range(4):
print(i)
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(name)
name = "Filipe"
for caracteres in name:
print(caracteres)
|
a2c36a29c113bc3e859964619f789ca534d9c90b | everydaytimmy/data-structures-and-algorithms | /python/code_challenges/hashmap_left_join/hashmap_left_join.py | 627 | 3.703125 | 4 | from code_challenges.hashtable.hashtable import Hashtable
def hashmap_left_join(ht1, ht2):
answer = []
for bucket in ht1._bucket:
if bucket:
current = bucket.head
while current:
current_key = current.data[0]
current_value = current.data[1]
pairs = [current_key, current_value]
if ht2.contains(current_key):
pairs.append(ht2.get(current_key))
else:
pairs.append(None)
answer.append(pairs)
current = current.next
return answer
|
8146d291bad0d0938f624ff9b7dcbf6b93a491e3 | everydaytimmy/data-structures-and-algorithms | /python/tests/test_breadth_first_graph.py | 1,272 | 3.515625 | 4 | from code_challenges.depth_first_graph.depth_first_graph import depth_traversal, Stack, Node
from code_challenges.graph.graph import Graph, Vertex
def test_depth_traversal_exists():
assert depth_traversal
def test_depth_traversal_one():
graph = Graph()
boston = graph.add_node('Boston')
seattle = graph.add_node('Seattle')
la = graph.add_node('LA')
sf = graph.add_node('SF')
chi = graph.add_node('CHI')
ny = graph.add_node('NY')
graph.add_edge(boston, ny, 82)
graph.add_edge(boston, chi, 90)
graph.add_edge(ny, chi, 42)
graph.add_edge(ny, seattle, 200)
graph.add_edge(ny, la, 225)
graph.add_edge(ny, sf, 230)
graph.add_edge(chi, seattle, 175)
graph.add_edge(seattle, sf, 85)
graph.add_edge(sf, la, 85)
actual = depth_traversal(boston, graph)
expected = [boston, chi, seattle, sf, la, ny]
assert actual == expected
def test_depth_traversal_two():
graph = Graph()
city = graph.add_node('Boston')
town = graph.add_node('Seattle')
place = graph.add_node('LA')
graph.add_edge(city, town, 82)
graph.add_edge(town, place, 90)
graph.add_edge(city, place, 42)
actual = depth_traversal(city, graph)
expected = [city, place, town]
assert actual == expected
|
f34dda828ad84815f41a2ba1b2199410f9b4d0dc | everydaytimmy/data-structures-and-algorithms | /python/code_challenges/breadth_first/breadth_first.py | 1,750 | 3.921875 | 4 |
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def add(self, value):
if not self.root:
self.root = Node(value)
return
def walk(root):
if not root:
return
if not root.left:
root.left = Node(value)
return
if root.left and not root.right:
root.right = Node(value)
return
walk(root.left)
walk(root.right)
walk(self.root)
@staticmethod
def breadth(tree = None):
list = []
queue = Queue()
queue.enqueue(tree.root)
if not tree:
return []
while queue.peek():
node = queue.dequeue()
list.append(node.value)
if node.left:
queue.enqueue(node.left)
if node.right:
queue.enqueue(node.right)
return list
class Queue:
def __init__ (self):
self.front = None
self.rear = None
def enqueue(self, value):
if self.front is None:
self.front = self.back = QNode(value)
else:
self.back.next = QNode(value)
def dequeue(self):
if self.front is None:
return
ret = self.front.value
self.front = self.front.next
return ret
def is_empty(self):
return self.front is None
def peek(self):
if self.front:
return self.front.value
class QNode:
def __init__(self, value, next = None):
self.value = value
self.next = next
|
73bcec6b393517af28ea6d4db20ad93c57522602 | harix1606/Word-and-letter-frequency-analyser | /finalproject.py | 9,732 | 3.75 | 4 | import string
import time
def palindrome_checker(word): #checks if word is palindrome. Returns True if palindrome, else returns False.
length= len(word)
if length==0:
return False
if length==1:
if word== "a" or word=="i":
return True
else:
return False
if not word.isalpha():
return False
if length>1:
word = word.lower() #convert the word into lower case and then compare.
compare = word[length:0:-1]+word[0] #adding word[0] because previous slice doesn't include last index(0).
if word == compare:
return True
else:
return False
def words(line, lettercount): #defining function which seperates line into words and counts letters.
vals=[0] #saves the indices where a space (" ") occurred. Adding index where first word starts (0).
for i in range(0,len(line)):
c=line[i].lower() #c for character.
if c== " ":
vals= vals+[i] #saves index if c was space.
if c == "a": #else adds one to the value corresponding to the letter key in dictionary defined below.
lettercount[0]+= 1
if c == "b":
lettercount[1]+= 1
if c == "c":
lettercount[2]+= 1
if c == "d":
lettercount[3]+= 1
if c == "e":
lettercount[4]+= 1
if c == "f":
lettercount[5]+= 1
if c == "g":
lettercount[6]+= 1
if c == "h":
lettercount[7]+= 1
if c == "i":
lettercount[8]+= 1
if c == "j":
lettercount[9]+= 1
if c == "k":
lettercount[10]+= 1
if c == "l":
lettercount[11]+= 1
if c == "m":
lettercount[12]+= 1
if c == "n":
lettercount[13]+= 1
if c == "o":
lettercount[14]+= 1
if c == "p":
lettercount[15]+= 1
if c == "q":
lettercount[16]+= 1
if c == "r":
lettercount[17]+= 1
if c == "s":
lettercount[18]+= 1
if c == "t":
lettercount[19]+= 1
if c == "u":
lettercount[20]+= 1
if c == "v":
lettercount[21]+= 1
if c == "w":
lettercount[22]+= 1
if c == "x":
lettercount[23]+= 1
if c == "y":
lettercount[24]+= 1
if c == "z":
lettercount[25]+= 1
vals= vals+[len(line)+1] #adds index where the last word ends
newwords= [] #lsit that will store all the words.
for i in range (0, len(vals)-1):
newwords+= [line[vals[i]:vals[i+1]].lower()] #saving words intoo newwords.
for index in range(0, len(newwords)):
newwords[index]= newwords[index].strip(string.punctuation).strip().strip('"()') #removing all punctuation that occurrs before and after words.
return newwords #returning the list of words.
allwords={} #dictionary to store occurrences of each word.
allletters=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
lettercount=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] #list to store occurrences of each letter.
palindromes={} #dictionary to store occurrences of each palindrome.
#error handling while taking input for filename in case file name is invalid.
count=0 #variable to check if errors have previously occurred while enterring filename.
while True:
try:
if count==0: #no errors have previously occurred.
inputed_file_name= raw_input("please enter address of text file to be evaluated: ")
pride= open(inputed_file_name, "r") #opening file in read mode.
print "File accepted. Evaluation in process"
break
if count >0: #error has previously occurred.
inputed_file_name= raw_input("File name not recognized. Please reenter: ")
pride= open(inputed_file_name, "r")
print "File accepted. Evaluation in process"
break
except: #if error occurs
count= count+1
count=0 #resetting variable for future use.
for line in pride: #iterating through the file line by line.
temp= line.strip() #removing all spaces before and after each line.
newwords= words(temp,lettercount) #calls function words defined above.
for word in newwords:
if (palindrome_checker(word)): #calls palindrome_checker function defined above to check if word is palindrome.
if word not in palindromes:
palindromes[word]=1 #adds new key and value to palindrome dictionary if not already present in it.
else:
palindromes[word]+= 1 #edits value of preexisting key
if word not in allwords: #adds new key and value to allwords dictionary if not already present in it.
allwords[word]=1
else: #only eidts value if word is already present.
allwords[word]= allwords[word]+1
perclettercount=[]
count= 0
for letter in lettercount:
count= count+ letter #counts total number of letters to calculate percentage occurrence of each letter.
print "\n \n \nOccurences of Each Letter in the given text \n \n"
time.sleep(1) #pause after print statement allows user to read.
for i in range(0,26):
perc= (float(lettercount[i])/count)*100
perclettercount += [perc]
print allletters[i], ":", lettercount[i], " "*(8-len(str(allletters[i])+":"+str(lettercount[i]))),"(", '%.2f' %perc, "%", ")" #string after third comma is to calculte number of spaces to print for editing purposes.
time.sleep(1)
words_printed= int(raw_input("\nHow many of the top most frequently occurring words do you want to see: "))
print "\n"
time.sleep(1)
import operator
sorted_allwords = sorted(allwords.items(), key=operator.itemgetter(1)) #converts the dictionary into a list of sorted lists on the basis of values.
sorted_palindromes= sorted(palindromes.items(), key= operator.itemgetter(1))
count=1
for i in range (len(sorted_allwords)-1, len(sorted_allwords)-(words_printed+1),-1): #Iterates through the most frequent words in descending order
print str(count)+ ")", sorted_allwords[i][0], " "*(18- len(str(count)+ ")"+ (str(sorted_allwords[i][0])))), ":", sorted_allwords[i][1], "occurences"
count += 1
time.sleep(0.5)
print "\n \n \nOccurences of Palindromes in the given text \n \n"
time.sleep(1)
count=1
for i in range(len(sorted_palindromes)-1, -1,-1):
print str(count)+ ")", sorted_palindromes[i][0], " "*(15- len(str(count)+")"+ (str(sorted_palindromes[i][0])))), ":", sorted_palindromes[i][1]
count+=1
#Program to print graph of percentage of each letter occurrence.
import numpy as np
import matplotlib.pyplot as plt
N = 26
ind = np.arange(N) # the x locations for the groups
width = 0.45 # the width of the bars
ax = plt.subplots()[1] #plt.subplots()[1] returns the axes objects that are later used to specify the labels and ticks.
white_means = (14, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
rectdummy = ax.bar(ind + width, white_means, width, color='w') #dummy values to get the scale correct. Printed in white so invisible.
#bars of the expected letter frequencies of each letter
expected_means = (8.16, 1.49, 2.78, 4.25, 12.70, 2.22, 2.01, 6.09, 6.96, 0.15, 0.77, 4.02, 2.40, 6.74, 7.50, 1.92, 0.09, 5.98, 6.32, 9.05, 2.75, 0.97, 2.36, 0.15, 1.97, 0.07)
expectedbars = ax.bar(ind, expected_means, width, color='yellow')
#bars of the actual letter frequencies of each letter.
actual_means = perclettercount
actualbars = ax.bar(ind + width, actual_means, width, color='lightblue')
# labels, title and axes ticks for the graph
ax.set_ylabel('Percentage')
ax.set_xlabel('Letter')
ax.set_title('Expected vs Actual Letter Frequency \n(Please Maximize Window)')
ax.set_xticks(ind + width / 2)
ax.set_xticklabels(('a', 'b', 'c', 'd', 'e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'))
ax.legend((expectedbars[0], actualbars[0]), ('Expected', 'Actual')) #expectedbars[0] returns colour of said bar
def label(rects): #adding a label to print the letter frequency above each graph.
for rect in rects:
plt.rcParams.update({'font.size': 6}) #updates font size to be used above each rectangle.
height = (rect.get_height())
ax.text(rect.get_x() + rect.get_width()/2.0, 1.0*height,
'%.1f' % float(height),
ha='center', va='bottom') #specifying position of text above each bar"
label(expectedbars)
label(actualbars)
graph_print ='n' #setting variable of y/n flag as "n" initially
count=0
print
while graph_print != 'y':
if count== 0:
graph_print= raw_input("display graph showing letter frequencies (y/n)?")
if count >0:
graph_print= raw_input("Input not recognized. If you want graph, enter 'y'. Otherwise, enter 'n'")
if graph_print.lower()=='y':
plt.show() #if flag is yes, graph is shown.
break
elif graph_print.lower()=='n':
print "ok, not showing graph"
break
else:
count += 1
|
86088a8771ee8bd2bb1af643d45cda87f8b912b3 | Thaileaf/TestBench | /Data Structures/Hash Tables/HashTableClass.py | 2,961 | 4.0625 | 4 | # Hash tables have a O(1) look up time
# Disadvantages are possible high memory requirement, as excess space is usually needed
# Uses key value pairs
# Similar to dictionaries in Python
class HashTable:
# Initializes an array with four spaces
def __init__(self, length=4):
self.array = [None] * length
# Hashes a key relative to the length of the array
def hash(self, key):
length = len(self.array)
return hash(key) % length
# Add method adds a key value pair to the array
def add(self, key, value):
# Gets the index through the hashing function
index = self.hash(key)
# If our array at the index has something already stored there, then we will check if
# the key is being stored. If not, add it
# This method of collision handling is called "chaining".
if self.array[index] is not None:
for pairs in self.array[index]:
if pairs[0] == key:
pairs[1] = value
break
else:
# Does not exist, adds it
self.array[index].append[key, value]
else:
# The index is empty, so we will add a new list and append the key and value to there
self.array[index] = []
self.array[index].append[key, value]
#check
if self.is_full():
self.double()
# Gets the value of the key given from the array by looping
# through index, raising a key error if the index is empty or the key cannot be found
def get(self, key):
index = self.hash(key)
if self.array[index] is not None:
for pairs in self.array[index]:
if pairs[0] == key:
return pairs[1]
else:
raise KeyError()
else:
raise KeyError()
def is_full(self):
# Determines if the array is the full by calculating the load factor
# *Need to make load factor an attribute of the class
objects = 0
for obj in self.array:
if obj is not None:
objects += len(obj)
load_factor = len(objects) / len(self.array)
# If there are more objects than half the length of the total array
if load_factor > .5:
return True
def double(self):
# Doubles the array capacity by creating a new hash table object
# and adding each of the key value pairs to the new hash table,
# then copying the array attribute back to the old hash table
ht2 = HashTable(length=len(self.array) * 2)
for index in self.array:
if index is not None:
for pair in index:
# Adds each key value pair to a hash table of different length
# Different hash codes because different length
ht2.add([pair[0], pair[1]])
self.array = ht2.array
|
82fa0a3e0d9c0d82f97ab3dcdf1b81129b512d58 | joanalexs/python_clases | /tarea_01/ejercicio2.py | 277 | 3.890625 | 4 | #Programa qu muestre la suma de dos numeros usando funciones
num1=int (input("Ingrese el primer numero"))
num2=int (input("Ingrese el segundo numero"))
def sumar(numero1, numero2):
suma= numero1 + numero2
print(f"La suma de los numeros es: {suma}")
sumar(num1, num2) |
3cdcd8cdc341777efff7754d2e8f131dd5eb4c65 | chenyao1226/learnPython | /oo/what_is_var.py | 1,005 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/5/4 10:52
# @Author : ChenYao
# @File : what_is_var.py
'''python中的对象引用
python和java中的变量本质不一样,python的变量实质上是一个指针,指针大小是固定的,无所谓类型,可以指向任何一种数据类型
'''
a = 1
a = "abc"
# 1. a贴在1上面
# 2. 先生成对象 然后贴便利贴
'''
a和b指向的是同一个对象
'''
a = [1, 2, 3]
b = a
print(id(a), id(b))
print(a is b)
# b.append(4)
# print (a)
a = [1, 2, 3, 4]
b = [1, 2, 3, 4]
'''
python 中一切皆对象,类也是对象,type方法返回的是一个类,通过is来判断是否和我们要比较的目标对象是不是同一个
'''
class People:
pass
person = People()
if type(person) is People:
print("yes")
'''
py中有一种优化机制:
两个相同值的简单数据类型对象指向的是同一个内存空间
'''
a = 1
b = 1
print(a == b)
print(id(a), id(b))
print(a is b)
|
57a281e701ea461dc1debad81d6920ed6d9abd4f | chenyao1226/learnPython | /sequence_protocol/test_sequence.py | 719 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/5/2 22:06
# @Author : ChenYao
# @File : test_sequence.py
my_list = []
my_list.append(1)
my_list.append("a")
from collections import abc
'''
abc模块中实现了序列的基类,规定序列协议应该实现哪几种方法
'''
'''拼接一个列表四种不同的方式
1. c = a + b
2. a += b
3. a.extend()
4. a.append
'''
'''
'''
a = [1,2]
c = a + [3,4]
'''这种方法其实是用魔法函数__iadd__
__iadd__方法本质上还是调用的extend方法
'''
a += (3,4)
a.extend(range(3))
a.append((1,2))
print(a)
'''
extend方法支持的参数类型是迭代器,所以+= (列表,元组,集合都是可以的)
''' |
f3055dbb503990eeb5242d4ba2dfc9a8af3b2cf0 | QQyukim/for-Algorithm-Zonzal | /nong님-온라인-코칭-테스트/BOJ-2902-KMP.py | 271 | 3.546875 | 4 | # KMP는 왜 KMP일까?
longWord = input()
abb = longWord[0]
for i in range(len(longWord)):
if (longWord[i] == '-'):
abb += longWord[i+1]
print(abb)
# 대문자나 하이픈(아스키코드)는 신경을 쓰지 않나?
# 신경 쓴 코드 만들어보기? |
a47bd4030e26f1c167df1976e97d79491f5fd489 | QQyukim/for-Algorithm-Zonzal | /PS 스터디 (with @mindflip)/프로그래머스-타겟 넘버.py | 318 | 3.546875 | 4 | # 두 개 이상 리스트의 모든 조합 구하기
from itertools import product
# 예시 입력
numbers = [1,1,1,1,1]
target = 3
# 로직
count = 0
items = [(ele, -ele) for ele in numbers]
combiList = list(product(*items))
for nTuple in combiList:
if sum(nTuple) == target:
count += 1
print(count) |
27d131704628d011c109f8200e6d5c821be57c83 | QQyukim/for-Algorithm-Zonzal | /PS 스터디 (with @mindflip)/프로그래머스-해시-L1-완주하지_못한_선수.py | 700 | 3.5625 | 4 | # def solution(participant, completion):
# for i in range(len(participant)):
# if participant[i] in completion:
# completion.remove(participant[i])
# participant[i] = ""
# for p in participant:
# if p != "":
# return p
# 유효성 검사 탈락
def solution(participant, completion):
participant.sort()
completion.sort()
for i in range(len(completion)):
if participant[i] != completion[i]:
return participant[i]
return participant[i+1]
participant = ["marina", "josipa", "nikola", "vinko", "filipa"]
completion = ["josipa", "filipa", "marina", "nikola"]
print(solution(participant, completion)) |
53c0736c0768ad4f3fba23e0c93ee51839f07540 | QQyukim/for-Algorithm-Zonzal | /BOJ/3052-나머지.py | 183 | 3.53125 | 4 | inList = []
rList = []
count = int(0)
for i in range(10):
inList.append(int(input()))
for num in inList:
rList.append(num % 42)
count += len(list(set(rList)))
print(count) |
799980b8a3f55456bdeccd40ae63d5bfaf029303 | ramvishvas/Old_Chegg_Solution | /PYTHON/Bisection.py | 886 | 3.9375 | 4 | #use python3
def f(x):
return A*(x**3) + B*(x**2) + C*x + D
def bisection(a, b, t):
if (f(a) * f(b) >= 0):
print("\nYou have not assumed right (a, b)")
return
#get midpoint value
mid = (a+b)/2.0
# excute loop till the tollerence is more than given tollerence t
while (b-a)/2.0 > t:
#check is midpoint root
if f(mid) == 0:
return mid
# a > b we know becoz its interval
# Decide the side to repeat the steps
elif f(a)*f(mid) < 0:
b = mid
else :
a = mid
mid = (a+b)/2.0
return mid
print("F(x) = Ax^3 + Bx^2 + Cx + D")
A = float(input("Enter A : "))
B = float(input("Enter B : "))
C = float(input("Enter C : "))
D = float(input("Enter D : "))
print("\nInterval : (a, b)")
a = float(input("Enter a : "))
b = float(input("Enter b : "))
t = float(input("\nEnter Tollerance : "))
print("Solution is : ",bisection(a, b, t)) |
ee142f5e64cd3d4000c67025bbda892e24641a49 | ramvishvas/Old_Chegg_Solution | /StudentList.py | 1,229 | 4.03125 | 4 | students = [("White", "Snow", 9, "F", 3.56),
("Sprat", "Jack", 12, "M", 2.0),
("Contrary", "Mary", 9, "F", 3.674),
("Dumpty", "Humpty", 11, "M", 2.342),
("Bunny", "Easter", 10, "M", 4.233),
("Wonderland", "Alice", 10, "F", 3.755),
("Bunyon", "Paul", 11, "M", 1.434),
("Penny", "Henny", 9, "F", 2.54),
("Hatter", "Mad", 11, "M", 4.522),
("Munk", "Chip", 10, "M", 3.0),
("Hood", "Red Riding", 10, "F", 3.137),
("Bunny", "Bugs", 11, "M", 2.12),
("Duck", "Daffy", 11, "M", 3.564),
("Ant", "Atom", 12, "M", 3.333),
("Mouse", "Mickey", 10, "M", 3.975),
("Brown", "Charlie", 9, "M", 1.25)]
while True:
print("""
1. School List
2. Sophomores
3. Juniors
4. Above Average Students
5. Alphabetical List
6. Highest and Lowest GPA
7. Find Student
8. Exit (Loop the menu – Extra Credit)
""")
ans=input("What would you like to do? ")
if ans=="1":
for a,b,c,d,e in students:
print(b,a,",","Grade",c)
elif ans=="2":
print("")
elif ans=="3":
print("")
elif ans=="4":
print("")
elif ans=="5":
print("")
elif ans=="6":
print("")
elif ans=="7":
print("")
elif ans=="8":
print("Goodbye")
break
else:
print(" Not Valid Choice Try again") |
e339317ef1806a17bbb65a8f9b5463d19d13324e | ramvishvas/Old_Chegg_Solution | /turtle.py | 2,498 | 4.09375 | 4 | from turtle import *
def part_one():
# asiigning value of a, b and c
a, b, c = 3, 4, 5
if a < b: #true if a if less than b
print('OK')
if c < b: #true if c is less than b
print('OK')
if a+b == c: #true if a+b is equals to c
print('OK')
if a*a + b*b == c*c: #true if a^2 + b^2 == c^2
print('OK')
def part_two():
a, b, c = 3, 4, 5
if a < b:
print('OK')
else: #this will excute if 'if' fails
print('NOT OK')
if c < b:
print('OK')
else:
print('NOT OK')
if a+b == c:
print('OK')
else:
print('NOT OK')
if a*a + b*b == c*c:
print('OK')
else:
print('NOT OK')
def print_line(color, width, length):
t = Turtle()
t.pencolor(color) #making colour of the pen same as given
t.pensize(width) #making width of the pen same as given
t.forward(length) #making a line of given length
t.ht()
def print_triangle(color, width, length):
t = Turtle()
t.pencolor(color) #making colour of the pen same as given
t.pensize(width) #making width of the pen same as given
t.forward(length) #making a line of given length
t.right(120) #turn 120 degree right
t.forward(length) #making a line of given length after turning
t.right(120) #again turn 120 degree right
t.forward(length) #making a line of given length after turning
t.ht() #hide cursor
def print_square(color, width, length):
t = Turtle()
t.pencolor(color) #making colour of the pen same as given
t.pensize(width) #making width of the pen same as given
t.forward(length) #making a line of given length
t.left(90) #turn 90 degree left
t.forward(length) # drawing line after turning
t.left(90) # agaib turn 90
t.forward(length) # again drawing line
t.left(90) # turn 90 (in the case of turning curson will be at same posotion)
t.forward(length)
t.left(90)
t.ht() #hide cursor
def start():
color = input('what color? ')
width = int(input('what line width? '))
length = int(input('what line length? '))
shape = input('line, triangle or square? ')
if shape == 'line':
print_line(color, width, length)
elif shape == 'triangle':
print_triangle(color, width, length)
elif shape == 'square':
print_square(color, width, length)
else:
print("Invalid Choice")
part_one()
print()
part_two()
# creating a screen
canvas = Screen()
canvas.setup(600,400)
start() #calling start function
canvas.exitonclick() #close screen after clicking |
f80511ba16ef82faf06740fcdf6d7c32a13f9381 | haydenmlh/csc108_lectures_practicals | /Practicals/week3/week3_activity3_booleans.py | 2,269 | 3.96875 | 4 | def marathon_time(half_marathon_time: int, is_hilly: bool) -> int:
'''Returns total marathon time given the half marathon time and whether or not the marathon is hilly
>>> marathon_time(300, True)
630
>>> marathon_time(250, False)
510
>>> marathon_time(0, True)
30
'''
if is_hilly:
return half_marathon_time * 2 + 30
else:
return half_marathon_time * 2 + 10
REGULAR_TICKET_PRICE = 3.99
STUDENT_TICKET_PRICE = 2.99
def total_ticket_price(number_regular_tickets: int, number_student_tickets: int, is_holiday: bool) -> float:
'''Returns total price for a given number of regular and student tickets and whether or not it is a holiday
>>> total_ticket_price(1, 1, True)
6.98
>>> total_ticket_price(4, 6, True)
32.205000000000005
>>> total_ticket_price(4, 6, False)
30.510000000000005
'''
if (number_regular_tickets + number_student_tickets >= 10):
if is_holiday:
return (number_regular_tickets * REGULAR_TICKET_PRICE + number_student_tickets * STUDENT_TICKET_PRICE) * 0.95
else:
return (number_regular_tickets * REGULAR_TICKET_PRICE + number_student_tickets * STUDENT_TICKET_PRICE) * 0.9
else:
return number_regular_tickets * REGULAR_TICKET_PRICE + number_student_tickets * STUDENT_TICKET_PRICE
def british_time(toronto_time: float, toronto_dst: bool, london_dst: bool) -> float:
'''Return the British time given the time in toronto and whether or not toronto has dst and london has dst
>>> british_time(0.0, True, True)
6.0
>>> british_time(12.0, True, False)
17.0
>>> british_time(12.0, False, True)
19.0
>>> british_time(12.0, False, False)
18.0
>>> british_time(23.0, False, False)
5.0
'''
if toronto_dst and london_dst:
british_time = toronto_time + 6
elif toronto_dst and not london_dst:
british_time = toronto_time + 5
elif not toronto_dst and london_dst:
british_time = toronto_time + 7
else:
british_time = toronto_time + 6
# if british_time > 24:
# british_time = british_time - 24
# return british_time
return british_time % 24
if __name__ == '__main__':
import doctest
doctest.testmod() |
4d39f5b89d8e925691e4e88d22be1c324808787b | haydenmlh/csc108_lectures_practicals | /Practicals/lab6/files.py | 4,162 | 4.28125 | 4 | import urllib.request
from typing import List, TextIO
# Precondition for all functions in this module: Each line of the url
# file contains the average monthly temperatures for a year (separated
# by spaces) starting with January. The file must also have 3 header
# lines.
DATA_URL = 'http://robjhyndman.com/tsdldata/data/cryer2.dat'
def open_temperature_file(url: str) -> TextIO:
'''Open the specified url, read past the three-line header, and
return the open file.
'''
file = urllib.request.urlopen(url)
for _ in range(3):
file.readline()
return file
def avg_temp_march(f: TextIO) -> float:
'''Return the average temperature for the month of March
over all years in f.
'''
# We are providing the code for this function
# to illustrate one important difference between reading from a URL
# and reading from a regular file. When reading from a URL,
# we must first convert the line to a string.
# the str(line, 'ascii') conversion is not used on regular files.
march_temps = []
# read each line of the file and store the values
# as floats in a list
for line in f:
line = str(line, 'ascii') # now line is a string
temps = line.split()
# there are some blank lines at the end of the temperature data
# If we try to access temps[2] on a blank line,
# we would get an error because the list would have no elements.
# So, check that it is not empty.
if temps != []:
march_temps.append(float(temps[2]))
# calculate the average and return it
return sum(march_temps) / len(march_temps)
def avg_temp(f: TextIO, month: int) -> float:
'''Return the average temperature for a month over all years
in f. month is an integer between 0 and 11, representing
January to December, respectively.
'''
month_temps = []
for line in f:
line = str(line, 'ascii')
temps = line.split()
# there are some blank lines at the end of the temperature data
# If we try to access temps[2] on a blank line,
# we would get an error because the list would have no elements.
# So, check that it is not empty.
if temps != []:
month_temps.append(float(temps[month]))
# calculate the average and return it
return sum(month_temps) / len(month_temps)
def higher_avg_temp(url: str, month1: int, month2: int) -> int:
'''Return either month1 or month2 (integers representing months in
the range 0 to 11), whichever has the higher average temperature
over all years in the webpage at the given URL. If the months have
the same average temperature, then return -1.
'''
f = open_temperature_file(url)
if avg_temp(f, month1) > avg_temp(f, month2):
return avg_temp(f, month1)
elif avg_temp(f, month1) < avg_temp(f, month2):
return avg_temp(f, month2)
else:
return -1
def three_highest_temps(f: TextIO) -> List[float]:
'''Return the three highest temperatures, in descending order,
over all months and years in f.
'''
max_1 = 0
max_2 = 0
max_3 = 0
for i in f:
i = str(i, 'ascii')
temps = i.split()
if temps != []:
for j in temps:
if float(j) > max_3:
max_3 = float(j)
if max_3 > max_2:
foo = max_2
max_2 = max_3
max_3 = foo
if max_2 > max_1:
foo = max_1
max_1 = max_2
max_2 = foo
return [max_1, max_2, max_3]
def below_freezing(f: TextIO) -> List[float]:
'''Return, in ascending order, all temperatures below freezing
(32 degrees Fahrenheit), for all temperature data in f. Include
any duplicates that occur.
'''
below = []
for i in f:
i = str(i, 'ascii')
temps = i.split()
if temps != []:
for j in temps:
if float(j) < 32:
below.append(float(j))
below.sort()
return below
|
fd2d918c5826af8e3a4c0e292995f6082bfba677 | alexpearce/Condorcet | /Condorcet/elections.py | 5,052 | 3.6875 | 4 | #!/usr/bin/env python
"""
preferences is a list of string e.g. ['abc','cab',...]
'cab' is a preference: candidate 'c' is the favoirite, followed by 'a' and 'b' is last
"""
def getScore(preferences, candidates):
"""
Get Score using Borda method, not useful for LHCb method but useful crosscheck
"""
num_candidates = len(candidates)
score = {}
for cand in candidates:
score[cand] = 0
for pref in preferences:
for i, cand in enumerate(pref):
score[cand] += num_candidates-1-i
return score
def getCondorcetWinner(preferences, candidates):
"""
Get winner with Borda Method, may give more than one winner in case of circles
"""
score = getScore(preferences, candidates)
return [key for key in score if score[key] == max(score.values())]
def getLoosers(preferences, candidates):
"""
Get looser with LHCb algorithm, the one placed as last by the majority. In case of tie keep the one most voted as a first, in case of tie, second ...
"""
num_candidates = len(candidates)
num_preferences = {}
for cand in candidates:
num_preferences[cand] = [0]*num_candidates
for pref in preferences:
for i, cand in enumerate(pref):
num_preferences[cand][i] += 1
# print num_preferences
preferences_loosers = dict((key, value) for key, value in num_preferences.items() if num_preferences[key][-1] == max([list_pref[-1] for list_pref in num_preferences.values()]))
# print preferences_loosers
for i in range(num_candidates-1):
if len(preferences_loosers) == 1: break
preferences_loosers = dict((key, value) for key, value in preferences_loosers.items() if preferences_loosers[key][i] == min([list_pref[i] for list_pref in preferences_loosers.values()]))
# print preferences_loosers
return preferences_loosers.keys()
def deleteCandidate(cand, preferences):
"""
From preferences, the list of strings containing the order of preferences of the electors, remove candidate cand
"""
newpref = []
for pref in preferences:
newpref.append(pref.replace(cand,''))
return newpref
def getWinner(preferences,candidates):
"""
get Winner with LHCb method
"""
candidates_copy = candidates[:]
# print 'Beginning'
# print 'candidates:', candidates
# print 'preferences:', preferences
for i in xrange(1,len(candidates)):
# print 'Iteration', i
loosers = getLoosers(preferences, candidates_copy)
if len(loosers) < len(candidates_copy):
for looser in loosers:
candidates_copy.remove(looser)
preferences = deleteCandidate(looser,preferences)
# print 'candidates:', candidates
# print 'preferences:', preferences
return candidates_copy
import random
def inventPreferences(candidates,num_preferences):
preferences = []
candidates_copy = candidates[:]
for i in xrange(num_preferences):
random.shuffle(candidates_copy)
preferences.append(''.join(candidates_copy))
return preferences
if __name__ == '__main__':
# candidates = ['a', 'b', 'c', 'd']#, 'e', 'f']
# preferences = ['adbc', 'adcb','dbac', 'adcb']
candidates = ['a', 'b', 'c']
# preferences = ['bca', 'bac', 'cba', 'bac', 'cab', 'cab', 'abc', 'abc', 'acb', 'bac']
# preferences = ['abc', 'bca','cab']
preferences = 20*['bca']+19*['abc']+19*['cab']+16*['bac']+13*['acb']+13*['cba']
# preferences = inventPreferences(candidates,10000)
# print preferences
score = getScore(preferences, candidates)
print score
print 'Condorcet winners: ',getCondorcetWinner(preferences, candidates)
print 'LHCb winners: ', getWinner(preferences, candidates)
candidates = ['a', 'b', 'c']
converge_C = 0
converge_L = 0
isEqual = 0
isDiff = 0
CL = 0
LC = 0
LLCC = 0
diffWinner = 0
interesting = []
for i in range(100):
preferences = inventPreferences(candidates,1000)
interesting.append(preferences)
condorcet = sorted(getCondorcetWinner(preferences, candidates))
LHCb = sorted(getWinner(preferences, candidates))
print i,condorcet, LHCb
if len(condorcet) == 1: converge_C += 1
if len(LHCb) == 1: converge_L += 1
if condorcet == LHCb:
isEqual +=1
else:
isDiff += 1
if len(condorcet) > len(LHCb):
CL += 1
elif len(condorcet) < len(LHCb):
LC +=1
else:
if len(LHCb) == 1: diffWinner += 1
LLCC += 1
print 'Condorcet converges: ', converge_C
print 'LHCb converges: ', converge_L
print 'Converge with different Results: ', diffWinner
print 'Same result: ', isEqual
print 'Different result: ', isDiff
print 'Condorcet > LHCb: ', CL
print 'Condorcet < LHCb: ', LC
print 'Condorcet = LHCb: ', LLCC
|
b652cfd77021b9f618cffafa687b400c11499fb7 | Sultanggg/codeabbey | /q36.py | 544 | 3.578125 | 4 | counter = 1
myarray =[]
for i in range(1,37):
myarray.append(i)
def josephus(arr,n,c=10):
global counter
for k in range(0,n):
if counter%c == 0:
arr[k]='x'
counter = counter + 1
return arr
def newarray(alist):
emptylist = []
for i in range(0,len(alist)):
if alist[i] != 'x':
emptylist.append(alist[i])
else:
continue
return emptylist
while(len(myarray) != 1):
x=josephus(myarray,len(myarray))
y = newarray(x)
myarray = y
print(y[0])
|
bc6f0d1baf6126210a5946088e4d148300bf67df | danny-moncada/nyusps_intro_python2.7 | /lesson_4/ex4.14.py | 247 | 3.8125 | 4 | #usr/bin/env python
new_set = set()
sentence = "I could; I wouldn't. I might? Might I!"
split_sentence = sentence.split()
for word in split_sentence:
new_word = word.rstrip('.!?;')
lower = new_word.lower()
new_set.add(lower)
print new_set |
8662b0f1cb802e9fb05399798e43456040b0489a | danny-moncada/nyusps_intro_python2.7 | /lesson_5/hw5.2.py | 1,196 | 4.0625 | 4 | #!/usr/bin/env python
"""
hw5.2.py -- create a dictonary that sums all Mkt-RF values per year
author: Danny Moncada
"""
mydict = {}
farma_french = open('../../python_data/F-F_Research_Data_Factors_daily.txt').readlines()[5:-2]
for line in farma_french:
line = line.split()
year = line[0][0:4]
mkt_rf = float(line[1])
if year not in mydict:
mydict[year] = 0.0
mydict[year] += mkt_rf
max_value = len(mydict)
while True:
results = raw_input('please enter number of results desired: ')
direction = raw_input('select "highest" or "lowest" results: ')
if results.isalpha():
print 'number results must be all digits'
print
continue
if direction not in ['highest', 'lowest']:
print 'top or bottom results must be "highest" or "lowest"'
continue
results = int(results)
if results > max_value:
print 'number results "{}" is greater than max "{}"'.format(results, max_value)
continue
break
if direction == 'highest':
rev = True
else:
rev = False
for key in sorted(mydict, key = mydict.get, reverse = rev)[0:results]:
print '{}: {}'.format(key, mydict[key])
exit() |
fd1fd31c510ec991298f5d84c1f4eef3583e9f3e | danny-moncada/nyusps_intro_python2.7 | /lesson_10/ex10.py | 415 | 3.53125 | 4 | #!usr/bin/env python
class Sum(object):
def add(self, val):
if not hasattr(self, 'x'):
self.x = 0
self.x = self.x + val
myobj = Sum()
myobj.add(5)
myobj.add(20)
print myobj.x
exit()
from datetime import date, timedelta
dt = date(1926, 12, 30)
td = timedelta(days = 3)
dt = dt + timedelta(days = 3)
print dt
dt2 = date.today()
dt2 = dt2 + timedelta(days = 1)
print dt2
print type(dt)
print type(td) |
89c8a5f620b40adb47f4d4399e79c9c0c6ea8e94 | danny-moncada/nyusps_intro_python2.7 | /lesson_9/ex9.7.py | 249 | 3.59375 | 4 | #!usr/bin/env python
def getlines(filename):
lines = open(filename).readlines()
return lines
lines = getlines('/Users/dmoncada/Documents/Introduction to Python Programming_NYU/python_data/revenue.txt')
for line in lines:
print line.rstrip()
|
4785dc0bc488f0e0a0df22222f5ac3707a8aca91 | danny-moncada/nyusps_intro_python2.7 | /lesson_6/ex6.1.py | 120 | 3.5 | 4 | #!/usr/bin/env python
numlist = [1, 13, 23, 3, 9, 16]
sorted_list = sorted(numlist, reverse = True)
print sorted_list |
ab35ea8ae198e9614f03ef9f5b4a1aad861d5ab7 | danny-moncada/nyusps_intro_python2.7 | /lesson_9/ex9.2.py | 159 | 3.90625 | 4 | #!usr/bin/env python
def printupper(string):
print string.upper()
printupper('hello')
printupper('my you are loud')
printupper('I am not lout. You are.')
|
dc0c7007fe3b1dfc77835d92ff3f8d7069827f96 | danny-moncada/nyusps_intro_python2.7 | /lesson_8/ex8.6.py | 503 | 3.796875 | 4 | #!usr/bin/env python
import os
import sys
user_input = raw_input('please enter a directory: ')
try:
test_dir = user_input
for file in os.listdir(test_dir):
full_path = os.path.join(test_dir, file)
size = os.path.getsize(full_path)
if os.path.isfile(full_path):
print '{} (file): {}'.format(file, size)
elif os.path.isdir(full_path):
print '{} (dir): {}'.format(file, size)
except IndexError:
exit('you must provide a file path')
except OSError:
exit('file path does not exist') |
ca5fa437808e1935217bc2230a062cdd1a28e7d3 | nilasissen/python-rookie | /india.py | 607 | 4.28125 | 4 | #!/usr/local/bin/python
print 'Legal age in INDIA'
driving_age=16
voting_age=18
smoking_age=19
marriage_age=21
age = int(raw_input('enter your age :) '))
def get_age(age):
"""this program will teach you about the if and else and elif statements """
if age >= marriage_age:
print 'you can get marriad,smoke,vote,and drive '
elif age >= smoking_age:
print 'you cant smoke,vote,drive '
elif age >= voting_age:
print 'you can only vote and driving '
elif age >= drive_age:
print 'you can driving '
else:
print 'you cant even vote'
|
3679e5d2092233de7fa650710660c67855774919 | mission-systems-pty-ltd/comma | /python/comma/dictionary/util.py | 5,053 | 3.71875 | 4 | '''
operations on dict and dict-like objects with string keys
made for convenience, not for performance
'''
import copy, functools, typing
def at( d, path, delimiter = '/', no_throw = False, full = False ): # todo: default=...
'''
return value at a given path in a dictionary
params
------
d: dictionary
path: path in dictionary, e.g 'a/b/c/d'
delimiter: path delimiter
no_throw: if path not found, return None instead of throwing exception
full: output dictionary, not just the key value, see example below
examples
--------
>>> d = { "a": { "b": { "c": 5, "d": 6 } }, "e": [ 7, [ 8, 9, 10 ] ] }
>>> comma.dictionary.at( d, "a/b/c" )
5
>>> comma.dictionary.at( d, "a/b/c", full = True )
{ "a": { "b": { "c": 5 } } }
>>> comma.dictionary.at( d, 'e[0]' )
7
>>> comma.dictionary.at( d, 'e[1]' )
[ 8, 9, 10 ]
>>> comma.dictionary.at( d, 'e[2][1]' )
10
>>> comma.dictionary.at( d, 'e[1][1:]' )
[ 9, 10 ]
>>> e = [1, 2, {'a': 3} ]
>>> comma.dictionary.at( e, '[2]/a' )
3
'''
s = path.split( delimiter )
def _value( d, k ):
if not k:
if no_throw: return None
raise ValueError( f'"{path}" has an empty element; remove initial, trailing, or duplicated delimiters' )
n = k.split( '[', 1 )
if len( n ) == 1: return None if no_throw and ( not isinstance( d, dict ) or not k in d ) else d[k]
if full:
if no_throw: return None
raise KeyError( f'on path "{path}": full=True not supported for array indices, since it cannot be done consistently' )
if no_throw:
try: return eval( f'd[{n[1]}' if n[0] == '' else f'd[n[0]][{n[1]}', { 'd': d, 'n': n } )
except: return None
return eval( f'd[{n[1]}' if n[0] == '' else f'd[n[0]][{n[1]}', {'d': d, 'n': n} )
r = functools.reduce( lambda d, k: _value( d, k ), s, d )
return None if r is None else functools.reduce( lambda d, k: { k: d }, [ r ] + s[::-1] ) if full else r
def has( d, path, delimiter = '/' ):
'''
return true if element at a given dictionary path exists
todo: support list indices
examples
--------
>>> d = { "a": { "b": { "c": 1, "d": 2, "e": [ 3, 4, { "f": 5 } ] } } }
>>> comma.dictionary.has( d, "a/b/c" )
True
>>> comma.dictionary.has( d, [ "a", "b", "c" ] )
True
>>> comma.dictionary.has( d, [ "a", "b", "x" ] )
False
'''
p = path.split( delimiter ) if isinstance( path, str ) else path
return functools.reduce( lambda d, k: ( d[k[1]] if k[0] + 1 < len( p ) else True ) if isinstance( d, dict ) and k[1] in d else False, enumerate( p ), d )
def set( d, path, value, delimiter = '/' ):
'''
assign value to a nested dictionary/list element
examples
--------
>>> d = { "a": { "b": 1, "c": [ 2, 3 ], "d": { "e": 4 } } }
>>> comma.dictionary.set( d, 'a/b/c[1]', 5 )
todo
'''
def _set( d, p ):
s = p[0].split( '[', 1 )
if len( p ) == 1:
if len( s ) == 1: d[p[0]] = value
else: exec( f'd[{s[1]} = value' if s[0] == '' else f'd["{s[0]}"][{s[1]} = value', { 'd': d, 'value': value } )
else:
if len( s ) == 1:
if not p[0] in d: d[p[0]] = {}
_set( d[p[0]], p[ 1: ] )
else:
if ( len( s ) == 1 or s[0] != '' ) and not s[0] in d: raise KeyError( f'on path {path}: {s[0]} not found' )
_set( eval( f'd[{s[1]}' if s[0] == '' else f'd["{s[0]}"][{s[1]}', { 'd': d } ), p[1:])
_set( d, path.split( delimiter ) )
return d
def leaves( d, path=None ):
'''
generator of the leaf items of a nested dictionary or list, yields path-value pairs
example
-------
>>> list( comma.dictionary.leaves( { "x": { "y": [ { "z": 0 }, {"w": 2 } ], "v": "hello" } } ) )
[('x/y[0]/z', 0), ('x/y[1]/w', 2), ('x/v', 'hello')]
'''
if path is None: path = ''
if isinstance( d, dict ):
for key, value in d.items(): yield from leaves( value, f'{path}/{key}' )
elif isinstance( d, list ):
for i, value in enumerate(d): yield from leaves( value, f'{path}[{i}]' )
else:
yield path[1:] if path and path[0] == '/' else path, d
def parents( d, path, parent_field_name=None, root=None ):
'''
generator of parents of a given path
todo: usage semantics and examples
todo: unit test
'''
if root is None: root = ''
if parent_field_name is None or not has( d, f'{path}/{parent_field_name}' ):
p = os.path.dirname( path )
if p == root: yield p
else: yield from parents( d, p )
else:
p = at( d, f'{path}/{parent_field_name}' )
if p == '': yield p
else: yield from parents( d, f'{root}{p}' if p[0] == '/' else f'{os.path.dirname( path )}/{p}', parent_field_name, root ) |
be0f059ba551ea53b2eff35cee8d6a7cd2d5957f | codezoners-2/AgileDevelopment | /01_basic_testing/presentation/include/edge-cases.py | 148 | 3.828125 | 4 | def average(list):
"""
>>> average([1, 2, 3])
2
"""
total = 0
for i in list: total = total + i
return total / len(list)
|
1496c17e367409805481ebc32afc64d50f5449ce | JIAWea/Python_cookbook_note | /07skipping_first_part_of_an_iterable.py | 1,321 | 4.15625 | 4 | # Python cookbook学习笔记
# 4.8. Skipping the First Part of an Iterable
# You want to iterate over items in an iterable, but the first few items aren’t of interest and
# you just want to discard them.
# 假如你在读取一个开始部分是几行注释的源文件。所有你想直接跳过前几行的注释
from itertools import dropwhile
with open('/etc/passwd') as f:
for line in dropwhile(lambda line: line.startswith('#'), f):
print(line, end='')
# 迭代器和生成器是不能使用标准的切片操作的,因为它们的长度事先我们并不知道 (并且也没有实现索引)。
# 函数 islice() 返回一个可以生成指定元素的迭代器,它通过遍历并丢弃直到切片开始索引位置的所有元素。
# 然后才开始一个个的返回元素,并直到切片结束索引位置。
from itertools import islice
items = ['a', 'b', 'c', 1, 6, 8, 10]
for x in islice(items, 3, None)
print(x)
# 1
# 6
# 8
# 10
# 4.12 不同集合上元素的迭代
# itertools.chain() 方法可以用来简化这个任务。它接受一个可迭代对象列表作为输入,并返回一个迭代器
from itertools import chain
a = [1, 2, 3, 4]
b = ['x', 'y', 'z']
for x in chain(a, b):
print(x)
# 1
# 2
# 3
# 4
# x
# y
# z
|
ce83346829246a0c7896a2b25855b435c2f3ca0b | JIAWea/Python_cookbook_note | /09yield_and_yield_from-2.py | 2,082 | 3.71875 | 4 | # yield 除了能生成一个生成器的作用,还能用在协程当中,当我们遇到了阻塞,如 IO 阻塞时,可以调配线程去做别的事情
# 下面有一段伪代码,如:
"""
def test():
request_google_server(data)
yield
print(data)
"""
# 去请求百度需要走很长的网络线路,三路握手,数据传递。这在 cpu 的感官里这就是等待数年的操作。我们的程序无法继续运行,
# 难道我们就这样让 cpu 等待?当然不所以调用 yield 把线程的控制权交出来,然后我们让线程去做一些其他的事情,比如再入
# 请求新浪服务器等等,一瞬间我们同时请求了 N 台服务器了。
# 稍微总结一下 yield,通过其可以让我们程序员实现对线程的调配,从而更加充分的利用 cpu。
# 通常一个函数都是 a 调用 b, b 调用 c, c 调用 a。这样才会增加代码的可读性,复用性。
# 假如 b() 调用 c(), c()中存在 yield 时我们应该如何处理呢?
def b():
gen = c()
r = gen.send(None) # send(None) 相当于 next()
print(r) # 1
r = gen.send(None)
print(r) # 2
def c():
yield 1
yield 2
yield 3
# 鉴于生成器中调用生成器比较麻烦,所有有了 yield from 语法。用于简化嵌套调用生成器的语法复杂度,如:
def b2():
r = yield from c2()
print("r of b2:", r) # 4 (c2的return值)
def c2():
r = yield 1
print("r of c2:", r) # r of b2: 哈哈
return 4
if __name__ == '__main__':
# b()
try:
gen = b2()
# 第一次 send 返回的是 1,b2()到了 yield from 后,控制权就到了我们这里,所以返回了c2()中的 yield 1
gen.send(None)
# 第二次 send 值在上次 停留在 c2() 停留的 yield 开始往下执行,把 “哈哈” 作为 yield 的返回值
gen.send("哈哈")
except StopIteration:
print("Stop")
|
d5fc7d0c23127c4e7c052866a658499c71ba18a4 | chanbi-raining/algorithm-study | /0512_stackandqueue.py | 6,677 | 4.125 | 4 | # 알고리즘 시즌 2
'''
- date: 2019-05-12
- participants: @yoonjoo-pil, @cjttkfkd3941
- chapters: Stack and Queue
'''
# implementing stack in python
class StackNode():
def __init__(self, data, nextt=None):
self.data = data
self.next = nextt
class Stack():
def __init__(self):
self.size = 0
self.top = None
def isEmpty(self):
return bool(self.size == 0)
def push(self, data):
self.size += 1
if self.top:
self.top = StackNode(data, self.top)
else:
self.top = StackNode(data)
def pop(self):
if self.top:
self.size -= 1
temp = self.top.data
self.top = self.top.next
return temp
else:
print('\tthe stack is empty')
def peek(self):
if self.isEmpty():a
print('\tthe stack is empty')
return
return self.top.data
def __str__(self):
if not self.top:
print('\tthe stack is empty')
return
cursor = self.top
string = str(cursor.data)
cursor = cursor.next
while cursor:
string += '->' + str(cursor.data)
cursor = cursor.next
return string
# implementing queue in python
class QueueNode():
def __init__(self, data, nextt=None):
self.data = data
self.next = nextt
class Queue():
def __init__(self):
self.first = None
self.last = None
def add(self, data):
if self.first:
self.last.next = QueueNode(data)
self.last = self.last.next
else:
self.first = self.last = QueueNode(data)
def remove(self):
if self.first:
temp = self.first.data
self.first = self.first.next
return temp
print('\tthe queue is empty')
return
def peek(self):
if self.first:
return self.first.data
print('\tthe queue is empty')
return
def isEmpty(self):
return bool(self.first)
# 3.2
class Stack32(Stack):
def __init__(self):
Stack.__init__(self)
self.minn = Stack()
def push(self, data):
self.size += 1
if self.top:
self.top = StackNode(data, self.top)
if self.minn.peek() > data:
self.minn.push(data)
else:
self.top = StackNode(data)
self.minn.push(data)
def pop(self):
if self.top:
self.size -= 1
temp = self.top.data
self.top = self.top.next
if self.minn.peek() == temp:
self.minn.pop()
return temp
else:
print('\tthe stack is empty')
def min(self):
if self.minn:
return self.minn.peek()
print('\tthe stack is empty')
return
# 3.3
class Stack33(Stack):
def __init__(self, nextStack=None):
Stack.__init__(self)
self.nextStack = nextStack
class SetOfStacks():
def __init__(self, sizelimit=10):
self.sizelimit = sizelimit
self.top = None
def push(self, data):
if not self.top:
self.top = Stack33()
elif self.top.size >= self.sizelimit:
self.top = Stack33(self.top)
self.top.push(data)
def pop(self):
if not self.top:
print('No node')
return
temp = self.top.pop()
if self.top.size == 0:
self.top = self.top.nextStack
return temp
def __str__(self):
if not self.top:
print('No node')
return
cursor1 = self.top
string = ''
while cursor1:
cursor2 = cursor1.top
while cursor2:
string += '->' + str(cursor2.data)
cursor2 = cursor2.next
string += ' // '
cursor1 = cursor1.nextStack
return string
# 3.4
class MyQueue():
def __init__(self):
self.origin = Stack()
self.temp = Stack()
def add(self, data):
self.origin.push(data)
def remove(self):
while not self.origin.isEmpty():
self.temp.push(self.origin.pop())
temp = self.temp.pop()
while not self.temp.isEmpty():
self.origin.push(self.temp.pop())
return temp
def peek(self):
while not self.origin.isEmpty():
self.temp.push(self.origin.pop())
temp = self.temp.pop()
self.origin.push(temp)
while not self.temp.isEmpty():
self.origin.push(self.temp.pop())
return temp
def isEmpty(self):
return self.origin.isEmpty()
def sortStack(example):
tempstack = Stack()
tempstack.push(example.pop())
while not example.isEmpty():
if tempstack.peek() < example.peek():
tempstack.push(example.pop())
else:
temp = example.pop()
while not tempstack.isEmpty():
example.push(tempstack.pop())
tempstack.push(temp)
while not tempstack.isEmpty():
example.push(tempstack.pop())
return example
class AnimalNode():
def __init__(self, name, order, nextt=None):
self.data = name
self.next = nextt
self.order = order
class AnimalQueue(Queue):
def __init__(self):
Queue.__init__(self)
def add(self, data, order):
if self.first:
self.last.next = AnimalNode(data, order)
self.last = self.last.next
else:
self.first = self.last = AnimalNode(data, order)
def timestamp(self):
return self.first.order
class AnimalShelter():
def __init__(self):
self.cats = AnimalQueue()
self.dogs = AnimalQueue()
self.order = 0
def enqueue(self, name, species):
if species == 'cat':
self.cats.add(name, self.order)
else:
self.dogs.add(name, self.order)
self.order += 1
def dequeueAny(self):
if self.cats and self.dogs:
if self.cats.timestamp() > self.dogs.timestamp():
return self.dogs.remove()
return self.cats.remove()
if self.cats:
return self.cats.remove()
if self.dogs:
return self.dogs.remove()
return 'No animals left'
def dequeueDog(self):
return self.dogs.remove()
def dequeueCat(self):
return self.cats.remove()
|
1ff8c1d0e4d2c8ff72a72b36daece2ed1ee97d3c | hejia-zhang/welcome_assignments_sols | /rrt/env.py | 1,338 | 4.03125 | 4 | import matplotlib.pyplot as plt
import numpy as np
from rrt.robot import Robot, Obstacle
class World(object):
def __init__(self, w=400):
self.w = w # a world is a square with this width
self.world_map = np.zeros(shape=(self.w, self.w)) # this is used to just visualize, think it as a white board.
self.obs_lst = []
self.robot_lst = []
def visualize(self):
"""With this function we can print the world with all obstacles and the robot if there is any."""
# student implements it.
self.world_map = np.zeros(shape=(self.w, self.w))
for obs in self.obs_lst:
obs.draw(self.world_map)
# robot should be drawn after the obstacles,
# so we can always see it.
for robot in self.robot_lst:
robot.draw(self.world_map)
plt.matshow(self.world_map)
plt.show()
def add_obs(self, obs):
self.obs_lst.append(obs)
def add_robot(self, robot):
self.robot_lst.append(robot)
if __name__ == '__main__':
world = World()
obs0 = Obstacle((200, 200))
world.add_obs(obs0)
obs1 = Obstacle((65, 340))
world.add_obs(obs1)
obs2 = Obstacle((340, 65))
world.add_obs(obs2)
robot0 = Robot((100, 100))
world.add_robot(robot0)
world.visualize()
world.visualize()
|
c1b83c2ac9d096558fa7188d269cc55f2a25ecf1 | tolu1111/Python-Challenge | /PyBank.py | 2,088 | 4.1875 | 4 | #Import Dependencies perform certain functions in python
import os
import csv
# define where the data is located
bankcsv = os.path.join("Resources", "budget_data.csv")
# define empty lists for Date, profit/loss and profit and loss changes
Profit_loss = []
Date = []
PL_Change = []
# Read csv file
with open(bankcsv, newline= '') as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csvheader = next(csvreader)
# calculate the values for the profit/loss and the dates
# store respective values in appropraite lists created earlier
for row in csvreader:
Profit_loss.append(float(row[1]))
Date.append(row[0])
#Print the calculated values
print("Financial Analysis")
print("-----------------------------------")
print(f"Total Months: {len(Date)}")
print(f"Total Revenue: {sum(Profit_loss)}")
#Calculate the average revenue change, the greatest revenue increase and the greatest revenue decrease
for i in range(1,len(Profit_loss)):
PL_Change.append(Profit_loss[i] - Profit_loss[i-1])
avg_PL_Change = (sum(PL_Change)/len(PL_Change))
max_PL_Change = max(PL_Change)
min_PL_Change = min(PL_Change)
max_PL_Change_date = str(Date[PL_Change.index(max(PL_Change)) + 1])
min_PL_Change_date = str(Date[PL_Change.index(min(PL_Change)) + 1])
# print the calculated values
print(f"Avereage Revenue Change: {round(avg_PL_Change,2)}")
print(f"Greatest Increase in Revenue: {max_PL_Change_date}, {max_PL_Change}")
print(f"Greatest Decrease in Revenue: {min_PL_Change_date}, {min_PL_Change}")
#export text file
p = open("PyBank.txt","w+")
p.write("Financial Analysis\n")
p.write("-----------------------------------\n")
p.write(f"Total Months: {len(Date)}\n")
p.write(f"Total Revenue: {sum(Profit_loss)}\n")
p.write(f"Avereage Revenue Change: {round(avg_PL_Change,2)}\n")
p.write(f"Greatest Increase in Revenue: {max_PL_Change_date}, {max_PL_Change}\n")
p.write(f"Greatest Decrease in Revenue: {min_PL_Change_date}, {min_PL_Change}\n")
p.close()
|
3586071535e42f3431e3ddbacc7d6c80c8ba5497 | AlanSoldar/Artifitial-Intelligence | /8Puzzle/Sucessor.py | 1,262 | 3.546875 | 4 | import sys
def sucessor():
puzzle = str(sys.argv[1])
emptyPos = puzzle.find('_')
print(getLeft(puzzle, emptyPos), getDown(puzzle, emptyPos), getRight(puzzle, emptyPos), getUp(puzzle, emptyPos))
def getRight(puzzle, emptyPos):
if(emptyPos!=2 and emptyPos!=5 and emptyPos!=8):
newState = puzzle[:emptyPos] + puzzle[emptyPos+1] + '_' + puzzle[emptyPos+2:]
return '(direita,“' + newState + '”)'
else:
return ''
def getLeft(puzzle, emptyPos):
if(emptyPos!=0 and emptyPos!=3 and emptyPos!=6):
newState = puzzle[:emptyPos-1] + '_' + puzzle[emptyPos-1] + puzzle[emptyPos+1:]
return '(esquerda,“' + newState + '”)'
else:
return ''
def getUp(puzzle, emptyPos):
if(emptyPos-3 >= 0):
newState = puzzle[:emptyPos-3] + '_' + puzzle[emptyPos-2:emptyPos] + puzzle[emptyPos-3] + puzzle[emptyPos+1:]
return '(acima,“' + newState + '”)'
else:
return ''
def getDown(puzzle, emptyPos):
if(emptyPos+3 <= 8):
newState = puzzle[:emptyPos] + puzzle[emptyPos+3] + puzzle[emptyPos+1:emptyPos+3] + '_' + puzzle[emptyPos+4:]
return '(abaixo,“' + newState + '”)'
else:
return ''
if __name__ == '__main__':
sucessor() |
78f8062aa223caa2d4a340b8b4719deb99d4a314 | AlanSoldar/Artifitial-Intelligence | /8Puzzle/avalia_dfs.py | 3,670 | 3.515625 | 4 | import sys
DIREITA = 'direita'
ESQUERDA = 'esquerda'
ACIMA = 'acima'
ABAIXO = 'abaixo'
EMPTY_SPACE = '0'
FINAL_STATE = '123456780'
class Node:
def __init__(self, previous, direction, cost, current):
self.previous = previous
self.direction = direction
self.cost = cost
self.current = current
def existInList(self, nodeList):
if(nodeList.get(int(self.current)) is None):
return False
else:
return True
def toString(self):
return '(' + self.direction + ',' + self.current+',' + str(self.cost) + ',' + self.previous + ')'
def dfs():
inPuzzle = str(sys.argv[1]).replace('_', '0')
puzzle = Node(inPuzzle, 'start', 0, inPuzzle)
frontier = []
expandedList = {}
while(puzzle.current != FINAL_STATE):
expandedList[int(puzzle.current)] = puzzle
frontier = addOnFrontier(frontier, expandedList, expande(puzzle.current, puzzle.cost))
if not frontier:
return
puzzle = frontier.pop()
traceTree(expandedList, puzzle)
def addOnFrontier(frontier, expandedList, nodeList):
for node in nodeList:
if not node in frontier and not node.existInList(expandedList):
frontier.append(node)
return frontier
def expande(currentState, currentCost):
emptyPos = currentState.find(EMPTY_SPACE)
nodeList = getNodeList(getLeft(currentState, emptyPos, currentCost),
getDown(currentState, emptyPos, currentCost),
getRight(currentState, emptyPos, currentCost),
getUp(currentState, emptyPos, currentCost))
return nodeList
def traceTree(expandedList, finalNode):
successPath = []
currentNode = finalNode
while currentNode.cost != 0:
successPath.append(currentNode)
currentNode = expandedList.get(int(currentNode.previous))
# print('currentNode: ', currentNode.current)
successPath.append(currentNode)
successPath.reverse()
successPath.pop(0)
for node in successPath:
print(node.direction, end=' ')
def getNodeList(left, down, right, up):
nodeList = []
if left is not None:
nodeList.append(left)
if down is not None:
nodeList.append(down)
if right is not None:
nodeList.append(right)
if up is not None:
nodeList.append(up)
return nodeList
def getRight(puzzle, emptyPos, cost):
if(emptyPos != 2 and emptyPos != 5 and emptyPos != 8):
newState = puzzle[:emptyPos] + puzzle[emptyPos+1] + \
EMPTY_SPACE + puzzle[emptyPos+2:]
return Node(puzzle, DIREITA, cost+1, newState)
else:
return None
def getLeft(puzzle, emptyPos, cost):
if(emptyPos != 0 and emptyPos != 3 and emptyPos != 6):
newState = puzzle[:emptyPos-1] + EMPTY_SPACE + \
puzzle[emptyPos-1] + puzzle[emptyPos+1:]
return Node(puzzle, ESQUERDA, cost+1, newState)
else:
return None
def getUp(puzzle, emptyPos, cost):
if(emptyPos-3 >= 0):
newState = puzzle[:emptyPos-3] + EMPTY_SPACE + puzzle[emptyPos -
2:emptyPos] + puzzle[emptyPos-3] + puzzle[emptyPos+1:]
return Node(puzzle, ACIMA, cost+1, newState)
else:
return None
def getDown(puzzle, emptyPos, cost):
if(emptyPos+3 <= 8):
newState = puzzle[:emptyPos] + puzzle[emptyPos+3] + \
puzzle[emptyPos+1:emptyPos+3] + EMPTY_SPACE + puzzle[emptyPos+4:]
return Node(puzzle, ABAIXO, cost+1, newState)
else:
return None
if __name__ == '__main__':
dfs() |
9576cd9981b4c19cb4895365a0621758a92eaf45 | anas-yousef/Asteroids-Game | /asteroid.py | 2,247 | 4.03125 | 4 | import math
TEN = 10
MINUS_FIVE = -5
class Asteroid:
def __init__(self, location, speed, life):
'''
:param location: Takes in the initial location of the asteroid
:param speed: Takes in the initial speed of the asteroid
:param life: Takes in the initial life of the asteroid
Initializes our class Asteroid
'''
self._x_location, self._y_location = location
self._x_speed, self._y_speed = speed
self._life = life
self._radius = self._life * TEN + MINUS_FIVE
def get_location(self):
'''
:return: Returns the location of the asteroid
'''
return self._x_location, self._y_location
def get_speed(self):
'''
:return: Returns the speed of the asteroid
'''
return self._x_speed, self._y_speed
def get_life(self):
'''
:return: Returns the life of the asteroid
'''
return self._life
def get_radius(self):
'''
:return: Returns the radius of the asteroid
'''
return self._radius
def set_location(self, new_location):
'''
:param new_location: New location for the asteroid
:return: Sets a new location for the asteroid
'''
self._x_location, self._y_location = new_location
def set_speed(self, new_speed):
'''
:param new_speed: New speed for the asteroid
:return: Sets a new speed for the asteroid
'''
self._x_speed, self._y_speed = new_speed
def set_life(self, new_life):
'''
:param new_life: New life for the asteroid
:return: Sets new life for the asteroid
'''
self._life = new_life
def has_intersection(self, obj):
'''
:param obj: The object we want to check interaction with
:return: Returns True if there is an interaction, otherwise False
'''
x_obj, y_obj = obj.get_location()
x_asteroid, y_asteroid = self.get_location()
distance = math.sqrt(math.pow((x_obj - x_asteroid), 2) + math.pow((y_obj - y_asteroid), 2))
if(distance <= self._radius + obj.get_radius()):
return True
return False |
4b6b08ab7cc50cfd04f423b39e64f91d46ec6fdd | Harakiri604/PGRM-1006 | /Week 2.2 - Pandas.py | 1,046 | 3.703125 | 4 | import pandas as pd
df = pd.read_csv("co2_emissions_tonnes_per_person.csv", index_col='country')
print(df.head(10))
print(df.describe())
print(df.columns)
print(df.index)
#Creating a list by columns
year19and20 = df[['1900', '2000']]
print(year19and20)
#Creating a list by rows
canadaAndchina = df.loc[['Canada','China']]
print(canadaAndchina)
#practice
india = df.loc['India']
print(india)
#Max/min etc
someMax = df[['1900','2000']].max()
print(someMax)
#Max of which country
maxCountry = df[['1950','1970','2014']].idxmax()
print(maxCountry)
#Add booleans
conditionals = df['2000'] > 10
print(conditionals)
#Booleans by row
conditionalsRow = df.loc['China'] > 6
print(conditionalsRow)
filtered = df['2000'][conditionals]
print(filtered)
#Plotting
df.loc['Canada'].plot()
df.loc['China'].plot()
#Plotting multiple
df.loc[['Canada','China','Russia', 'Mongolia']].T.plot()
#Sorting by specific column's values
df = df.sort_values(by='2014', ascending=False).head()
print(df.head())
|
0b79c5643a6406e9055c69cc160136ff712d9c54 | Harakiri604/PGRM-1006 | /Week 1.3 - Anonymous Functions.py | 246 | 3.84375 | 4 | # Lambda function syntax - lambda x,y,z: x+y+z
#Sum function
x = lambda a,b:a+b
print(x(2,3))
print(x(3,5))
#Power function
y = lambda a:a**2
print(y(2))
#List comprehension
z = lambda a:a**2
a = [z(y) for y in range (20)]
print(a) |
271876e5e1d156160e0c472fe3f251725f01ac3f | dhanraj404/ADA_1BM18CS027 | /longestpalindrome.py | 412 | 3.5625 | 4 | def max(x, y):
if(x > y):
return x
return y
def lps(seq, i, j):
if (i == j):
return 1
if (seq[i] == seq[j] and i + 1 == j):
return 2
if (seq[i] == seq[j]):
return lps(seq, i + 1, j - 1) + 2
return max(lps(seq, i, j - 1),
lps(seq, i + 1, j))
if __name__ == '__main__':
seq = input("Enter the String: ")
n = len(seq)
print("The length of the LPS is",
lps(seq, 0, n - 1))
|
7ede4feb02c69b109063273387609b7b43931927 | dhanraj404/ADA_1BM18CS027 | /q16/dijkstra.py | 1,503 | 3.78125 | 4 | def creategraph(vertices):
return [[0]*vertices for _ in range(vertices)]
def dijkstra(G, root, vertices):
def _mindistance(distance, vertices, selected):
mn = 10**8
for v in range(vertices):
if distance[v] < mn and v not in selected:
mn = distance[v]
min_idx = v
return min_idx
distance = [10**8]*vertices
distance[root] = 0
selected = set()
for _ in range(vertices):
u = _mindistance(distance, vertices, selected)
selected.add(u)
for v in range(vertices):
if G[u][v] > 0 and v not in selected and distance[v] > distance[u]+G[u][v]:
distance[v] = distance[u] + G[u][v]
for i in range(vertices):
print('From {} to {} -> {}'.format(root, i, distance[i]))
"""
vertices = int(input("enter number of vertices: "))
edges = int(input("enter number of edges: "))
G = creategraph(vertices)
print('Enter', edges, 'edges:')
print('eg: (vertex1 vertex2 weight)')
for _ in range(edges):
s, e, w = map(int, input().split())
G[s][e] = w
dijkstra(G, 0, vertices)
"""
G = [ [0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]
dijkstra(G, 0, 9) |
4486ff6ea00e2f7c0b9a41ddbc7c50e669690de2 | dhanraj404/ADA_1BM18CS027 | /binaryandlinear.py | 1,441 | 4.0625 | 4 | #Implement Recursive Binary search and Linear search and determine the time required to search an element. Repeat the experiment for #different values of N and plot a graph of the time taken versus N.
def binary(L,x):
L.sort()
l = 0
n = r = len(L)-1
while l <= r:
mid = int((l+r)/2)
if L[mid] == x:
'''
i = mid
k = mid
while L[i] == x and i >= 0:
f_pos = i
i -= 1
while L[k] == x and k != n:
l_pos = k
k += 1
if k == n:
l_pos += 1
print('The first occurrence of the key is at:',f_pos,'\nLast occurrence is at ',l_pos)
print('Count:',(l_pos-f_pos+1))
return
'''
print('Element found')
return
elif L[mid] < x:
l = mid+1
else :
r = mid-1
else:
print('Element not found.')
return
def linear(L, x):
L.sort()
for i in range(len(L)+1):
if L[i] == x:
print("Element found")
else :
print("Element not found")
import time
L = list(map(int, input('Enter the Array:').split()))
x = int(input('Enter the search element:'))
startB = time.process_time()
binary(L, x)
print("Binary Search",time.process_time()-startB)
startL = time.process_time()
linear(L, x)
print("Linear Search",time.process_time()-startL)
|
00646f9582bda3050984de87ef0e21f8325e9c3d | techforthepeople/NAVI-IoT-device | /setup.py | 950 | 3.625 | 4 | #Script for initial database setup
import sqlite3
from sqlite3 import Error
db = 'sensor.db'
def open_database(db):
con = None
try:
con = sqlite3.connect(db)
return con
except Error as e:
print(e)
return con
def create_table(con, sql):
try:
c = con.cursor()
c.execute(sql)
except Error as e:
print(e)
def main():
# create settings table
create_settings_sql = (' CREATE TABLE IF NOT EXISTS settings ('
'userid text,'
'low_temp integer,'
'high_temp integer,'
'low_humidity integer,'
'high_humidity integer,'
'low_pressure integer,'
'high_pressure integer,'
'polling_frequency integer);')
con = open_database(db)
if con is not None:
create_table(con, create_settings_sql)
else:
print("Can't open database")
if __name__ == '__main__':
main()
|
3ce0ea12701b7a79bb91e4d747176383682fe34d | 09ubberboy90/PythonProjects | /unit 14/pack/example5.py | 736 | 3.875 | 4 |
import tkinter
def display():
name = textVar.get()
messageLabel.configure(text="Hello "+name)
top = tkinter.Tk()
top.title("New_Title")
top.geometry("800x600")
top.configure(background = "white")
textVar = tkinter.StringVar("")
textEntry = tkinter.Entry(top,textvariable=textVar,width=12 ,bg = "white")
textEntry.grid(row=0,column=0)
messageLabel = tkinter.Label(top,text="",width=12,bg = "white")
messageLabel.grid(row=1,column=0)
showButton = tkinter.Button(top,text="Show",command=display,bg = "white",activebackground = "white")
showButton.grid(row=1,column=1)
quitButton = tkinter.Button(top,text="Quit",command=top.destroy,bg = "white",activebackground = "white")
quitButton.grid(row=1,column=2)
tkinter.mainloop()
|
882676658b32eb43e8e56162222b1ae7549f7627 | 09ubberboy90/PythonProjects | /graph/pack/__init__.py | 333 | 3.8125 | 4 | def test():
n = 2
x = 3
y = 4
n_increase = 0
x_increase = 0
y_increase = 0
while n_increase < n :
while x_increase < x :
while y_increase < y :
print("%d "% n)
y_increase +=1
x_increase += 1
n += 1
print(n)
test() |
789ef6d23defed8c3d6db95395ca9b8c80015f44 | AdityaM8/AMDZS | /P8.py | 124 | 4.28125 | 4 | x=int(input("enter the number"))
f=1
for i in range(1,x+1):
f= f*i
print ("The factorial is: ")
print (f)
|
4546b612b86188bd7be2bea96d3cb3a36529a28e | AdityaM8/AMDZS | /P7.py | 148 | 3.546875 | 4 | a=int(input("Enter lower limit:"))
b=int(input("Enter upper limit:"))
for n in range(a, b+1):
if((n%7==0) & (n%5!=0)):
print(n)
|
71f14e4f33f3d3c82a4fce471b679d5773c7ebe5 | bbsara/python-program | /multiptable.py | 252 | 3.828125 | 4 | n=int(input("enter the value of n"))
for i in range(1,11):
print(n,'x',i,'=',n*i)
#output
enter the value of n5
5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50 |
77c573ce31e2fefb975ade179176200cad5e5dd7 | bajpaiNikhil/dynamicProgramming | /bestSum.py | 1,494 | 4 | 4 | """given an target and array find the min len array whose sum is equall to target"""
#
# def best_sum(target_sum, numbers):
# if target_sum == 0:
# return []
# shortest_combination = None
# for num in numbers:
# remainder = target_sum - num
# if remainder >= 0:
# combination = best_sum(remainder, numbers)
# if combination is not None:
# combination = combination + [num]
# if shortest_combination is None or len(combination) < len(shortest_combination):
# shortest_combination = combination
# return shortest_combination
def best_sum(target_sum, numbers):
memo = {}
def helper(target_sum, numbers):
if target_sum == 0:
return []
if target_sum in memo:
return memo[target_sum]
shortest_combination = None
for num in numbers:
remainder = target_sum - num
if remainder >= 0:
combination = helper(remainder, numbers)
if combination is not None:
combination = combination + [num]
if shortest_combination is None or len(combination) < len(
shortest_combination
):
shortest_combination = combination
memo[target_sum] = shortest_combination
return memo[target_sum]
return helper(target_sum, numbers)
print(best_sum(5,[2,3,1,1,1])) |
b3a5649c4111ada661cef24d1d410c8d58b49153 | vyahello/speech-recogniser | /lib/robot/robots.py | 1,608 | 3.625 | 4 | from abc import ABC, abstractmethod
from lib.robot.engines import Engine
from lib.robot.quotes import Quotes
from lib.robot.speech import Sayable, Speech
class Robot(ABC):
"""Represent abstract robot."""
@abstractmethod
def cheer_up(self) -> None:
"""Cheer up the master."""
pass
@abstractmethod
def say_joke(self) -> None:
"""Say a joke."""
pass
@abstractmethod
def say_summary(self) -> None:
"""Compose a summary about a robot."""
pass
@abstractmethod
def say_unknown(self) -> None:
"""Unknown word to say."""
pass
@abstractmethod
def say_goodbye(self) -> None:
"""Say bye."""
pass
@abstractmethod
def say_hello(self) -> None:
"""Say hello."""
pass
@abstractmethod
def say_things_going(self) -> None:
"""Say how is going."""
pass
class JackRobot(Robot):
"""Represent robot named `Jack`."""
def __init__(self, speech_engine: Engine) -> None:
self._say: Sayable = Speech(speech_engine, Quotes())
def cheer_up(self) -> None:
self._say.cheer_up()
def say_joke(self) -> None:
self._say.joke()
def say_summary(self) -> None:
self._say.summary(
name='Jack',
age='with immortal'
)
def say_unknown(self) -> None:
self._say.unknown()
def say_goodbye(self) -> None:
self._say.goodbye()
def say_hello(self) -> None:
self._say.hello()
def say_things_going(self) -> None:
self._say.things_going()
|
ec2a4d0d4d528f20f5f84ed3b4e31d004339000e | hikoyoshi/hello_python | /time_example.py | 1,556 | 3.515625 | 4 | #!-*- coding:utf-8 -*-
import time,datetime
print(time.time()) # 返回當前時間的時間戳(1970紀元後經過的浮點秒數)
print(time.altzone) # 返回與UTC時間的時間差,以秒計算
print(time.localtime()) # 返回本地時間的struct time物件格式
print(time.gmtime(time.time())) # 返回UTC時間的struct時間物件格式
print(time.asctime()) # 返回時間格式'Fri Feb 9 15:55:27 2018'
print(time.asctime(time.localtime())) # 返回時間格式'Fri Feb 9 15:55:27 2018'
print(time.ctime()) # 返回時間格式'Fri Feb 9 15:55:27 2018',同上
print ("---------------------")
#日期字串 轉成 時間戳
print(time.strptime('2018-02-08','%Y-%m-%d')) # 將日期字串轉成struct時間物件格式
print(time.mktime(time.strptime('2018-02-08','%Y-%m-%d'))) # 將struct時間物件轉成時間戳
# 將時間戳 轉成 字串
print(time.gmtime()) # 將UTC時間戳轉換成struct_time格式
print(time.strftime('%Y-%m-%d %H:%M:%S')) # 返回以可讀字串表示的當地時間
print ("---------------------")
print(datetime.datetime.now()) # 返回'2018-02-09 16:04:43.109066'
print(datetime.date.fromtimestamp(time.time())) # 時間戳直接轉成日期格式'2018-02-09'
# 時間加減
print(datetime.datetime.now() + datetime.timedelta(3)) # 當前時間+3天
print(datetime.datetime.now() - datetime.timedelta(3)) # 當前時間-3天
print(datetime.datetime.now() + datetime.timedelta(hours=3)) # 當前時間+3小時
print(datetime.datetime.now() + datetime.timedelta(minutes=30)) # 當前時間+30分鐘 |
dbe7b53cb7768ca9794bca41d8688117830e887b | hikoyoshi/hello_python | /example_9/main.py | 542 | 3.828125 | 4 | #-*- coding:utf-8 -*-
import temperature as tp
c_or_f = input("0、離開 1、轉換為華式 2、轉換為攝式\n")
if c_or_f == "0":
print ("ByeBye~~")
sys.exit()
elif c_or_f != "1" and c_or_f !="2":
print ("沒這個選項啦~~")
sys.exit()
temp = input("請輸入溫度:\n")
if c_or_f == "0":
print ("ByeBye~~")
sys.exit()
elif c_or_f =="1":
f = tp.c2f(int(temp)
print f
print ("華式溫度為{}".format(f))
elif c_or_f =="2":
c = tp.f2c(int(temp)
print ("攝式溫度為{}".format(c)) |
759d6ceff530708756a834632dd744e576ab5157 | hikoyoshi/hello_python | /pillow_demo/pillow_rotated.py | 454 | 3.515625 | 4 | #!-*- coding:utf-8 -*-
#載入pil模組
from PIL import Image,ImageDraw,ImageFont
#載入圖片
im = Image.open('kaeru.jpg')
#旋轉45度,可旋轉任意角度但rotate的旋轉不是整張旋轉所以會帶有黑邊
nim = im.rotate(45)
nim.save("rotated.jpg")
# transpose 為整張旋轉不會有黑邊,可上下左右翻轉,旋轉角度以90、180、270
nimt =im.transpose(Image.FLIP_LEFT_RIGHT)
nimt.save("transpose.jpg")
nim.show()
nimt.show() |
cffb4d38386a6ae750d02eda9cfc05176ef6cb44 | hikoyoshi/hello_python | /module/xmath.py | 197 | 3.75 | 4 | def max(a,b):
return a if a > b else b
def min(a,b):
return a if a < b else b
def sum(*numbers):
total = 0
for number in numbers:
total += number
return total
pi = 3.1415926
e = 2.718281 |
e89d601b7e0fa608b872065882f6b00269afa615 | senchenkoanastasiya/study | /test3.py | 200 | 4 | 4 | def sum_of_digit():
n = input("Введите трехзначное число: ")
n = int(n)
a = n % 10
b = n % 100 // 10
c = n // 100
return a + b + c
print(sum_of_digit()) |
5a73135343eaef9b00eb933ce11119d43b5c3869 | ashleygw/AI | /smallProjects/bayesianNetwork/randvar.py | 4,854 | 3.8125 | 4 | """
Make sure to fill in the following information before submitting your
assignment. Your grade may be affected if you leave it blank!
For usernames, make sure to use your Whitman usernames (i.e. exleyas).
File name: randvar.py
Author username(s): ashleygw, millersm
Date: 5/4/2018
"""
'''
randvar.py
A module containing a class for building and training random variables
By Andy Exley
'''
import itertools
import random
from collections import defaultdict
import random
class RVNode:
'''
Represents a single random variable node in a Bayes Network
'''
def __init__(self, name, vrange, dependencies = None):
'''
Constructor for an RVNode
vrange is a list containing the range of this RV (its possible values)
i.e. [0, 1] for a boolean RV
dependencies is a list of other RVNodes that this RVNode is conditionally dependent on
'''
self.name = name
self.vrange = vrange
self.deps = dependencies
self.CPT = {}
self.sizedict = defaultdict(lambda: 0)
self.id = random.random()
if self.deps == None:
# okay, this RV does not depend on anything, we want a prior distr.
for var in self.vrange:
self.CPT[var] = 0
else:
deprangelist = []
for dep in self.deps:
deprangelist.append(dep.vrange)
# okay now deprangelist is a list of lists of ranges. each possible
# combination is a possible row in our CPT
# it is added as a tuple key
for row in itertools.product(*deprangelist):
self.CPT[row] = {}
for var in self.vrange:
self.CPT[row][var] = 0
def __hash__(self):
return hash((self.name, self.id))
def __eq__(self, other):
return (self.name, self.id) == (other.name, other.id)
def train(self, examples):
'''trains this RV from the given examples.
If this RV is not dependent on another, we expect examples to be a list of
values in vrange. We just count and set probabilities in out CPT.
e.g. if examples is [0,1,1,1,0,1,0,1,1,1]
then self.CPT[0] = .3 and self.CPT[1] = .7
If this RV is dependent on another, we expect examples to be a list of lists,
where each list is a single example containing values for the dependent variables and
this variable.
e.g. if examples is [[0,1], [1,1], [0,1], [1,0], [0,0]]
then self.CPT[(0,)][0] = 1
self.CPT[(0,)][1] = 2
self.CPT[(1,)][0] = 1
self.CPT[(1,)][1] = 1
I USE PROBABILITIES NOT THESE NUMBERS
FOR THIS EXAMPLE THESE ARE THE SAME FORM AS ABOVE
'''
size = len(examples)
if not isinstance(examples[0], list):
save = defaultdict(lambda: 0)
for item in examples:
save[item] += 1
for item in save:
self.CPT[item] = save[item]/size
else:
for l in examples:
a = tuple(l[:-1])
b = l[-1]
self.sizedict[a] += 1
self.CPT[a][b] += 1
for key in self.CPT:
for key2 in self.CPT[key]:
self.CPT[key][key2] /= self.sizedict[key]
def sample(self, depvals = None):
'''Generates a random sample from this RV.
If this RV doesn't have dependencies, just use the CPT to generate a random value.
If this RV has dependencies, use the given values to look up the CPT to generate a random value
'''
if not self.deps:
r = random.random()
for i in self.CPT:
r = r - self.CPT[i]
if r < 0:
return i
else:
dep = tuple(depvals)
r = random.random()
for i in self.CPT[dep]:
r = r - self.CPT[dep][i]
if r < 0:
return i
def test_simple():
'''tests a simple RV with no dependencies
'''
r1 = RVNode('Rain', [0,1])
r1.train([0,0,0,1,0,0,0,0,0,1,1,1,1,0,1]) # 9 0's, 6 1's.
zcount = 0
for i in range(1000):
result = r1.sample()
if result == 0:
zcount += 1
print('After 1000 samples, got %d 0s.' % zcount)
def test_1dep():
'''tests an RV with a single dependency
'''
r1 = RVNode('Rain', [0,1])
r1.train([0,0,0,1,0,0,0,0,0,1,1,1,1,0,1]) # 9 0's, 6 1's.
r2 = RVNode('Wet', [0,1], dependencies = [r1])
# train: it rains 6 times, 4 of those times the ground is wet.
# it doesn't rain 3 times, each of those times the ground is not wet.
r2.train([[1,1], [1,1], [1,0], [1,1], [1,1], [1,0],
|
fbcd8afd885134d564c137da6c6e5e017903697e | krishna07210/com-python-core-repo | /src/main/py/07-Exceptions/Raising-Exceptions.py | 438 | 3.953125 | 4 | def main():
try:
for line in readfile('line.txt1'): print(line.strip())
except IOError as e:
print('Could not find the file: ', e)
except ValueError as e:
print('bad filename: ',e)
def readfile(filename):
if filename.endswith('.txt'):
fh = open(filename)
return fh.readlines()
else:
raise ValueError('Filename must end with .txt')
if __name__ == "__main__": main()
|
1073469bf7f0ae9eab2079507b655a22897eaf25 | krishna07210/com-python-core-repo | /src/main/py/05-Operators/Operators.py | 700 | 3.921875 | 4 | #!/usr/bin/python3
def main():
print('Add -', 5 + 5)
print('Multi -', 5 * 5)
print('Sub -', 5 - 3)
print(5 / 3)
print(5 // 3)
print(5 % 3)
print(divmod(5, 3))
num = 5
num += 1
print(num)
x, y = 4, 5
print(id(x), id(y))
print(x is y)
print(x is not y)
x = 5
print(id(x), id(y))
print(x is y)
print('Booleans')
print(True and False)
print(True and True)
print(True or False)
print(False and False)
print(False or False)
print('----')
a, b = 0, 1
x, y = 'zero', 'one'
print(x < y)
if a < b and x < y:
print('yes')
else:
print('no')
if __name__ == "__main__": main()
|
cfa342710536f41de8ec8967c38b8fc1b23a3fd6 | krishna07210/com-python-core-repo | /src/main/py/10-StringMethods/String-working.py | 850 | 4.21875 | 4 | def main():
print('This is a string')
s = 'This is a string'
print(s.upper())
print('This is a string'.upper())
print('This is a string {}'.format(42))
print('This is a string %d' % 42)
print(s.find('is'))
s1 = ' This is a string '
print(s1.strip())
print(s1.rstrip())
s2 = ' This is a string\n'
print(s2.rstrip('\n'))
print(s.isalnum())
print('thisisasting'.isalnum())
a,b =1,3
print('this is {}, that is {}'.format(a,b))
s = 'this is {}, that is {}'
print(s.format(5,9))
print(s.center(80))
s1 = 'this is %d, that is %d' % (a,b)
print(s1 )
a,b =42,35
print('this is {}, that is {}'.format(b,a))
print('this is {1}, that is {0}'.format(b,a))
print('this is {bob}, that is {fred}'.format(bob=a,fred=b))
if __name__ == "__main__": main()
|
c0ef50bb9e3c789792feb214dcbb7675100255ec | avalanchesiqi/awesome-tools | /tutorials/stationary_time_series_data.py | 3,818 | 3.5625 | 4 | """
How to Check if Time Series Data is Stationary with Python
source: https://machinelearningmastery.com/time-series-data-stationary-python/
"""
from pandas import Series
from scipy.stats import ks_2samp
from statsmodels.tsa.stattools import adfuller
import matplotlib.pyplot as plt
if __name__ == '__main__':
# == == == == == == Part 1: prepare exemplary data == == == == == == #
# stationary time series data
s_data = Series.from_csv('./data/stationary_ts/daily-total-female-births.csv', header=0)
# non-stationary time series data
ns_data = Series.from_csv('./data/stationary_ts/international-airline-passengers.csv', header=0)
# visualize data
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 7))
ax1.plot(s_data)
ax1.set_title('Stationary time series data')
ax2.plot(ns_data)
ax2.set_title('Non-stationary time series data')
plt.tight_layout()
plt.show()
# == == == == == == Part 2: calculate summary statistics == == == == == == #
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 7))
ax11 = ax1.twinx()
ax22 = ax2.twinx()
# split the time series into two continuous sequences and calculate mean and variance
for idx, data in enumerate((s_data, ns_data)):
X = data.values
split = len(X) // 2
X1, X2 = X[:split], X[split:]
if idx == 0:
print('statistics for two continuous sequences in stationary data')
ax11.hist(X1, normed=True, cumulative=True, histtype='step', color='b', label='CDF of 1st half')
ax11.hist(X2, normed=True, cumulative=True, histtype='step', color='r', label='CDF of 2nd half')
else:
print('statistics for two continuous sequences in non-stationary data')
ax22.hist(X1, normed=True, cumulative=True, histtype='step', color='b', label='CDF of 1st half')
ax22.hist(X2, normed=True, cumulative=True, histtype='step', color='r', label='CDF of 2nd half')
mean1, mean2 = X1.mean(), X2.mean()
var1, var2 = X1.var(), X2.var()
print('mean1=%.2f, mean2=%.2f' % (mean1, mean2))
print('variance1=%.2f, variance2=%.2f' % (var1, var2))
print('running Kolmogorov-Smirnov statistic test...')
print(ks_2samp(X1, X2))
# plot CDF of two sequences
print('-'*79)
ax1.hist(s_data, alpha=0.2, color='k')
ax1.set_title('Stationary data ~ Gaussian distribution')
ax2.hist(ns_data, alpha=0.2, color='k')
ax2.set_title('Non-stationary data ~ Non-Gaussian distribution')
ax11.legend(loc='best', frameon=False)
ax22.legend(loc='best', frameon=False)
plt.tight_layout()
plt.show()
# == == == == == == Part 3: perform Augmented Dickey-Fuller test == == == == == == #
# Null Hypothesis (H0): If accepted (p-value > 0.05), it suggests the time series has a unit root,
# meaning it is non-stationary. It has some time dependent structure.
# Alternate Hypothesis (H1): If rejected (p-value <= 0.05), it suggests the time series does not have a unit root,
# meaning it is stationary. It does not have time-dependent structure.
for idx, data in enumerate((s_data, ns_data)):
if idx == 0:
print('Augmented Dickey-Fuller test for stationary data')
else:
print('Augmented Dickey-Fuller test for non-stationary data')
result = adfuller(data)
print('ADF Statistic: %.4f' % result[0])
print('p-value: %.4f' % result[1])
print('Critical Values:')
for key, value in result[4].items():
print('\t%s: %.4f' % (key, value))
if result[1] > 0.05:
print('>>> accept H0, it is non-stationary time series data.')
else:
print('>>> reject H0, it is stationary time series data.')
print('='*79)
|
1ec5b2dab936247f8792abc87c39a523175dc5ea | goofygeckos/drunken-ninja | /utils/pngconvert.py | 1,416 | 3.765625 | 4 | """Goofy utility to convert between PNG and text files.
Usage:
pngconvert.py myfile.png myfile.txt
Or:
pngconvert.py myfile.txt myfile.png [options]
"""
import optparse
import png
def convert_png_to_txt(png_file, txt_file):
r = png.Reader(png_file)
f = open(txt_file, 'w')
width, height, pixels, meta = r.read()
print >> f, width, height
for row in pixels:
for index, pixel in enumerate(row, 1):
print >> f, pixel,
if index % width == 0:
print >> f # start new line
def convert_txt_to_png(txt_file, png_file, options):
f = open(txt_file, 'r')
width, height = map(int, f.readline().split())
# TODO: pass any needed options to Writer
w = png.Write(width=width, height=height)
def row_reader():
yield map(int, f.readline().split())
w.write(open(png_file, 'w'), row_reader())
def option_parser():
parser = optparse.OptionParser()
parser.add_option('--bitdepth', dest='bitdepth',
help='Bit depth: from 1 to 16', default=1)
# TODO: add any missing options here
return parser
def main():
parser = option_parser()
(options, args) = parser.parse_args()
if len(args) != 2:
print __doc__
parser.print_help()
else:
in_file, out_file = args
if in_file.endswith('.png'):
convert_png_to_txt(in_file, out_file)
else:
convert_txt_to_png(out_file, in_file, options)
if __name__ == "__main__":
main()
|
728e6e0ed79d771b5448317a4f53f1429ac4cbdb | tnmoc-coderdojo/coderdojo | /python/pong/pong.py | 2,877 | 3.609375 | 4 | import pygame
from pygame.locals import *
def draw_game_screen():
screen.blit(bg,(0,0))
screen.blit(paddle1, (10, l_paddle_pos))
screen.blit(paddle2, (620, 100))
screen.blit(ball, (ball_pos_x, ball_pos_y))
# Scores
l_score_str = font.render(str(l_score), True, (0,0,0))
r_score_str = font.render(str(r_score), True, (0,0,0))
screen.blit(l_score_str, (50,10))
screen.blit(r_score_str, (560,10))
def move_ball():
""" Update the position of the ball and check if it has hit the paddle or
the edge of the screen """
global ball_pos_x, ball_pos_y
global ball_speed_x, ball_speed_y
global l_paddle_pos, l_paddle_speed
global l_score, r_score
ball_pos_x += ball_speed_x
ball_pos_y += ball_speed_y
if l_paddle_pos + l_paddle_speed > 0 and l_paddle_pos + l_paddle_speed < 430:
l_paddle_pos += l_paddle_speed
relative_pos_l = ball_pos_y - l_paddle_pos
if ball_pos_x <= 20 and relative_pos_l > -8 and relative_pos_l < 50:
ball_speed_x = -ball_speed_x
if ball_pos_x > 604:
ball_speed_x = -ball_speed_x
if ball_pos_y <= 0 or ball_pos_y > 464:
ball_speed_y = -ball_speed_y
if ball_pos_x <= 0 or ball_pos_x > 624:
if ball_pos_x <= 0:
r_score += 1
else:
l_score += 1
ball_speed_x = -ball_speed_x
ball_pos_x += 10 * ball_speed_x
ball_pos_y = 200
def handle_user_input():
""" Handle any keys pressed or released by the user """
global game_over
global l_paddle_speed
for event in pygame.event.get():
if event.type == QUIT:
game_over = True
elif event.type == KEYDOWN:
if event.key == ord('s'):
l_paddle_speed = max_paddle_speed
elif event.key == ord('w'):
l_paddle_speed = -max_paddle_speed
elif event.type == KEYUP:
if event.key == ord('s') or event.key == ord('w'):
l_paddle_speed = 0
pygame.init()
screen=pygame.display.set_mode((640,480))
pygame.display.set_caption("Pong!")
bg = pygame.Surface((640,480))
bg.fill((255,255,255))
paddle1 = pygame.Surface((10,50))
paddle1.fill((255,0,0))
paddle2 = pygame.Surface((10,50))
paddle2.fill((0,255,0))
ball = pygame.Surface((16,16))
ball = pygame.transform.scale(ball, (16,16))
#ball.fill((255,255,255))
#pygame.draw.circle(ball, (0,0,255), (8,8), 8)
clock = pygame.time.Clock()
font = pygame.font.SysFont("calibri",40)
ball_pos_x = 320
ball_pos_y = 240
ball_speed_x = 5
ball_speed_y = 5
max_paddle_speed = 5
l_paddle_pos = 50
l_paddle_speed = 0
l_score = 0
r_score = 0
game_over = False
while not game_over:
handle_user_input()
draw_game_screen()
move_ball()
pygame.display.flip()
clock.tick(30)
pygame.quit()
|
a3284a0c50e455866fdce7d59a573f14160765e0 | barweizman/SolveLinearEquations | /SolveLinearEquations.py | 11,213 | 3.640625 | 4 | # Bar Sela - 206902355
# Bar Weizman - 206492449
# ------Solve AX=b by using Gauss Elimination------
# Cond A
def CalcConditionNumber(matrix):
"""
description
calculation of the condition number by using the infinity norm
:param matrix: the matrix
:return: condition number
"""
norm_matrix = 0
norm_inverted = 0
sum_line = 0
row = len(matrix)
col = len(matrix[0])
for j in range(0, col):
for i in range(0, row):
sum_line += abs(matrix[i][j])
if sum_line > norm_matrix:
norm_matrix = sum_line
sum_line = 0 # reset for every line
inverted_matrix = InvertMatrix(matrix)
for j in range(0, col):
for i in range(0, row):
sum_line += abs(inverted_matrix[i][j])
if sum_line > norm_inverted:
norm_inverted = sum_line
sum_line = 0 # reset for every line
return norm_matrix * norm_inverted
# Print matrix
def printMatrix(matrix):
"""
description:
print matrix as a rows and columns
:param matrix: the printed matrix
"""
for row in matrix:
print('', end='\t\t\t\t')
print(row, end='\n')
# Singularity check-by calculating determination
def CalcDet(matrix):
"""
description:
recursive function.calculate the determination of the matrix
:param matrix: array nXn. represent the matrix
:return:matrix's determination
"""
n = len(matrix)
if n == 1:
return matrix[0][0]
det = 0
for j in range(0, n):
det += ((-1) ** j) * matrix[0][j] * CalcDet(SubDet(matrix, 0, j))
return det
def SubDet(matrix, i, j):
"""
description: the function create new matrix (n-1)(n-1) by
removing the selected column and row.
:param i: row to remove
:param matrix: the original matrix
:param j:column to remove
:return: minor matrix
"""
return [row[:j] + row[j + 1:] for row in (matrix[:i] + matrix[i + 1:])]
# Elementary Actions on Matrix-Creating an elementary matrix
def Identity(n):
"""
description:
The function Create identity matrix
:param n: size of choice
:return: identity matrix
"""
mat = [([0] * n) for i in range(n)] # initialize the matrix with zeros
for i in range(0, n):
mat[i][i] = 1 # the identity matrix includes 1 all over its diagonal, starts at [0][0]
return mat
def Matrix_multiplication(mat1, mat2):
"""
description:
The function the result matrix of multiplication two matrix
mat1 on the left and mat2 on the right
:param mat1: first initialized square matrix with values
:param mat2: second initialized square matrix with values
:return: result matrix, that will be the multiplication between mat1 and mat2
"""
if len(mat1[0]) != len(mat2):
raise Exception("Illegal multiplication between matrix's ")
result_mat = [([0] * len(mat2[0])) for i in range(len(mat1))] # initialize the result matrix with zeros
# iterate through the first matrix rows
for row1 in range(0, len(mat1)):
# iterate through the second matrix columns
for col2 in range(0, len(mat2[0])):
# iterate through the second matrix rows
for row2 in range(0, len(mat2)):
result_mat[row1][col2] += mat1[row1][row2] * mat2[row2][col2]
return result_mat
def Copy_matrix(mat):
"""
description:
the function receive matrix and return a copy of her
:param mat: matrix with values
:return: copy of the given matrix
"""
size = len(mat)
copied_mat = [([0] * size) for i in range(size)] # initialize the matrix with zeros
for row in range(0, len(mat)):
for col in range(0, len(mat[0])):
copied_mat[row][col] = mat[row][col] # copy all values
return copied_mat
def ResetOrgan(row, col, n, pivot, a):
"""
description:
create elementary matrix that reset the chosen organ to zero
at first the elementary matrix starts as a regular I matrix.
at the chosen indexes we put the value which will give a 0 by multiply the elementary matrix with the original matrix
:param row: num of row to insert the value
:param col: num of column to insert the value
:param n: number of rows and column
:param pivot: the pivot of the original matrix
:param a: the value we need to reset to zero
:return:elementary matrix
"""
elementary_matrix = Identity(n)
elementary_matrix[row][col] = -(a / pivot)
return elementary_matrix
def MultiplyRow(row, a, n):
"""
description:
The function create elementary matrix through which we can multiply a row by a value
insert the value to the pivot in the selected row
:param row:the selected row to multiply
:param a:the value to multiply the row
:param n:number of rows and columns in the original matrix
:return:elementary matrix
"""
elementary_matrix = Identity(n)
elementary_matrix[row][row] = a
return elementary_matrix
def ExchangeRows(row1, row2, n):
"""
The function creates for us an elementary matrix through which we can exchange rows
by multiplying them
:param row1:row to exchange
:param row2:row to exchange
:param n:number of rows and columns in the original matrix
:return:elementary matrix
"""
elementary_matrix = Identity(n)
elementary_matrix[row1][row1] = 0
elementary_matrix[row1][row2] = 1
elementary_matrix[row2][row2] = 0
elementary_matrix[row2][row1] = 1
return elementary_matrix
def InvertMatrix(matrix):
"""
description:
The function calculate the inverted matrix. suitable for non-singular(reversible matrix) matrix-if singular an exception will be raised
:param matrix: the matrix to invert
:return: inverted matrix
"""
if len(matrix) != len(matrix[0]):
raise Exception("singular matrix. there is no inverted matrix")
n = len(matrix)
inverted = Identity(n)
for j in range(0, n):
for i in range(0, n):
if i == j:
pivot = matrix[i][j]
for k in range(i + 1, n):
if abs(matrix[k][j]) > abs(pivot): # pivoting
elementary_matrix = ExchangeRows(k, i, n)
matrix = Matrix_multiplication(elementary_matrix, matrix)
inverted = Matrix_multiplication(elementary_matrix, inverted)
pivot = matrix[i][j]
if matrix[i][j] == 0:
raise Exception("singular matrix. there is no inverted matrix")
for i in range(0, n):
if i != j:
if matrix[i][j] != 0:
elementary_matrix = ResetOrgan(i, j, n, pivot, matrix[i][j])
matrix = Matrix_multiplication(elementary_matrix, matrix)
inverted = Matrix_multiplication(elementary_matrix, inverted)
for i in range(0, n):
if matrix[i][i] != 1:
if matrix[i][i] < 0:
elementary_matrix = MultiplyRow(i, -1, n)
matrix = Matrix_multiplication(elementary_matrix, matrix)
inverted = Matrix_multiplication(elementary_matrix, inverted)
elementary_matrix = MultiplyRow(i, 1 / matrix[i][i], n)
matrix = Matrix_multiplication(elementary_matrix, matrix)
inverted = Matrix_multiplication(elementary_matrix, inverted)
for row in range(n):
for col in range(n):
inverted[row][col] = round(inverted[row][col], 2)
return inverted
def LU_matrix_calculation(mat):
"""
description:
the function calculates the result by calculating L (lower triangular matrix) and U (upper triangular matrix)
:param mat: the given matrix
:param b: the result vector
:return: vector variables
"""
size = len(mat) # doesnt matter if we take len(mat) or len(mat[0]), were talking square matrix.
res = Copy_matrix(
mat) # in the whole process, we will consider "res" as the matrix we do all manipulations on, in order not to change the original matrix
for col in range(0, size):
pivot = res[col][col] # every iteration our pivot will be changed according to the res
if pivot == 0 and col != size - 1:
for row in range(col + 1, size):
if res[row][col] != 0:
elementary_matrix = ExchangeRows(row, col, size)
res = Matrix_multiplication(elementary_matrix, res)
mat = Matrix_multiplication(elementary_matrix, mat)
pivot = res[col][col]
break
if pivot == 0 and col != size - 1:
raise Exception("Could`nt calculate the L matrix and U matrix1")
for row in range(col + 1, size): # we start at col+1, in order to skip the pivot`s row
m = -(res[row][col] / pivot) # m is the multiply number
elementary_mat = Identity(size)
elementary_mat[row][col] = m # this is the elementary matrix (the identity matrix and the multiply number)
res = Matrix_multiplication(elementary_mat, res) # at the end of the loops, res will be 'U'
if col == 0 and row == 1: # in order to keep the first elementary matrix, for future calculations
L = InvertMatrix(elementary_mat)
else:
L = Matrix_multiplication(L, InvertMatrix(elementary_mat))
if Matrix_multiplication(L, res) == mat:
print("^^^^^^ LU Calculation ^^^^^^^")
print("L Matrix:")
printMatrix(L)
print("U Matrix:")
printMatrix(res)
else:
raise Exception("Could`nt calculate the L matrix and U matrix")
def CalcRegularMatrix(matrix, b):
"""
description:
the function calculate the result by multiply the inverted matrix and the result vector
:param matrix: the given matrix
:param b: the result vector
:return:the Vector variables
"""
return Matrix_multiplication(InvertMatrix(matrix), b)
# main function to calculate matrix
def CalcMatrix(matrix, b):
"""
description:
the function check if the determinant of param matrix. if the matrix is regular the function find the result of
multiplication of the inverted matrix and vector b.
if matrix is not regular the function print L and U matrix's
:param matrix:the selected matrix
:param b: the result vector
:return: if matrix regular print the vector solution else print L and U matrix's
"""
if CalcDet(matrix) == 0:
LU_matrix_calculation(matrix)
else:
print("result vector: ")
printMatrix(CalcRegularMatrix(matrix, b))
print("Cond(A)=", end=' ')
print(CalcConditionNumber(matrix))
# driver
mat1 = [[2, -1, 0],
[-1, 2, -1],
[0, -1, 2]]
b = [[4], [6], [8]]
mat2 = [[4, 5, -6],
[2, 5, 2],
[1, 3, 2]]
mat3 = [[0, 2, -1],
[3, -2, 1],
[3, 2, -1]]
mat4 = [[0, 2, -1],
[3, -2, 1],
[3, 2, 1]]
try:
CalcMatrix(mat1, b)
CalcMatrix(mat2, b)
CalcMatrix(mat3, b)
CalcMatrix(mat4, b)
except Exception as e:
print(e)
|
df806bbd777caaebb26b0b52f7ef58b571948629 | jdfrens/polyglot-euler | /001/Python/problem001.py | 141 | 3.734375 | 4 | def sum35(n):
return sum([m for m in range(0, n+1) if interestingNumber(m)])
def interestingNumber(n):
return n % 3 == 0 or n % 5 == 0
|
629109031bfa1503c4cc1ef7035776378b2f6825 | takaolds/cryptopals-solutions | /solutions/set1/challenge3.py | 325 | 3.546875 | 4 | def main():
input_string = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"
input_bytes = bytearray.fromhex(input_string)
for i in range(255):
result = bytearray("", 'utf-8')
for j in range(len(input_bytes)):
result.append(input_bytes[j] ^ i)
print("{0}: {1}".format(i, result))
if __name__ == "__main__":
main()
|
503e7db374872bb34b5126f33a7c28e580b96bd5 | ValeronMEN/Databases | /term1/lab1/lab1/module.py | 474 | 3.671875 | 4 | import datetime
def date_check(date):
birthday_date_array = date.split(' ')
if len(birthday_date_array) == 3:
year = int(birthday_date_array[0], 10)
if 1900 <= year <= datetime.datetime.now().year:
month = int(birthday_date_array[1], 10)
if 0 <= month <= 12:
day = int(birthday_date_array[2], 10)
if 1 <= day <= 31:
return datetime.date(year, month, day)
return None
|
56e740d84e825a248b044f1f867ea8f5a97ee76c | Maskyoung/pj1 | /t2.py | 670 | 3.84375 | 4 | # /usr/bin/env python
# -*- coding: utf-8 -*-
# a = 7
# if a > 0:
# # raise ValueError('number must be non-negative')
# print('asd')
# else:
# print(a)
#
# # # print(a)
# s='asdga\asdgasdasd\sdg\t\t'
# print(s)
# import re
# def plural(noun):
# if re.search('[sxz]$', noun):
# return re.sub('$', 'es', noun)
# elif re.search('[^aeioudgkprt]h$', noun):
# return re.sub('$', 'es', noun)
# elif re.search('[^aeiou]y$', noun):
# return re.sub('y$', 'ies', noun)
# else:
# return noun + 's'
# print(plural('asdngoasdcnaois'))
def fib(max):
a, b = 0, 1
while a < max:
yield a
a, b = b, a + b |
317e92540d3a6e00bec3dcddb29669fe4806c7fa | Frank1963-mpoyi/REAL-PYTHON | /FOR LOOP/range_function.py | 2,163 | 4.8125 | 5 | #The range() Function
'''
a numeric range loop, in which starting and ending numeric values are specified. Although this form of for loop isn’t directly built into Python, it is easily arrived at.
For example, if you wanted to iterate through the values from 0 to 4, you could simply do this:
'''
for n in (0, 1, 2, 3, 4):
print(n)
# This solution isn’t too bad when there are just a few numbers.
# But if the number range were much larger, it would become tedious
# pretty quickly.
'''
Happily, Python provides a better option—the built-in range() function,
which returns an iterable that yields a sequence of integers.
range(<end>) returns an iterable that yields integers starting with 0,
up to but not including <end>:
'''
print()
x = range(5)
print(x)
print(type(x))
print(range(0, 15))
# Note that range() returns an object of class range, not a list or tuple of the values. Because a range object is an iterable, you can obtain the values by iterating over them with a for loop:
x = range(5)
list(x)
tuple(x)
print(list(x))
print(tuple(x))
for n in x:
print(n)
# However, when range() is used in code that is part of a larger application,
# it is typically considered poor practice to use list() or tuple() in this way.
# Like iterators, range objects are lazy—the values in the specified range are not
# generated until they are requested. Using list() or tuple() on a range object forces
# all the values to be returned at once. This is rarely necessary, and if the list is long,
# it can waste time and memory.
print(list(range(5, 20, 3)))
#range(<begin>, <end>, <stride>) returns an iterable that yields integers starting with
# <begin>, up to but not including <end>. If specified, <stride> indicates an amount to skip
# between values (analogous to the stride value used for string and list slicing):
#If <stride> is omitted, it defaults to 1:
print( list(range(5, 10, 1)))
print( list(range(5, 10)))# if stride is omiited the default is one
print(list(range(-5, 5))) # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
print(list(range(5, -5)))#[]
print(list(range(5, -5, -1)))# [5, 4, 3, 2, 1, 0, -1, -2, -3, -4] |
341071c13e042e7de021e4883ecdd8b936633afb | Frank1963-mpoyi/REAL-PYTHON | /FOR LOOP/forloop_patterns_exercises.py | 417 | 4.09375 | 4 | no_patterns= int(input("Please Enter the Number of patterns: ? "))
'''
for num in range(1,no_patterns+1):
print()
for pict in range(1, 10):
print(pict, end="")
print()
print(f"Number of iteration : {num}")# will print the number of user input for each iteration
'''
for row in range(1, no_patterns):
for columns in range(0, row+1):
print("*", end="")
# print(row)
print() |
1eec2e1904286641b7140f572c19f7b860c3427e | Frank1963-mpoyi/REAL-PYTHON | /WHILE LOOP/whileloop_course.py | 2,036 | 4.25 | 4 | ''' Iteration means executing the same block of code over and over, potentially many times. A programming structure that implements iteration is called a loop'''
'''
In programming, there are two types of iteration, indefinite and definite:
With indefinite iteration, the number of times the loop is executed isn’t
specified explicitly in advance. Rather, the designated block is executed
repeatedly as long as some condition is met.
With definite iteration, the number of times the designated block will be
executed is specified explicitly at the time the loop starts.
while <expr>:
<statement(s)>
<statement(s)> represents the block to be repeatedly executed, often referred
to as the body of the loop. This is denoted with indentation, just as in an if statement.
'''
a = 0# initialise
while a <= 5: # to check Boolean condition if its True it will execute the body
# then when a variale will do addition it will be 0+1=1 go again to check the condition like new value
# of a = 1 and 1<=5 True it print and add again 1+1=2 2<=5, 2+1= 3 , 3<=5, until 6<=5 no the condition become false
# and the loop terminate
print(a)# you can print the a value for each iteration
# print("Frank") or you can print Frank the number of the iterations
a = a + 1# increment to make the initialize condition become false in order to get out of the loop
#Note : Note that the controlling expression of the while loop is tested first,
# before anything else happens. If it’s false to start with, the loop body will never
# be executed at all:
family = ['mpoyi', 'mitongu', 'kamuanya', 'sharon', 'ndaya', 'mbuyi', 'tshibuyi']
while family:#When a list is evaluated in Boolean context, it is truthy if it has elements in it and falsy if it is empty
print(family.pop(-1)) # for every iteration it will remove the last element in the list until the list is finish
#Once all the items have been removed with the .pop() method and the list is empty, a is false, and the loop terminates.
|
6fa0391f1539a982b0b11e1a38a6f1e9109a5460 | Frank1963-mpoyi/REAL-PYTHON | /MODULE_AND_PACKAGE/from_import.py | 1,639 | 4.03125 | 4 | '''
from <module_name> import <name(s)>
An alternate form of the import statement allows individual objects from
the module to be imported directly into the caller’s symbol table:
'''
#Syntax
# from <module_name> import <name(s)>
#Exemple
from mod import foo, s
print(s)
# Because this form of import places the object names directly into the caller’s
# symbol table, any objects that already exist with the same name will be overwritten:
# this s will override the one imported
s = [5, 6, 7]
print(s)
# It is even possible to indiscriminately import everything from a module at one fell swoop:
# Syntax
#from <module_name> import *
from mod import *
# Note:
'''
This isn’t necessarily recommended in large-scale production code. It’s a bit dangerous
because you are entering names into the local symbol table en masse. Unless you know them
all well and can be confident there won’t be a conflict, you have a decent chance of
overwriting an existing name inadvertently. However, this syntax is quite handy when
you are just mucking around with the interactive interpreter, for testing or discovery
purposes, because it quickly gives you access to everything a module has to offer without
a lot of typing.
'''
#from <module_name> import <name> as <alt_name>
#from <module_name> import <name> as <alt_name>[, <name> as <alt_name> …]
# >>> s = 'foo'
# >>> a = ['foo', 'bar', 'baz']
from mod import s as string, a as alist
print(string)
print(alist)
'''
import <module_name> as <alt_name>
You can also import an entire module under an alternate name:
'''
import mod as my_module
print(my_module.s)
|
16cd19a92c053cfe1cc9aeafac4d6484a98b308b | ngtrangtee/ngtrangtee.github.io | /python/homework2.py | 7,617 | 4.03125 | 4 | # 1. Viết chương trình yêu cầu người dùng nhập một chuỗi, và một giá trị số (index), hiển thị chuỗi được cắt từ 0 đến vị trí index
print("Nhập một chuỗi")
string = input(">")
print("Nhập một giá trị số (Index)")
index = input(">")
print(string[0:int(index)])
# 2. Viết chương trình yêu cầu người dùng nhập tên, in ra tên viết tắt theo mẫu:
# Ví dụ:
# Nhập tên: Ba Nguyễn
# Ba Ng.
print("Nhập Tên và Họ có dấu")
name = input("> ")
space = name.find(" ")
short_name = name.replace[:space + 3] + "."
print(short_name)
# 3. Viết chương trình yêu cầu người dùng nhập địa chỉ email, ẩn địa chỉ email và in ra theo mẫu trong ví dụ:
# Ví dụ:
# Nhập email: banguyen@gmail.com
# ba...@gmail.com
print("Nhập địa chỉ email")
email = input("> ")
at = email.find("@")
new_email = email.replace(email[2:at],"...")
print(new_email)
# 4. Viết chương trình yêu cầu người dùng nhập một chuỗi, và một ký tự bất kỳ trong chuỗi đó. Đếm số lần xuất hiện của ký tự trong chuỗi, và hiển thị chuỗi khi thay thế ký tự đó thành 😉
# Ví dụ:
# Nhập một chuỗi bất kỳ: Hello world
# Nhập một ký tự trong chuỗi: o
# Ký tự 'o' xuất hiện 2 lần trong chuỗi 'Hello world'
# Hell😉 w😉rld
print("Nhập một chuỗi")
string = input(str("> "))
print("Nhập một kí tự bất kì trong chuỗi trên")
character = input(str("> "))
print(f"Kí tự {character} xuất hiện {string.count(character)} lần trong chuỗi '{string}'")
new_string = string.replace(character, f"😉")
print(new_string)
# 1. Viết chương trình yêu cầu người dùng nhập vào 2 số a, b. Tính và in ra kết quả của các phép tính (+ - * / // % ...) giữa 2 số đó
print("Nhập số a")
number_a = int(input("> "))
print("Nhập số b")
number_b = int(input("> "))
print(number_a + number_b)
print(number_a - number_b)
print(number_a * number_b)
print(number_a / number_b)
print(number_a // number_b)
print(number_a % number_b)
# 4. Viết chương trình yêu cầu người dùng nhập vào giá trị độ dài (long) với đơn vị là cm, quy đổi và in ra giá trị tương ứng ở các đơn vị km, dm, m, mm
print("Nhập giá trị độ dài cm")
cm = int(input("> "))
km = cm/1000
dm = cm/10
m = cm/100
mm = cm*10
print(f"{cm} cm = {km} km")
print(f"{cm} cm = {dm} dm")
print(f"{cm} cm = {m} m")
print(f"{cm} cm = {mm} mm")
# 5. Viết chương trình yêu cầu người dùng nhập vào giá trị nhiệt độ thang nhiệt Celsius (c), quy đổi và in ra nhiệt độ tương ứng trong thang nhiệt Fahrenheit và Kevin
print("Nhập nhiệt độ theo giá trị Celcius")
celcius = int(input("> "))
fahrenheit = (celcius * 9/5) + 32
kevin = celcius + 273.15
print(f"{celcius} độ C = {fahrenheit} độ F")
print(f"{celcius} độ C = {kevin} độ K")
# 6. Viết chương trình yêu cầu người dùng nhập vào số phút (tính từ 0h của ngày hôm nay, giả sử số phút nhập không quá 1440), tính và in ra giá trị giờ:phút tương ứng (VD: 325 -> 5:25)
print("Nhập vào số phút (tính từ 0h của ngày hôm nay; số phút nhập không quá 1440)")
minutes = round(float(input("> ")))
hour = round(minutes // 60)
print(round(hour))
minute = round(((minutes / 60) % 1) * 60)
print(minute)
print(f"{minutes} phút tương ứng với {hour} giờ {minute} phút")
###################################
# 1. Viết chương trình yêu cầu nhập một số nguyên n, kiểm tra và in ra số đó có chia hết cho cả 3 và 5 hay không
# Ví dụ:
# Nhập một số nguyên: 5
# 5 không chia hết cho cả 3 và 5
import math
print("Type an integer")
integer = int(input("> "))
if integer % 3 == 0 and integer % 5 == 0:
print(f"{integer} Chia hết cho cả 3 và 5")
else:
print(f"{integer} Không chia hết cho cả 3 và 5")
# 2. 2. Viết chương trình yêu cầu nhập 3 số a, b, c. Kiểm tra và in ra số lớn nhất
# Ví dụ:
# Nhập số a: 1
# Nhập số b: 2
# Nhập số c: 3
# Số lớn nhất trong 3 số [1 2 3] là 3
import math
print("Type number A")
a = int(input("> "))
print("Type number B")
b = int(input("> "))
print("Type number C")
c = int(input("> "))
if a >= b and a >= c:
print(f"{a} là số lớn nhất")
elif b >= a and b >= c:
print(f"{b} là số lớn nhất")
elif c >= a and c >= b:
print(f"{c} là số lớn nhất")
print("Type an integer")
max = a = int(input(">"))
b = int(input(">"))
c = int(input(">"))
if b > max:
max = b
if c > max:
max = c
print(f"{max} la so lon nhat trong 3 so [{a}, {b}, {c}]")
# 3. Viết chương trình yêu cầu nhập 3 số a, b, c tương ứng với độ dài 3 cạnh tam giác. Kiểm tra và in ra 3 số có tạo thành một tam giác hợp lệ hay không
# Ví dụ:
# Nhập cạnh a: 1
# Nhập cạnh b: 3
# Nhập cạnh c: 3
# [1 3 3] là một tam giác hợp lệ
print("Nhập cạnh a của tam giác")
side_a = int(input("> "))
print("Nhập cạnh b của tam giác")
side_b = int(input("> "))
print("Nhập cạnh c của tam giác")
side_c = int(input("> "))
if (side_a + side_b) > side_c and (side_a + side_c) > side_b and (side_b + side_c) > side_a:
print(f"[{side_a} {side_b} {side_c}] là một tam giác hợp lệ")
else:
print(f"[{side_a} {side_b} {side_c}] không phải là một tam giác hợp lệ")
# # 4. Viết chương trình yêu cầu nhập 3 số a, b, c. Kiểm tra và in ra 3 số là dãy tăng dần (a < b < c), giảm dần (a > b > c) hay không
# # Ví dụ:
# # Nhập số a: 1
# # Nhập số b: 2
# # Nhập số c: 3
# # [1 2 3] là dãy tăng dần
print("Nhập số a")
number_a = int(input("> "))
print("Nhập số b")
number_b = int(input("> "))
print("Nhập số c")
number_c = int(input("> "))
if number_a <= number_b and number_b <= number_c:
print(f"[{number_a} {number_b} {number_c}] là dãy số tăng dần")
elif number_a >= number_b and number_b >= number_c:
print(f"[{number_a} {number_b} {number_c}] là dãy số giảm dần")
else:
print(f"[{number_a} {number_b} {number_c}] không phải là dãy số giảm dần hay tăng dần")
# 5. Viết chương trình yêu cầu nhập một ký tự, kiểm tra và in ra ký tự đó có thuộc bảng alphabet (a-zA-Z) hay không
# Ví dụ:
# Nhập một ký tự: g
# 'g' thuộc bảng ký tự alphabet
print("Nhập một kí tự")
letter = str(input("> "))
if letter.isalpha() == True:
print(f"{letter} thuộc bảng kí tự alphabet")
else:
print(f"{letter} không thuộc bảng kí tự alphabet")
# 6. Viết chương trình yêu cầu nhập một tháng trong năm, kiểm tra và in ra mùa tương ứng
# Ví dụ:
# Nhập một tháng bất kỳ: 5
# Tháng 5 là mùa hè
print("Nhập tháng trong năm dưới dạng số")
month = int(input("> "))
if month == 1 or month == 2 or month == 3:
print("Mùa xuân")
if month == 4 or month == 5 or month == 6:
print("Mùa hạ")
if month == 7 or month == 8 or month == 9:
print("Mùa thu")
if month == 10 or month == 11 or month == 12:
print("Mùa đông")
else:
print("Không phải tháng trong năm") |
eccf4a1f564166306f13e66bb7e89fa05738a7c6 | 425776024/Pythonic | /25mmap/1start.py | 1,221 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/5/7 13:36
# @Author : xinfa.jiang
# @Site :
# @File : 1start.py
# @Software: PyCharm
'''
mmap是一种虚拟内存映射文件的方法,即可以将一个文件或者其它对象映射到进程的地址空间,
实现文件磁盘地址和进程虚拟地址空间中一段虚拟地址的一一对映关系。
普通文件被映射到虚拟地址空间后,程序可以像操作内存一样操作文件,可以提高访问效率,适合处理超大文件
'''
import mmap
# write a simple example file
with open("hello.txt", "wb") as f:
f.write('Hello Python!\n'.encode())
f.write('Hello 123!\n'.encode())
with open("hello.txt", "r+b") as f:
# memory-map the file, size 0 means whole file
mm = mmap.mmap(f.fileno(), 0)
# read content via standard file methods
print(mm.readline())
# read content via slice notation
print(mm[:5])
# update content using slice notation;
# note that new content must have same size
mm[6:14] = " world!\n".encode()
# ... and read again using standard file methods
mm.seek(0)
print(mm.readline())
print(mm.readline())
# close the map
mm.close()
|
bcfb966cbb69581fc67cf1b81d25220710391602 | 425776024/Pythonic | /24asyncio/2并发运行.py | 900 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/5/6 12:30
# @Author : xinfa.jiang
# @Site :
# @File : 2start.py
# @Software: PyCharm
import threading
import asyncio
import time
async def hello(n):
# 打印的currentThread是一样的,也就是自始自终就是一个线程在高
print('Hello world! (%s)' % threading.currentThread())
print(n)
await asyncio.sleep(2)
print('Hello again! (%s)' % threading.currentThread())
start = time.time()
loop = asyncio.get_event_loop()
# 3个coroutine是由同一个线程并发执行的。
tasks = [hello(3), hello(6), hello(7)]
# 一组的时候要加wait
# timeout指定超时
loop.run_until_complete(asyncio.wait(tasks, timeout=10))
loop.close()
print('time:', time.time() - start)
print('time打印的时间肯定远远低于3s!,但是我们执行了3个sleep(1)(耗时1s以上的函数)的操作')
|
6ab468dc6d9364874608798e597e819875731892 | 425776024/Pythonic | /2.删除重复元素,保持顺序不变.py | 1,776 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Site :
# @File : 2.删除重复元素,保持顺序不变.py
def dedupe_iter(items):
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
a = [5, 5, 2, 1, 9, 1, 5, 10]
print(a)
print(list(dedupe_iter(a)))
it = dedupe_iter(a)
while True:
try:
c = next(it)
print(c, end='//')
except Exception as e:
print(e)
break
# 复杂对象去重复
def buha(items, key=None):
seen = set()
for item in items:
# print(seen)
val = item if key is None else key(item)
if val not in seen:
yield item
seen.add(val)
a = [{'x': 2, 'y': 3}, {'x': 1, 'y': 4},
{'x': 2, 'y': 3}, {'x': 10, 'y': 15}]
print(a)
print(list(buha(a, key=lambda x: (x['x'], x['y']))))
# 自定义哈希
class Foo:
def __init__(self, name, count):
self.name = name
self.count = count
def __hash__(self):
# 当两个变量的哈希值不相同时,就认为这两个变量是不同的。
return hash(self.count)
def __eq__(self, other):
# 当两个变量哈希值一样时,调用__eq__方法,比较是否具有相同的各种属性,可以简单地理解为值是否相等
# self是存在的一方对象,other是新来的和存在的冲突的对象
if self.count == other.count:
# if self.__dict__ == other.__dict__:
return True
else:
return False
def __repr__(self, ):
return 'print:%s' % (self.name)
f1 = Foo('f1', 1)
f2 = Foo('f2', 2)
f3 = Foo('f3', 3)
f4 = Foo('f4', 3)
f5 = Foo('f5', 3)
f6 = Foo('f6', 3)
ms = [f1, f2, f3, f4, f5, f6]
print(set(ms))
|
16ac851a482a7c06c1a705cc1c73fcd8c543b555 | anudeeptreddy/ctci | /Ch4_Trees_And_Graphs/02_minimal_tree.py | 729 | 4.0625 | 4 |
def in_order(bst):
# in order traversal of a binary search tree
if not bst:
return
in_order(bst.left)
print bst.data
in_order(bst.right)
def minimal_height_bst(sorted_array):
if len(sorted_array) == 0:
return None
middle = len(sorted_array) // 2
left = minimal_height_bst(sorted_array[:middle]) # middle not included
right = minimal_height_bst(sorted_array[(middle+1):])
return Node(sorted_array[middle], left, right)
class Node:
def __init__(self, data, left, right):
self.data, self.left, self.right = data, left, right
if __name__ == '__main__':
sorted_array = [1, 2, 3, 4, 5, 6, 7]
bst = minimal_height_bst(sorted_array)
in_order(bst)
|
923b8c5dcd7f3dfc8ccbb5b80fc1250edf141c84 | anudeeptreddy/ctci | /Ch3_Stacks_And_Queues/02_stack_min.py | 1,748 | 3.9375 | 4 |
class Node:
def __init__(self, value, min_val):
self.value = value
self.min_val = min_val
class MinStack:
def __init__(self):
self.items = []
self.min = None
def __str__(self):
return ' '.join([str(node.value) for node in self.items])
def push(self, item):
if not self.min: # stack is empty
self.min = item
else: # stack is non empty
self.min = item if item <= self.min else self.min
node = Node(item, self.min)
self.items.append(node)
def pop(self):
if self.is_empty():
raise RuntimeError('Cannot pop from an empty stack')
item = self.items.pop()
return item
def top(self):
if self.is_empty():
raise RuntimeError('Cannot provide top element in an empty stack')
return self.items[-1]
def is_empty(self):
return len(self.items) == 0
def min_value(self):
return self.top().min_val
if __name__ == '__main__':
minstack = MinStack()
minstack.push(5)
print '%s is min in stack %s' % (minstack.min_value(), minstack)
minstack.push(6)
print '%s is min in stack %s' % (minstack.min_value(), minstack)
minstack.push(3)
print '%s is min in stack %s' % (minstack.min_value(), minstack)
minstack.push(7)
print '%s is min in stack %s' % (minstack.min_value(), minstack)
minstack.pop()
print '%s is min in stack %s' % (minstack.min_value(), minstack)
minstack.pop()
print '%s is min in stack %s' % (minstack.min_value(), minstack)
# o/p:
# 5 is min in stack 5
# 5 is min in stack 5 6
# 3 is min in stack 5 6 3
# 3 is min in stack 5 6 3 7
# 3 is min in stack 5 6 3
# 5 is min in stack 5 6
|
bcdd34865c6780d422652fa822ca3ff818979217 | anudeeptreddy/ctci | /Ch2_Linked_Lists/02_kth_to_last.py | 818 | 3.875 | 4 | from LinkedList import LinkedList
def kth_element_recursion(current, position):
if current is None:
return 0, None
index, kth_value = kth_element_recursion(current.next, position)
index += 1
if index == position:
kth_value = current.value
return index, kth_value
def kth_element_runner(ll, position):
if ll.head is None:
return None
current = ll.head
runner = ll.head
counter = 1
while current.next:
counter += 1
if counter > position:
runner = runner.next
current = current.next
return runner.value if counter >= position else None
if __name__ == '__main__':
ll = LinkedList()
ll.generate(20, 1, 20)
print ll
print kth_element_recursion(ll.head, 4)[1]
print kth_element_runner(ll, 4) |
afda6bccb0538ce637a4f94b62eb533c6a2401e3 | anudeeptreddy/ctci | /Ch2_Linked_Lists/08_loop_detection.py | 627 | 4 | 4 | from LinkedList import LinkedList
def loop_detection(ll):
fast = slow = ll.head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast is slow:
break
if fast is None or fast.next is None: # no loop
return None
slow = ll.head
while fast is not slow:
fast = fast.next
slow = slow.next
return fast
if __name__ == '__main__':
ll = LinkedList([3, 1, 5, 9, 7, 2, 1])
count = 3
current = ll.head
for i in range(count):
current = current.next
ll.tail.next = current
print loop_detection(ll)
|
30f88d737655de27739242328675c6dd775421b3 | Nadeemk07/Python-Examples | /Arrays/rotation_sum.py | 762 | 4.03125 | 4 | '''Python program to find maximum value of Sum(i*arr[i])'''
# returns max possible value of Sum(i*arr[i])
def maxSum(arr):
# stores sum of arr[i]
arrSum = 0
# stores sum of i*arr[i]
currVal = 0
n = len(arr)
for i in range(0, n):
arrSum = arrSum + arr[i]
currVal = currVal + (i*arr[i])
# initialize result
maxVal = currVal
# try all rotations one by one and find the maximum
# rotation sum
for j in range(1, n):
currVal = currVal + arrSum-n*arr[n-j]
if currVal > maxVal:
maxVal = currVal
# return result
return maxVal
# test maxsum(arr) function
arr = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print("Max sum is: ", maxSum(arr))
|
9e43c6b0f91d8b46d8cb747266440460d1f4008b | Nadeemk07/Python-Examples | /Arrays/sort.py | 182 | 3.671875 | 4 | def combine_array():
arr1 = [1, 2, 3]
arr2 = [4, 5, 1]
final_array = arr1+arr2
print(final_array)
a = final_array.sort()
print(a)
combine_array()
|
855bf744bf1ad10b2cd99790bb30017ab64ae3b1 | Nadeemk07/Python-Examples | /Arrays/array_rotate.py | 546 | 3.890625 | 4 | # rotating element By d
def rotation(arr, n, d):
for i in range(0, d):
rotate_by_one(arr, n)
# rotating element one by one
def rotate_by_one(arr, n):
temp = arr[0]
for i in range(0, n-1):
arr[i] = arr[i+1]
arr[n-1] = temp
# Printing the rotated array
def rotated_array(arr, n):
for i in range(n):
print(arr[i], end=" ")
# checking with same output
arr = [1, 2, 3, 4, 5, 6, 7]
rotation(arr, 7, 3)
rotate_by_one(arr, 7)
rotated_array(arr, 7)
# TC=O(N*D) SC=O(1)
|
cf38d3bf5f83a42c436e46a934f2557763ab0ff4 | utkarsht724/Pythonprograms | /Replacestring.py | 387 | 4.65625 | 5 | #program to replace USERNAME with any name in a string
import re
str= print("Hello USERNAME How are you?")
name=input("Enter the name you want to replace with USERNAME :") #taking input name from the user
str ="Hello USERNAME How are you?"
regex =re.compile("USERNAME")
str = regex.sub(name,str) #replace Username with input name by using regular expression
print(str)
|
f81f22047a6538e19c1ef847ef365609646ed2df | utkarsht724/Pythonprograms | /Harmonicno.py | 296 | 4.46875 | 4 | #program to display nth harmonic value
def Harmonic(Nth):
harmonic_no=1.00
for number in range (2,Nth+1): #iterate Nth+1 times from 2
harmonic_no += 1/number
print(harmonic_no)
#driver_code
Nth=int(input("enter the Nth term")) #to take Nth term from the user
print(Harmonic(Nth)) |
ad856fa96d1ea81585eb68df6b7398c2edec1625 | noelster/Pythonify | /111.py | 129 | 3.84375 | 4 | def pow(b, p):
y = b ** p
return y
def square(x):
a = pow(x, 2)
return a
n = 5
result = square(n)
print(result) |
5d353c9f31d56c0cca68e69d83735f2fce5190df | Manpreet-Bhatti/TicBlack | /Blackjack.py | 1,677 | 3.859375 | 4 | class Player(object):
def __init__(self, bank = 1000):
self.bank = bank
def addbet(self, bet):
self.bank += bet*2
def minusbet(self, bet):
self.bank -= bet
def __str__(self):
return "Your bank is currently at %x" %(self.bank)
game = Player()
game.addbet(20)
game.bank
import random
class Player(object):
def __init__(self, bank = 1000):
self.bank = bank
def addbet(self, bet):
self.bank += bet*2
def minusbet(self, bet):
self.bank -= bet
def __str__(self):
return "Your bank is currently at %s" %(self.bank)
l = Player()
def start():
print l
while True:
howmuchbet = raw_input("How much would you like to bet? Please either input: 1, 5, 10, 25, or 100 ")
if howmuchbet != 1 or howmuchbet != 5 or howmuchbet != 10 or howmuchbet != 25 or howmuchbet != 100:
print "Dealing..."
for x in range(1):
print "You have been dealt a " ,random.randint(1,11)
break
else:
print "Try again - Input either: 1, 5, 10, 25, 100 "
continue
while True:
standorhit = raw_input("Now, would you like to stand or hit? ").lower()
if standorhit == 'stand':
break
elif standorhit == 'hit':
for x in range(1):
print 'You have been dealt a ' ,random.randint(1,11)
break
else:
print 'Try again - Would you like to stand or hit?'
continue
start()
|
0ac48d4f34a86f4cd2e279ac41c96d8f393a37d2 | joel99/GP_Titanic_Classifier | /primitives.py | 1,286 | 3.828125 | 4 | # Some place for primitives
# [bool, float, float] -> float
def if_then_else(input, output1, output2):
return output1 if input else output2
# [float, float] -> bool
def is_greater(input1, input2):
return input1 > input2
def is_equal_to(input1, input2):
return input1 == input2
def relu(input1):
return input1 if input1 > 0 else 0
# Wrappers
# [float, float] -> float
def safe_division(input1, input2):
if absolute(input2) < 1: # Prevent explosions
return input1
return input1 / input2
# [float] -> float
def absolute(input1):
return input1 if input1 > 0 else -1 * input1
# [float] -> float
def cube(input1): # Putting in pow is too much, system can't use safely
return input1 ** 3
# [float, int] -> float
def safe_pow(input1, input2):
if input1 <= 0:
return 0
return input1 ** min(input2, 4)
# Complex operators
# Forced if_then_else
# NEGATIVE EFFECT
# [bool, bool, float, float] -> float
def equal_conditional(input1, input2, output1, output2):
return output1 if is_equal_to(input1, input2) else output2
# In range check
# [float, float, float] -> bool
def in_range(input1, input2, input3):
return is_greater(input1, input2) and is_greater(input3, input1) |
8746ea471667d7ee618b23ffda91418bd80318b2 | ramthiagu/interviewcake | /exercise_3.py | 2,719 | 3.578125 | 4 | #!/usr/bin/env python
import unittest
import copy
def highest_product(array_of_ints):
new_array_of_ints = sort_array_of_ints(copy.deepcopy(array_of_ints))
if is_count_of_top_n_numbers_even(3,new_array_of_ints):
return reduce(lambda x,y: x * y, get_top_n_numbers(3,(new_array_of_ints)))
else:
return reduce(lambda x,y: x * y, get_top_n_numbers(3,remove_first_negative_number((new_array_of_ints))))
def sort_array_of_ints(array_of_ints):
return sorted(array_of_ints, key=abs)
def get_top_n_numbers(n, array_of_ints):
return array_of_ints[-n:]
def is_negative(n):
if n < 0:
return True
else:
return False
def is_count_of_top_n_numbers_even(n, array_of_ints):
sorted_ints = sort_array_of_ints(array_of_ints)
top_n_numbers = sorted_ints[-n:]
counter = 0
for num in top_n_numbers:
if num < 0:
counter += 1
if counter % 2 == 0:
return True
else:
return False
def remove_first_negative_number(array_of_ints):
new_array_of_ints = copy.deepcopy(array_of_ints)
for i, elem in enumerate(new_array_of_ints):
if is_negative(elem):
del new_array_of_ints[i]
break
return new_array_of_ints
class TestHighestProduct(unittest.TestCase):
def test_highest_product(self):
test_numbers = [1,8,5,9,7]
test_numbers2 = [-10,-10,1,3,2]
self.assertEqual(highest_product(test_numbers), 504)
self.assertEqual(highest_product(test_numbers2), 300)
def test_sorted_array_of_ints(self):
test_numbers = [1,8,5,9,7]
test_numbers2 = [2,-300,4,5]
self.assertEqual([1,5,7,8,9],sort_array_of_ints(test_numbers))
self.assertEqual([2,4,5,-300], sort_array_of_ints(test_numbers2))
def test_get_top_n_numbers(self):
test_numbers = [1,5,7,8,9]
self.assertEqual([7,8,9],get_top_n_numbers(3, test_numbers))
def test_number_if_negative(self):
self.assertTrue(is_negative(-1))
self.assertFalse(is_negative(1))
def test_count_of_top_3_numbers_is_even(self):
self.assertTrue(is_count_of_top_n_numbers_even(3,[0,1,2,3,-4,-5]))
def test_remove_first_negative_number(self):
test_numbers = [1,2,3,4,5,-6,7]
test_numbers2 = [1,2,3,4,-5,-6,-7]
self.assertEqual(remove_first_negative_number(test_numbers), [1,2,3,4,5,7])
self.assertEqual(remove_first_negative_number(test_numbers2), [1,2,3,4,-6,-7])
if __name__ == "__main__":
array_of_ints = [6,25,1,5,7,8,9]
print "Array of ints: " + ",".join(str(elem) for elem in array_of_ints)
print "Product: {highest_product}".format(highest_product=highest_product(array_of_ints))
|
6727f7bfbdbc29109f02075fcd102ddebf658c14 | dinis-it/boilerplate-time-calculator | /time_calculator.py | 4,473 | 4 | 4 | def add_time(start, duration, startingDay = None):
splitList = start.split(':') # Aux list to store start time in tuple, time separated by hours and minutes + period
startInfo = (splitList[0], splitList[1].split()[0], splitList[1].split()[1]) # Tuple with (hours,minutes,period)
# print(startInfo)
addInfo = tuple(duration.split(':')) # Tuple with (hours, minutes) to add to the start time
# Stores ints corresponding to starting time, accounts for both periods of the day
if 'AM' in startInfo:
if int(startInfo[0]) == 12:
startHours = 0 # 12 AM corresponds to 0 total starting hours
startMinutes = int(startInfo[1])
else:
startHours = int(startInfo[0])
startMinutes = int(startInfo[1])
elif 'PM' in startInfo:
if int(startInfo[0]) == 12:
startHours = 12 # 12 PM corresponds to 12 total starting hours
startMinutes = int(startInfo[1])
else:
startHours = int(startInfo[0]) + 12 # Sum 12 to the total to account for the past first half of the day
startMinutes = int(startInfo[1])
# print(startHours,startMinutes)
# Stores ints for total hours and total minutes separately for later addition
addHours = int(addInfo[0])
addMinutes = int(addInfo[1])
# print(addHours,addMinutes)
# Calculate total hours and total minutes separately, without converting extra minutes yet
totalHours = startHours + addHours
totalMinutes = startMinutes + addMinutes
#print(totalHours,totalMinutes)
# Calculate remainder telling us the final minutes to be displayed after conversion of minutes over 59 to hours
finalMinutes = totalMinutes % 60
# Pad final minutes to be displayed with a 0 for when they're less than 10
finalMinutesStr = str(finalMinutes).zfill(2)
# Calculate no. of hours to add from minutes over 59, add to total hours
finalTotalHours = totalMinutes // 60
finalTotalHours += totalHours
#print(finalTotalHours,finalMinutes)
# Calculate no. of days past after duration is added to the starting hour
finalHours24 = finalTotalHours % 24
extraDays = finalTotalHours // 24
#print(extraDays)
#print(finalHours24,extraDays)
# Convert hours to 12 hour format
if finalHours24 < 12:
if finalHours24 == 0:
finalHours12 = '12' #
else:
finalHours12 = str(finalHours24)
dayHalf = 'AM'
else:
if finalHours24 == 12:
finalHours12 = '12'
else:
finalHours12 = str(finalHours24 - 12)
dayHalf = 'PM'
# Check if day is the same, prepare part of final string, empty if the day is the same.
if extraDays == 0:
printExtraDays = ''
elif extraDays == 1:
printExtraDays = ' (next day)'
else:
printExtraDays = f' ({extraDays} days later)'
# Tuple containing str with resulting day of the week in case starting day was provided, and an empty string otherwise
weekDays = (', Monday',', Tuesday',', Wednesday',', Thursday',', Friday',', Saturday',', Sunday','')
dayIndex = 7 # Case where starting day was not provided
# Calculates index by using remainder of division by 7 to know the day of the week. Necessary in case duration is longer than a week.
# 0 is Monday, 1 is Tuesday until 6 - Sunday
# Final index goes from 0-6
if startingDay is not None:
if startingDay.lower() == 'monday':
dayIndex = ((0 + extraDays) % 7)
elif startingDay.lower() == 'tuesday':
dayIndex = ((1 + extraDays) % 7)
elif startingDay.lower() == 'wednesday':
dayIndex = ((2 + extraDays) % 7)
elif startingDay.lower() == 'thursday':
dayIndex = ((3 + extraDays) % 7)
elif startingDay.lower() == 'friday':
dayIndex = ((4 + extraDays) % 7)
elif startingDay.lower() == 'saturday':
dayIndex = ((5 + extraDays) % 7)
elif startingDay.lower() == 'sunday':
dayIndex = ((6 + extraDays) % 7)
# print(dayIndex)
weekDay = weekDays[dayIndex] # Assigns correct week day of result or nothing if starting day was not provided
# Format final string to be returned
new_time = f'{finalHours12}:{finalMinutesStr} {dayHalf}' + weekDay + printExtraDays
return new_time
# return new_time
|
2ec335a44a4f6b50185252eebe8460c3d3f37c6f | KiloBravo77/python_code | /countdown_timer.py | 328 | 3.796875 | 4 | import time
timer_max = int(input("Set timer: "))
for x in range(timer_max):
print(str(timer_max - x))
time.sleep(1)
print("TIME IS UP!!!!!!!!!!!!!!!")
'''
print("5")
time.sleep(1)
print("4")
time.sleep(1)
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
print("BOOOOOOOOOOOM!!!!!!!!!!!!!!!")
''' |
ceb136907c54a752da1c1be2944f25282b35b6d9 | KiloBravo77/python_code | /pig_latin.py | 741 | 3.984375 | 4 | print("Pig Latin Converter")
original = input("Enter a word: ")
if len(original) > 0 and original.isalpha():
word = original.lower()
first_letter = word[0]
second_letter = word[1]
if first_letter == 'a' or first_letter == 'e' or first_letter == 'i' or first_letter == 'o' or first_letter == 'u':
pig_word = word + 'way'
elif second_letter != 'a' and second_letter != 'e' and second_letter != 'i' and second_letter != 'o' and second_letter != 'u' and second_letter != 'y':
pig_word = word[2:] + first_letter + second_letter + 'ay'
else:
if second_letter == 'y':
pig_word = 'i' + word[2:] + first_letter + 'ay'
else:
pig_word = word[1:] + first_letter + 'ay'
print(pig_word)
else:
print("That ain't a word you dummy!") |
1ef034ef72b6b91ce392b889c10f4b7129996018 | jlat07/Python.ScientificCalculator | /calctests.py | 3,075 | 3.65625 | 4 | import unittest
from calculator import Calculator
class TestStringMethods(unittest.TestCase):
def test_add(self):
c = Calculator()
self.assertEqual(c.add(3, 3), 6)
def test_add2(self):
c = Calculator()
self.assertEqual(c.add(12, -10), 2)
def test_add3(self):
c = Calculator()
self.assertEqual(c.add(5, 8), 13)
def test_sub(self):
c = Calculator()
self.assertEqual(c.subtract(9, 3), 6)
def test_multiply(self):
c = Calculator()
self.assertEqual(c.mutiply(9, 3), 27)
def test_divide(self):
c = Calculator()
self.assertEqual(c.divide(12, 3), 4)
def test_square(self):
c = Calculator()
self.assertEqual(c.square(3), 9)
def test_exp(self):
c = Calculator()
self.assertEqual(c.exp(2, 3), 8)
def test_square_root(self):
c = Calculator()
self.assertEqual(c.square_root(9), 3)
def inv(self):
c = Calculator()
self.assertEqual(c.inv(4), 0.25)
def sine(self):
c = Calculator()
self.assertEqual(c.sine(30), -0.98803162409)
def sine(self):
c = Calculator()
self.assertEqual(c.sine(math.degree(30)), 0.5)
def cosine(self):
c = Calculator()
self.assertEqual(c.cosine(60), -0.98803162409)
def cosine(self):
c = Calculator()
self.assertEqual(c.cosine(math.degree(60)), 0.5)
def tangent(self):
c = Calculator()
self.assertEqual(c.tagent(45), 1.61977519054)
def tangent(self):
c = Calculator()
self.assertEqual(c.tagent(math.degree((45)), 1))
def invSin(self):
c = Calculator()
self.assertEqual(c.invSin(0.5), 0.52359878)
def invSin(self):
c = Calculator()
self.assertEqual(c.invSin(math.degree(0.5)), 30)
def invCos(self):
c = Calculator()
self.assertEqual(c.invCos(0.5), 1.04719755)
def invCos(self):
c = Calculator()
self.assertEqual(c.invCos(math.degree(0.5)), 60)
def invTan(self):
c = Calculator()
self.assertEqual(c.invSin(1), 0.78539816)
def invTan(self):
c = Calculator()
self.assertEqual(c.invSin(math.degree(1)), 45)
def switch_sign(self):
c = Calculator()
self.assertEqual(c.swith_sign(2), -2)
def factorial(self):
c = Calculator()
self.assertEqual(c.factorial(math.facotrial(4), 24))
def log_base_10(self):
c = Calculator()
self.assertEqual(c.log_base_10(math.log10(100), 2))
def inv_base_10(self):
c = Calculator()
self.assertEqual(c.inv_base_10(2), 100)
def log_base_e(self):
c = Calculator()
self.assertEqual(c.log_base_e(2.718281828), 1)
def inv_base_e(self):
c = Calculator()
self.assertEqual(c.inv_base_e(math.exp(1)), 2.718281828)
def log_base_y(self):
c = Calculator()
self.assertEqual(c.log_base_y(log(4, 2)), 2)
if __name__ == '__main__':
unittest.main()
|
5b74b55cbc8f0145d125993fc7ac34702d8954f7 | rawatrs/rawatrs.github.io | /python/prob1.py | 819 | 4.15625 | 4 | sum = 0
for i in range(1,1000):
if (i % 15 == 0):
sum += i
elif (i % 3 == 0):
sum += i
elif (i % 5 == 0):
sum += i
print "Sum of all multiples of 3 or 5 below 1000 = {0}".format(sum)
'''
**** Consider using xrange rather than range:
range vs xrange
The range function creates a list containing numbers defined by the input. The xrange function creates a number generator. You will often see that xrange is used much more frequently than range. This is for one reason only - resource usage. The range function generates a list of numbers all at once, where as xrange generates them as needed. This means that less memory is used, and should the for loop exit early, there's no need to waste time creating the unused numbers. This effect is tiny in smaller lists, but increases rapidly in larger lists.
'''
|
bdf8ab8ce51fc3cc31505e0addbbf199084e8abb | kosigz/DiabetesPatientReadmissionClassifier | /classifier/znorm.py | 610 | 3.546875 | 4 | # decorator to z-normalize the input data of a functions
# input function arguments: self, X, Y
# output function arguments: self, X, Y, normalize
def znorm_dec(fn):
def znorm_fn(self, X, Y):
X, normalize = znorm(X)
return fn(self, X, Y, normalize)
return znorm_fn
# perform z-score normalization on the dataset, providing the normalization
# function to be used on test points
def znorm(X):
stdev = X.std(axis=0)
stdev[stdev == 0] = 1 # replace 0s with 1s for division
mean = X.mean(axis=0)
normalize = lambda x: (x - mean) / stdev
return normalize(X), normalize |
6936a4fbce24ffa6be02883497224eb0fc6ad7e5 | nirmalshajup/Star | /Star.py | 518 | 4.5625 | 5 | # draw color filled star in turtle
import turtle
# creating turtle pen
t = turtle.Turtle()
# taking input for the side of the star
s = int(input("Enter the length of the side of the star: "))
# taking the input for the color
col = input("Enter the color name or hex value of color(# RRGGBB): ")
# set the fillcolor
t.fillcolor(col)
# start the filling color
t.begin_fill()
# drawing the star of side s
for _ in range(5):
t.forward(s)
t.right(144)
# ending the filling of color
t.end_fill()
|
71fb8c00547fb699029b1dae39b7cddcb5e7b2c7 | theetje/Twitter-Analyzer | /Analyzer/Classes/TweetAnalyzer.py | 841 | 3.5 | 4 | from datetime import datetime
class TweetAnalyzer(object):
"""docstring for [object Object]."""
""" Geef de datem terug vanuit een ms time. """
def getDateFromMSTime(timestamp_ms):
s = int(timestamp_ms) / 1000.0
return datetime.fromtimestamp(s)
""" Geef het sentiment van een tweet terug als een dict. """
def getSentiment(tweet, positive_list, negative_list):
print(tweet['text'])
words_in_tweet = tweet['text'].split() # Stop de worden in een list
date = TweetAnalyzer.getDateFromMSTime(tweet['timestamp_ms'])
positive_words = len(set(words_in_tweet) & set(positive_list))
negative_words = len(set(words_in_tweet) & set(negative_list))
return {date : { "positive_words" : positive_words,
"negative_words" : negative_words }}
|
9bf123a9cf95c8c258fef91e7a16d6cc9e639aff | jdavis24/guipw | /guipw/guipw.py | 879 | 3.8125 | 4 | #! /usr/bin/python3
from tkinter import *
root = Tk()
root.title('gui password test')
# initialize some variables needed below
namevar = StringVar()
passvar = StringVar()
displayvar = StringVar()
# create username/password labels and text boxes
label_name = Label(root, text='username:')
label_pass = Label(root, text='password:')
entry_name = Entry(root, textvariable=namevar)
entry_pass = Entry(root, textvariable=passvar)
label_name.grid(row=0)
label_pass.grid(row=1)
entry_name.grid(row=0, column=1)
entry_pass.grid(row=1, column=1)
# create a label to display entered values for testing
def display():
label_display = Label(root, text=namevar, fg='blue', textvariable=namevar)
label_display.grid(row=3, column=1)
print (namevar)
# create a button to save
button_submit = Button(text='Submit', command=display)
button_submit.grid(row=3, column=0)
root.mainloop()
|
cd03b7b76bfb8c217c0a82b3d48321f8326cc017 | jnassula/calculator | /calculator.py | 1,555 | 4.3125 | 4 | def welcome():
print('Welcome to Python Calculator')
def calculate():
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for substraction
* for multiplication
/ for division
** for power
% for modulo
''')
number_1 = int(input("Enter your first number: "))
number_2 = int(input("Enter your second number: "))
#Addition
if operation == '+':
print(f'{number_1} + {number_2} = ')
print(number_1 + number_2)
#Subtraction
elif operation == '-':
print(f'{number_1} - {number_2} = ')
print(number_1 - number_2)
#Multiplication
elif operation == '*':
print(f'{number_1} * {number_2} = ')
print(number_1 * number_2)
#Division
elif operation == '/':
print(f'{number_1} / {number_2} = ')
print(number_1 / number_2)
#Power
elif operation == '**':
print(f'{number_1} ** {number_2} = ')
print(number_1 ** number_2)
#Modulo
elif operation == '%':
print(f'{number_1 % number_2} = ')
print(number_1 % number_2)
else:
print('You have not typed a valid operator, please run the program again.')
again()
def again():
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.''')
if calc_again.upper() == 'Y':
calculate()
elif calc_again.upper() == 'N':
print('See you later.')
else:
again()
welcome()
calculate()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.