blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d0232f188cd2dc1505fa57d3bc48e6c12515cd73 | xiaoluome/algorithm | /Week_01/id_3/recursion/101/test_101.py | 675 | 3.71875 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def build(nums):
if not nums:
return None
return build_node(nums, 1)
def build_node(nums, i):
if len(nums) < i or nums[i-1] is None:
return None
node = TreeNode(nums[i-1])
node.left = build_node(nums, 2 * i)
node.right = build_node(nums, 2 * i + 1)
return node
import lc_101_v1
import lc_101_v2
import lc_101_v3
# f = lc_101_v1.is_symmetric
f = lc_101_v2.is_symmetric
# f = lc_101_v3.is_symmetric
def check(nums):
print(f(build(nums)))
check([1, 2, 2, 3, 4, 4, 3])
check([1, 2, 2, None, 3, None, 3])
|
38b2a6418f232a88692f615946a99fa9cea0bf1f | pramodhsingh/python | /08_Table-Dynamic.py | 315 | 3.625 | 4 | import os
os.system('cls||clear')
a = int(input("***Print Table of a Number***\n\nEnter a Number: "))
b = int(input("Enter increment: "))
if (b==0 | b<a):
print("\nInvalid Range, pleas try again...")
for a in range(a,b+1):
for i in range(1,11):
print(a, "x",i ,"=", a*i)
print('\t') |
7b0cbdc232fcb050c30cf72d8c81ba1d20c77927 | AnthonyRivers/CS136_Lab | /lab_10/Lab10_Antonio_Rios_Searching_and_Sorting_Algorithms.py | 3,423 | 3.84375 | 4 | # Antonio Rios
# April 17, 2015
# CS 136 Lab
# LAB 10: Searching and Sorting Algorithms
#
# This lab provides an opportunity to get an
# understanding of how to perform some basic
# profiling, i.e. you will measure the execution
# time of some searching and sorting algorithms
# that we covered in class.
# -------------------------------------------------------------
import random
import time
def linear_search(data, item):
counter = 0
for elem in data:
counter += 1
if elem == item:
return True, counter-1, counter
# This line only executes after the for loop is finished
return False, None, counter
def binary_search(lst, to_find):
count = 0
low = 0
high = len(lst) - 1
while low <= high:
count += 1
mid = (low + high) // 2
found = lst[mid]
if found == to_find:
return True, mid, count
if found < to_find:
low = mid + 1
else:
high = mid - 1
return False, None, count
#--- Problem 1- Comparing execution times of Insertion vesus Selection Sort ------#
def selection_sort(in_list):
#swap as an inner function
def swap(in_list, index_a, index_b):
tmp = in_list[index_a]
in_list[index_a] = in_list[index_b]
in_list[index_b] = tmp
for lower_index in range(len(in_list) - 1):
min_index = lower_index
for compare_index in range(lower_index+1, len(in_list)):
if in_list[min_index] > in_list[compare_index]:
min_index = compare_index
swap(in_list, min_index, lower_index)
def insertion_sort(in_list):
for index in range(1, len(in_list)):
current_value = in_list[index] # save the value, as it may be overwritten
sorted_index = index - 1
# keep swapping the current value until you run into something lower
while sorted_index >= 0 and in_list[sorted_index] > current_value:
in_list[sorted_index+1] = in_list[sorted_index]
sorted_index -= 1
in_list[sorted_index+1] = current_value
def main():
# Problem 1
start = time.clock()
insertion_sort(list(range(10000, 0, -1)))
end = time.clock()
print("It took", end-start, "seconds to insertion sort the list.")
start = time.clock()
selection_sort(list(range(10000, 0, -1)))
end = time.clock()
print("It took", end-start, "seconds to selection sort the list.")
# Problem 2
# Variable used to store times for binary search
binary_avg = 0
for i in range(100):
start = time.clock()
binary_search(list(range(1, 100001)), random.randint(1, 100000))
end = time.clock()
# Adds to total time variable
binary_avg += end-start
# Compute average
binary_avg /= 100
print("The average time for binary search was", binary_avg)
# Variable used to store times for linear search
linear_avg = 0
for i in range(100):
start = time.clock()
linear_search(list(range(1, 100001)), random.randint(1, 100000))
end = time.clock()
# Adds to total time variable
linear_avg += end-start
# Compute average
linear_avg /= 100
print("The average time for linear search was", linear_avg)
print("Binary search outperformed linear search by a ratio of", linear_avg/binary_avg)
if __name__ == "__main__":
main()
|
6bc09d62e8075e840edfd2cf1d741b14af0f514f | EwertonBar/CursoemVideo_Python | /mundo03/aulas/aula017c.py | 238 | 4.03125 | 4 | valores = list()
for v in range (0,5):
valores.append(int(input('Digite um valore: ')))
for c, v in enumerate(valores):
print(f'Na posição {c} encontrei o valor {v}.')
print('Cheguei no final da lista.')
print(valores) |
8ef28d0af8f5986f795cab9c3e7b0dcc481d740e | nataliegarate/python_ds | /trees/k_dist_from_root.py | 1,092 | 3.765625 | 4 | # iterative
def findKNodes(root, k):
if root is None:
return None
def findKNodes(root, k):
results = []
queue = [{'node': root, 'order': 0}]
while len(queue) > 0:
cur = queue.pop(0)
if cur['order'] == k:
results.append(cur['node'].val)
continue
if (cur['node'].leftChild != None):
queue.append(
{'node': cur['node'].leftChild, 'order': cur['order'] + 1})
if (cur['node'].rightChild != None):
queue.append(
{'node': cur['node'].rightChild, 'order': cur['order'] + 1})
return results
return findKNodes(root, k)
# recursive
# def findKNodes(root, k):
# def addNodes(root, k, num, arr):
# if root is None:
# return arr
# if k == num:
# arr.append(root.val)
# return arr
# addNodes(root.leftChild, k, num + 1, arr)
# addNodes(root.rightChild, k, num + 1, arr)
# return arr
# return addNodes(root, k, 0, [])
|
7e55242b569a138d0af9dc6e3e3e3141586f53e2 | Rosebotics/PythonGameDesign2018 | /camp/Z_2019_Solutions/TicTacToe/Solutions/TicTacToe0.py | 1,763 | 4.34375 | 4 | # TicTacToe Version 0 - draw a bsic 3x3 grid.
# import pygame so we can use it
import pygame
# initialize constants
BOARD_SIZE = 3 # number of rows and columns
BOARD_RANGE = range(BOARD_SIZE) # range of rows and columns
PPS = 150 # pixels per square
WINDOW_SIZE = PPS * BOARD_SIZE # width and height of window
INSET = 15 # num pixels around X's and O's in squares
BLACK = (0, 0, 0) # color black
WHITE = (255, 255, 255) # color white
# Initialize global variables
screen = None # Everything is displayed in this screen, initialized in main()
def draw_grid():
'Draw the horizontal and vertical lines'
for i in range(1, BOARD_SIZE):
pygame.draw.line(screen, BLACK, (0, i*PPS), (WINDOW_SIZE, i * PPS))
pygame.draw.line(screen, BLACK, (i*PPS, 0), (i * PPS, WINDOW_SIZE))
# ----- Main Function
def main():
global screen
pygame.init() # Initialize Pygame
screen = pygame.display.set_mode((WINDOW_SIZE, WINDOW_SIZE))
pygame.display.set_caption("Tic Tac Toe version 0")
# define a variable to control the main loop
running = True
# main loop
while running:
for event in pygame.event.get(): # event handling, gets all event from the event queue
if event.type == pygame.QUIT: # only do something if the event is of type QUIT
running = False # change the value to False, to exit the main loop
screen.fill(WHITE) # Clear the screen and set the screen background
draw_grid()
pygame.display.update() # Update the screen
# quit the game when exit out the while loop
pygame.quit()
# calling main function here
main()
|
0df76c213b7c33834068c94f9ee14b4343683a3c | Nilsonsantos-s/Python-Studies | /HackerRank/11.py | 674 | 3.6875 | 4 | #
if __name__ == '__main__':
pessoas = []
pessoa = []
scores = []
penultimo = []
for x in range(int(input().strip())):
name = input().strip()
score = float(input().strip())
pessoa.append(name)
pessoa.append(score)
scores.append(score)
pessoas.append(pessoa[:])
pessoa.clear()
for x in range(scores.count(min(scores))):
scores.remove(min(scores))
scores.sort()
for x in range(scores.count(min(scores))):
penultimo.append(scores[x])
if pessoas[0][0] != 'Test1':
pessoas.reverse()
for x in pessoas:
if x[1] == penultimo[0]:
print(x[0])
|
f5fadff37aad768e66a1753fbda120dab31f1c3f | abiswas20/Computational_Programming_in_Python | /Knapsack+Graph Optimization Problems/usingGreedyAlgo.py | 1,393 | 4.15625 | 4 | ##Functions to use "greedy algorithm" to choose items. Their implementation is dependent on class 'Item' and function 'greedy'. Code is based on Fig.12.4. in John Guttag's book.##
from classItem import Item
from classItem import value,weightInverse,density
from greedyAlgorithm import greedy
def buildItems():
names=['AB','CD','EF','GH','IJ','KL','MN'] #'names','values' and 'weights' are parameters passed to class 'Item' to build each element of list 'Items'#
values=[1,2,3,4,5,6,7]
weights=[5,10,15,20,25,30,35]
Items=[] #declaring empty list#
for i in range(len(values)):
Items.append(Item(names[i],values[i],weights[i])) #'Items' is a list declared earlier in the function.'Item' is a class imported from classItem.#
return Items
def testGreedy(items,maxWeight,keyFunction):
taken,val=greedy(items,maxWeight,keyFunction)
print('total value of items taken is',val)
for item in taken:
print(' ',item)
def testGreedys(maxWeight=20):
items=buildItems()
print('Use greedy algorithm by value to fill a knapsack. maxWeight',maxWeight)
testGreedy(items,maxWeight,value)
print('Greedy algorithm by inverse of weight. maxWeight',maxWeight)
testGreedy(items,maxWeight,weightInverse)
print('Greedy algorithm by density(i.e. value:weight). maxWeight',maxWeight)
testGreedy(items,maxWeight,density)
testGreedys()
|
53cb04551d8bb6dac449acd7867a46deb7f6e688 | kbrain41/class | /stroki/stroki1.py | 201 | 3.796875 | 4 | a = "Строк бояться не нужно! Строки это всего лишь обьекты заключенные в ковычки."
p = len(a) // 2
print(a[0:p].lower() + a[p::].upper())
|
2018dbb964523d14024a55c8ccddcded176a47c1 | cccccyclone/Maleapy | /src/ex5/leacurve.py | 1,977 | 3.59375 | 4 | import sys
sys.path.append('..')
import numpy as np
from ex1.linear import *
def addOnes(x,m):
"""
Add a col of 1 at first column of x
x: the number of rows
"""
n = x.size/m
one = np.ones((m,1))
x = x.reshape((m,n))
judge = np.sum(x[:,0] == one.flatten())
if judge != m:
x = np.hstack((one,x))
return x
def leacurve(x,y,xval,yval,lamda):
"""
this function implements code to generate the learning curves that will be useful in debugging learning algorithms.
To plot the learning curve, we need a training and cross validation set error for different training set sizes.
To obtain different training set sizes,the function uses different subsets of the original training set x.
Specifically, for a training set size of i, you should use the first i examples (i.e., x(0:i) and y(0:i))
"""
m1 = y.size
m2= yval.size
x = addOnes(x,m1)
xval = addOnes(xval,m2)
m,n = x.shape
errtrain = np.zeros(m)
errval = np.zeros(m)
thetaInit = np.zeros(n)
for i in range(1,m+1):
status,theta = optimSolve(thetaInit,x[0:i],y[0:i],reg=True,lamda=lamda)
errtrain[i-1] = costFunc(theta,x[0:i],y[0:i])
errval[i-1] = costFunc(theta,xval,yval)
return errtrain, errval
def errAndLamda(x,y,xval,yval,lamdas):
m1 = y.size
m2= yval.size
x = addOnes(x,m1)
xval = addOnes(xval,m2)
nlam = lamdas.size
errtrain = np.zeros(nlam)
errval = np.zeros(nlam)
thetaInit = np.zeros(np.size(x,1))
i = 0
for lam in lamdas:
status,theta = optimSolve(thetaInit,x,y,reg=True,lamda=lam)
errtrain[i] = costFunc(theta,x,y)
errval[i] = costFunc(theta,xval,yval)
i += 1
return errtrain, errval
"""
if __name__ == '__main__':
x = np.loadtxt('x.txt')
y = np.loadtxt('y.txt')
xval = np.loadtxt('xval.txt')
yval = np.loadtxt('yval.txt')
errtrain,errval = leacurve(x,y,xval,yval,0.0)
"""
|
410d4b95329fafb4a5ecd1d6f43e8d0d46308dde | alex-ozerov/Python_starter | /007_Lists/task_1.py | 131 | 3.59375 | 4 | my_list = [1, 2, 3, 4, 5, 6, 7, 8]
print(min(my_list))
print(max(my_list))
print(sum(my_list))
print((sum(my_list))/(len(my_list))) |
83ec468a399464f462f5695f10202663b46365d8 | SarthakSingh2010/PythonProgramming | /basics/List.py | 2,708 | 4.375 | 4 | kp=list(range(10))#make a list of 0-9 using range data type
print(kp)
nums = [25,12,16,95,43]
print(nums)
print('make a copy of nums')
mp=nums.copy()
print(mp)
print('1st value ',nums[0])
print('from index 2 till last index')
print(nums[2:])
print('last 3 element')
print(nums[-3:])
print('negative indexing')
print(nums[-5])#1st element.
names=['apple','mango','orange']
print(names)
values=[6.5,'sarthak',24]
print(values)
mil=[names,values]
print(mil)
print('accessing the mil elements:')
print('1st row:')
print(mil[0])
print('2nd row')
print(mil[1])
print('1st row 2nd element')
print(mil[0][1])
#list are mutable
print('append 25 at end')
nums.append(25) #append at end
nums=nums+[25] #another way to append
print(nums)
print('count all occurances of 25')
print(nums.count(25))# count occurances of 25 in list
print('sort ascending')
nums.sort() #ascending order
nums.sort(reverse=True) #descending order
print(nums)
print('get reverse of list')
nums.reverse() #reverse the entire list
print(nums)
print('remove a element by its value')
nums.remove(16)#remove element 16
print(nums)
print('remove the last element')
nums.pop() #removes last element
print(nums)
print('remove element by index')
nums.pop(2)#remove element at index 2
print(nums)
print('Delete all element from index 2 till last "multiple deletion"')
del nums[2:]
print(nums)
print('append more than 1 element in list')
nums.extend([44,55,66,77,88,99])
print(nums)
print('index of 55')
print(nums.index(55))#error if not in list else index start from 0
print('insert 69 at index 2 in nums list')
nums.insert(2,69)
print(nums)
print('minimum ',min(nums))
print('maximum ',max(nums))
print('sumtotal ',sum(nums))
print('remove all element making it empty')
nums.clear() #clear entire list
print(nums)
#check if element is there in list or not reply as True or False
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
#List are mutable values can be changed
thislist[1]="mango"
print(thislist)
#get a 2d matrix code
print("enter content for 2d matrix")
arr=[]
for i in range(3):
k=list(map(int,input().split()))
arr.append(k)
print(arr) # thats a matrix with 3 rows
u=[1,2,3]
v=[1,2,3]
#set(u) & set(v) give intersection of 2 list as list
if len(set(u) & set (v))==len(u):
print('Lists are same')
else:
print('List are different')
print('List to string using join func')
k=['A','P','P','L','E']
print('.'.join(k))#only works for a list having str type elem
print('valid list builts')
k1=[1,2,3,4]
k2=[[1,2,3],[4,5,6],[7,8,9]]
k3=['A'+'PP','$'*3,7+4,3]
print(k1)
print(k2)
print(k3)
#convert 123 into [1,2,3]
lis=list(map(int,str(123)))
print(lis) |
e6c954556cbe0b0ea053648241e4d5255602dc1d | iKwesi/Labyrinth-Game-python | /Helpers/ILabyrinth.py | 556 | 3.578125 | 4 | from abc import ABC, abstractmethod
class ILabyrinth(ABC):
""" Interface for creating a maze object """
@abstractmethod
def generate_grid(self): pass
@abstractmethod
def find_neighbours(self, row, col): pass
@abstractmethod
def _validate_neighbours_generate(self, neighbour_indices): pass
@abstractmethod
def _pick_random_entry_exit(self, used_entry_exit = None): pass
@abstractmethod
def generate_labyrinth(self, start_coor = (0, 0)): pass
@abstractmethod
def check_monolith(self, row, col): pass |
388c0084041f974c32f4ebb0a5600c41246a8506 | Linyameng/alphadata-dev | /appbak/app/core/test1.py | 442 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on 2018/8/2
@author: xing yan
"""
# -*- coding: utf-8 -*-
# __author__="ZJL"
#a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = [{"a":1,"b":2,"c":3},{"d":4,"e":5},{"f":6,"g":7},{"h":8,"i":9}]
def fenye(datas, pagenum, pagesize):
if datas and isinstance(pagenum, int) and isinstance(pagesize, int):
return datas[((pagenum - 1) * pagesize):((pagenum - 1) * pagesize) + pagesize]
print(fenye(a, 2, 3)) |
1440519a0f3dd3c1576311823e32aa6a74ae79df | Syabz03/pythonCombinedProject | /mydata.py | 3,808 | 4.03125 | 4 | class Mydata:
"""Represents 1 day of data from Reddit or Twitter
Attributes:
topic: str
Topic being searched
source : str
"reddit" or "twitter"
date: datetime
The day which the data is for
interactionCount: int
number of upvotes/downvotes, likes
commentCount: int
number of comments for the day
topComments: List
3 of the top posts/tweets for the day
Methods:
__init__(topic, platform, date):
class constructor
addPost(text,id,url,date)
addition of a top 3 post to the day
addLikeCount(count)
cummulative addition to the interactionCount
addCommentCount(count)
cummulative addition to the commentCount
getTopComments()
returns the list of top comments
"""
topic=''
source=''
date=''
interactionCount=''
commentCount=''
topComments=''
def __init__(self,topic,platform,date):
"""class constructor
Args:
topic(str): topic that was searched for
platform(str): "reddit" or "twitter"
date(datetime): date of the search
Returns:
mydata class obj
"""
self.topic = topic
self.source = platform
self.date = date
self.interactionCount = 0
self.commentCount =0
self.topComments=[]
def addPost(self,text,id,url,date):
"""addition of a top 3 post to the day
A post obj is created then added to the list
Args:
text(str): title of the post(reddit) or content of the tweet
id(str): the unique platform id of the post/tweet
url(str): url link to the post
date(datetime): date of the post
"""
self.topComments.append(Post(text,id,url,date))
return None
def addLikeCount(self,count):
"""cummulative addition to the interactionCount
Args:
count(int): amount of interactions to be added
"""
self.interactionCount += count
return None
def addCommentCount(self,count):
"""cummulative addition to the commentCount
Args:
count(int): amount of comments to be added
"""
self.commentCount += count
return None
def getTopComments(self):
"""returns the list of top tweets/posts
Returns:
list: a list of 3 top tweets/posts
"""
return self.topComments
class Post:
"""Represents 1 post/tweet
Attributes:
text(str): tweet/post content
id(str): platform identifier for the post
url(str): link to the post
date(datetime): date of the post
"""
text = ''
id = ''
url =''
date = ''
def __init__(self, text, id, url, date):
"""class constructor
Args:
text(str): tweet/post content
id(str): platform identifier for the post
url(str): link to the post
date(datetime): date of the post
Returns:
Post class obj
"""
self.text = text
self.id = id
self.url = url
self.date = date
def getText(self):
"""returns the post text
Returns:
string: the post text
"""
return self.text
def getUrl(self):
"""returns the post url
Returns:
string: the post url
"""
return self.url
def getDate(self):
"""returns the created date of post
Returns:
date: the created date of post
"""
return self.date
|
8f33a34b87856056390294dac9e622c4d083e92a | Sixpounder87/Intel_tasks | /intel_task_1/time_converter.py | 984 | 3.71875 | 4 | import sys
def time_to_sec(s='1'):
if not isinstance(s, str):
raise TypeError('Wrong type of argument. Should be a string.')
list_of_char_digits = list(map(str, range(10)))
time_units = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}
for i in s[:-1]:
if i not in list_of_char_digits + ['.']:
raise TypeError('Wrong type of argument. Only digits are acceptable. '
'Acceptable time specifiers are \'s\', \'m\', \'h\', \'d\'')
if s[-1] in list_of_char_digits + ['.']:
return int(float(s))
elif s[-1] in time_units.keys():
return int(float(s[:-1]) * time_units.get(s[-1])) if len(s) > 1 else time_units.get(s[-1])
else:
raise TypeError('Wrong type of argument. Only digits are acceptable. '
'Acceptable time specifiers are \'s\', \'m\', \'h\', \'d\'')
if __name__ == "__main__":
var = sys.argv[1]
print(time_to_sec(var))
|
1936510a8af69ed168f6ec496a597adcb3990991 | MicheleAlladioAKAMich/Compiti_Vacanze | /ReverseString.py | 250 | 4.1875 | 4 | '''
Author: Michele Alladio
es:
Reverse a string
For example: input: "cool" output: "looc"
'''
def main():
string = input("Inserisci una stringa: ")
print(string[::-1]) #fastest way to reverse a string
if __name__ == main():
main() |
2f5210b00ce782bdca50f27ac9ee61fbff39c724 | vinamrathakv/pythonCodesMS | /CountVowelsConsonantsInFile14_11.py | 390 | 3.984375 | 4 | # count vowels and consonants in file
vowels = {"a", "e", "i", "o", "u"}
fileName = input("Enter filename to count vowels and consonants : ")
file = open(fileName, "r")
fileData = file.read()
print(len(fileData))
v = 0
c = 0
for i in fileData:
i.lower()
if i in vowels:
v += 1
else:
c +=1
print("vowels : ",v)
print("consonants : ",c )
|
b1e6429edaa1beeb6060704b6074f379c742f351 | N3CROM4NC3R/python_crash_course_exercises | /Lists/Slices/My pizzas,Your Pizzas.py | 329 | 4.25 | 4 | pizzas=["chesse pizza","cheddar pizza","detroit pizza"]
friendPizzas=pizzas[:]
pizzas.append("new york pizza")
friendPizzas.append("greek pizza")
print("My favorite pizzas are:")
for pizza in pizzas:
print(pizza)
print("My friend's favorite pizzas are:",friendPizza)
for friendPizza in friendPizzas:
print(friendPizza) |
88e27f867e1e1cd87efa6911efa299dc8f76cf21 | yshshadow/Leetcode | /151-200/190.py | 1,894 | 3.859375 | 4 | # Reverse
# bits
# of
# a
# given
# 32
# bits
# unsigned
# integer.
#
# Example
# 1:
#
# Input: 00000010100101000001111010011100
# Output: 00111001011110000010100101000000
# Explanation: The
# input
# binary
# string
# 00000010100101000001111010011100
# represents
# the
# unsigned
# integer
# 43261596, so
# return 964176192
# which
# its
# binary
# representation is 00111001011110000010100101000000.
# Example
# 2:
#
# Input: 11111111111111111111111111111101
# Output: 10111111111111111111111111111111
# Explanation: The
# input
# binary
# string
# 11111111111111111111111111111101
# represents
# the
# unsigned
# integer
# 4294967293, so
# return 3221225471
# which
# its
# binary
# representation is 10101111110010110010011101101001.
#
# Note:
#
# Note
# that in some
# languages
# such as Java, there is no
# unsigned
# integer
# type.In
# this
# case, both
# input and output
# will
# be
# given as signed
# integer
# type and should
# not affect
# your
# implementation, as the
# internal
# binary
# representation
# of
# the
# integer is the
# same
# whether
# it is signed or unsigned.
# In
# Java, the
# compiler
# represents
# the
# signed
# integers
# using
# 2
# 's complement notation. Therefore, in Example 2 above the input represents the signed integer -3 and the output represents the signed integer -1073741825.
#
# Follow
# up:
#
# If
# this
# function is called
# many
# times, how
# would
# you
# optimize
# it?
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
# built in func
# return int(bin(n)[2:].zfill(32)[::-1],2)
# bit op
cnt = 0
for _ in range(32):
# 先位移cnt再加,否则多移一次
cnt <<= 1
cnt += n & 1
n >>= 1
return cnt
s = Solution()
print(s.reverseBits((int('00000010100101000001111010011100', 2))))
|
76f2df275391acb9452fe62c9f67fbf6069ad199 | AlpineMeadow/GameOfLife | /GameOfLife.py | 5,416 | 3.578125 | 4 | #! /usr/bin/env python3
#A program to simulate The Game of Life by John Conway.
def getNeighborsState(i, j, gOL) :
#Get the inital conditions.
iup = i - 1
idown = i + 1
jleft = j - 1
jright = j + 1
currentCellState = gOL[i, j] #Either live or dead.
uleft = gOL[iup, jleft]
ucenter = gOL[iup, j]
uright = gOL[iup, jright]
cleft = gOL[i, jleft]
cright = gOL[i, jright]
lleft = gOL[idown, jleft]
lcenter = gOL[idown, j]
lright = gOL[idown, jright]
#Sum up the surrounding cells states.
liveOrDie = uleft + ucenter + uright + cleft + cright + lleft + lcenter + lright
return currentCellState, liveOrDie
#End of the function getNeighborsState.py
######################################################################################
######################################################################################
def getArgs(parser) :
import numpy as np
#Get the parameters
parser.add_argument('-nI', '--numIterations', default = 50,
help = 'Choose how many iterations are made before stopping.', type = int)
numGridPointsStr1 = ('Choose the number of grid points. ')
numGridPointsStr2 = ('This value will give numGridPoints Squared points.')
numGridPointsStr = numGridPointsStr1 + numGridPointsStr2
parser.add_argument('-nG', '--numGridPoints', default = 10, help = numGridPointsStr,
type = int)
args = parser.parse_args()
#Generate variables from the inputs.
numIterations = args.numIterations
numGridPoints = args.numGridPoints
#Generate the initial set of cells.
initialSet = np.rint(np.random.rand(numGridPoints, numGridPoints))
return initialSet, numIterations
#End of the function getArgs(parser).py
#################################################################################
#################################################################################
def getGameOfLife(gOL) :
import numpy as np
#Get the shape of the game of life array.
m, n = gOL.shape
#Allocate a new Game Of Life array.
newGOL = np.ndarray((m, n))
#Loop through the cells.
for i in range(1, m - 1) : #Do not count the outer boundary.
for j in range(1, n - 1) : #Do not count the outer boundary.
#Determine the live or die parameter for each cell.
currentCellState, liveOrDie = getNeighborsState(i, j, gOL)
#Apply the rules of the game.
#Rule #1.
if(liveOrDie < 2) :
if(currentCellState == 1) :
newGOL[i, j] = 0 #Cell dies.
else :
newGOL[i, j] = 0 #Cell dies.
#End of if(currentState == 1) : statement.
#End of if(liveOrDie < 2) : statement.
#Rule #2.
if((liveOrDie == 2) or (liveOrDie == 3)) :
if(currentCellState == 1) :
newGOL[i, j] = 1 #Cell lives.
else :
newGOL[i, j] = 0 #Cell dies
#End of if(currentCellState == 1) : statement.
#End of if((liveOrDie == 2) or (liveOrDie == 3)) : statement.
#Rule #3.
if(liveOrDie > 3) :
if(currentCellState == 1) :
newGOL[i, j] = 0 #Cell dies.
else :
newGOL[i, j] = 0 #Cell dies.
#End of if(currentCellState == 1) : statement.
#End of if(liveOrDie > 3) : statement.
#Rule #4.
if((currentCellState == 0) and (liveOrDie == 3)) :
newGOL[i, j] = 1 #Cell is born.
#End of if((currentCellState == 0) and (liveOrDie == 3)) : statement.
#End of for loop - for j in range(m) :
#End of for loop - for i in range(n) :
return newGOL
#End of the function getGameOfLife.py
#####################################################################################
#####################################################################################
#Gather our code in a main() function.
def main() :
import argparse
import matplotlib.pyplot as plt
import numpy as np
import cv2
# from moviepy.editor import VideoClip
# from moviepy.video.io.bindings import mplfig_to_npimage
#Set up the argument parser.
parser = argparse.ArgumentParser()
#Set up the location of domain to be investigated.
#Set up the number of iterations to be done on the point.
#Create a number of points. This will give numGridPoints^2 of values to be plotted.
gOL, numIterations = getArgs(parser)
#Get the shape of the domain.
m, n = gOL.shape
#Create a output file name to where the plot will be saved.
outfilepath = '/home/jdw/Computer/GameOfLife/Movies/'
filename = ('GameOfLife.mp4')
outfile = outfilepath + filename
#initialize video writer
# fourCC possibilities are DIVX, XVID, MJPG, X264, WMV2, mp4v
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Be sure to use lower case
framesPerSecond = 1
out = cv2.VideoWriter(outfile, fourcc, framesPerSecond, (m, n), True)
#Loop through the iterations.
for i in range(numIterations) :
#Get the Game Of Life set.
gOL = 255*getGameOfLife(gOL)
gray = cv2.normalize(gOL, None, 255, 0, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)
gray_3c = cv2.merge([gray, gray, gray])
out.write(gray_3c) # Write out frame to video
#End of for loop - for i in range(numIterations):
# Release everything if job is finished
# out.release()
# cv2.destroyAllWindows()
# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
main()
|
c8acc2c8b6896c28146d3e1518793c7619d54598 | daiyeyue/PythonExercise | /For/LY-04-For.py | 226 | 4 | 4 | for i in range(0,4):
for j in range(0,5):
print("*" , end=" ")
print("\t")
#简单图形打印
for i in range(0,4):
if i == 0 or i ==3 :
print("* " * 5);
else:
print("* *")
|
ebcdc63b14419b543bc777fd1c32b8ba2d31f11e | Omupadh/python3 | /Desafios/desafio071.py | 570 | 3.515625 | 4 | from math import trunc
print('=' * 37)
print('{:^37}'.format('BANCO WJ'))
print('=' * 37)
valor = int(input('Qual valor você quer sacar? R$ '))
if valor >= 50:
n50 = trunc(valor / 50)
valor = valor % 50
print(f'Total de {n50} cédulas de R$50')
if valor >= 20:
n20 = trunc(valor / 20)
valor = valor % 20
print(f'Total de {n20} cédulas de R$20')
if valor >= 10:
n10 = trunc(valor / 10)
valor = valor % 10
print(f'Total de {n10} cédulas de R$10')
if valor >= 1:
n1 = trunc(valor / 1)
print(f'Total de {n1} cédulas de R$1')
|
c3d7035598ec023f8128a622a4157e7e31ff517b | lccastro9/hkr-6 | /Point.py | 533 | 3.765625 | 4 | class Point():
def __init__(self,x,y):
self.x=x
self.y=y
def move(self,x,y):
self.x1=x
self.y1=y
def reset(self):
self.x=0
self.y=0
def calculate_distance(self,otherPoint):
a=(otherPoint.x-self.x)**2 + (otherPoint.y-self.y)**2
distancia = a**0.5
return distancia
D=[]
for i in range((int(raw_input())/2)):
D.append(Point(*map(int,raw_input().split())).Distancia(Point(*map(int,raw_input().split()))))
for i in D:
print i
|
d0ab9d001660bc65eb034a260123274b82a94ea7 | gautambp/codeforces | /1081-A/1081-A-48094617.py | 75 | 3.734375 | 4 | s = int(input())
if s == 2 or s == 1:
print(s)
else:
print(1)
|
b525c63b12b0837474ef32a6be37baa1c21615f1 | langlixiaobailongqaq/python-selenium | /Python3_Selenium3_BD/data_driven.py | 464 | 3.796875 | 4 | """
5.2、数据驱动之参数化驱动和txt文件数据驱动
"""
# coding:utf-8
from selenium import webdriver
import time
search_text = ['python', '中文', 'text']
for keys in search_text:
driver = webdriver.Chrome()
# 隐式等待
driver.implicitly_wait(10)
driver.get("https://www.baidu.com/")
driver.find_element_by_id('kw').send_keys(keys)
time.sleep(3)
driver.find_element_by_id('su').click()
time.sleep(2)
driver.quit()
|
4c2f4e9b9500fc8b2308ccf3bdbe9c789bf20de1 | padhs/py-work | /newpy-project/q17.py | 428 | 4.21875 | 4 | # adding an element to the tuple
def add_element(new_dance_form):
dance_form = ("Samba", "Tango", "Ballet", "Tap", "Modern", "Jazz", "Hip-hop")
list_dance_form = list(dance_form)
print(f"These were the given dance forms:\n {dance_form}")
list_dance_form.append(new_dance_form)
print("These are the updated dance forms: ")
print(tuple(list_dance_form))
add_element(input("Enter any one dance form: "))
|
4cd64efdbbf0a3eb06799f90d5904c735c72eddd | 240302975/study_to_dead | /面向对象/21 绑定方法与非绑定方法介绍.py | 1,091 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time :2020/1/1 21:35
"""
在类内部定义的函数,分为两大类:
一:绑定方法:绑定给谁,就应该由谁来调用,谁来调用就会把调用者当作第一参数自动传入
绑定到对象的方法:在类内定义的没有被任何装饰器修饰的
绑定到类的方法:在类内定义的被装饰器classmethod修饰的方法
二:非绑定方法:没有自动传值这么一说,就类中定义的一个普通工具,对象和类都可以使用
非绑定方法:不与类或者对象绑定
"""
class Foo:
def __init__(self, name):
self.name = name
def tell(self): # 绑定对象
print('名字是%s' % self.name)
@classmethod # 绑定到类
def func(cls):
print(cls)
@staticmethod # 非绑定方法
def func1(x, y):
print(x + y)
f = Foo('egon')
# Foo.tell(f)
# print(f.tell)
# f.tell()
# print(Foo.func) # <bound method Foo.func of <class '__main__.Foo'>>
# Foo.func()
Foo.func1(1, 2)
f.func1(1, 3)
|
ee1aa1857bf79f58397701b512a3777566dd33cd | Createitv/BeatyPython | /08-python-books/intermediate python/map,filter,reduce.py | 364 | 3.515625 | 4 | items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
print(squared)
# Output: [1, 4, 9, 16, 25]
number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)
# Output: [-5, -4, -3, -2, -1]
from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
print(product)
# Output: 24
|
e58a48c3d1220a209361319b7c66244d71899249 | croguerrero/pythonexercises | /ejercicio18.py | 547 | 3.875 | 4 | import numpy as np
n = int(input("Introduce las filas A: "))
m = int(input("Introduce las columnas A: "))
p = int(input("Introduce las columnas B: "))
A = np.empty((n,m))
print("\n=======Matriz A========")
for i in range(n):
for j in range(m):
A[i, j] = float(input("Introduce el elemento ({},{})".format(i, j)))
B = np.empty((m,p))
print("\n=======Matriz B========")
for i in range(m):
for j in range(p):
B[i, j] = float(input("Introduce el elemento ({},{})".format(i, j)))
print("\nMatriz A * B")
print(A.dot(B)) |
912446cdae226f82f8a2e1d08accb9add960ac03 | maolei1/ApiAutoTest | /day01/03.上传文件.py | 978 | 3.765625 | 4 | '''
接口的功能是上传文件,比如上传头像,附件等
'''
import requests
url = "http://www.httpbin.org/post"
file = r"D:\test.txt"
with open(file, 'r') as f:
#字典,上传的文件:文件相关参数组成的元祖
# text/plain 是文件的类型
load = {"file1": (file, f, "text/plain")}
r = requests.post(url, files = load)
#print(r.text)
#上传图片
file1 = r"D:\a.jpg"
with open(file1,'rb') as d:
load = {"file2":(file1,d,"image/jpg")}
#文件名:file-tuple
#file-tuple 可以是二元组、三元组、四元组
#img/png MIME类型,文件类型,application/json application/
r = requests.post(url,files =load)
# print(r.text)
#可以一次上传多个文件,文本和图片一起上传
with open(file,'r') as f1:
with open(file1,'rb') as f2:
load = {"file1": (file, f1, "text/plain"), "file2": (file1, f2, "image/jpg")}
r = requests.post(url, files=load)
print(r.text) |
a09634a235dbbd30908bfac185f7c6f3d38c4af5 | XxWar-MachinexX/Computer_Science_Capstone | /Weather_Station.py | 3,525 | 3.53125 | 4 | # Jose F. Pina Jr.
# Southern New Hampshire University
# CS-350 Emerging Systems Architecture & Technology
# Final Project __Weather Station__
import grovepi
import math
import json
import time
import datetime
from grovepi import *
# LED configuration
green_led = 2
blue_led = 3
red_led = 4
# Temp / humidity sensor on port 5
sensor = 5
# Grove light sensor to analog port A0
light_sensor = 0
# Record data if light detected
threshold = 20
grovepi.pinMode(light_sensor, "INPUT")
# Sensor types
blue = 0
white = 1
# Initiate LEDs
pinMode(blue_led, "OUTPUT")
pinMode(green_led, "OUTPUT")
pinMode(red_led, "OUTPUT")
counter = 0.0
time_gap = 1800
# Function to control lights
def lights(red, green, blue):
digitalWrite(red_led, red)
digitalWrite(green_led, green)
digitalWrite(blue_led, blue)
# Lights start off in the off position
lights(0,0,0)
# Creates JSON file to store data
with open("weather_station_data.json", "a") as write_file:
write_file.write('[\n')
# Main
while (True & (counter < 11)):
try:
# First parameter is port, second parameter is sensor type
[temp,humidity] = grovepi.dht(sensor, blue)
# Celsius to Fahrenheit conversion
temp = ((9 * temp) / 5) + 32
# Output variables
t = str(temp)
h = str(humidity)
# Creates data object to hold data
data = [
counter,
temp,
humidity
]
# Sensor value
sensor_value = grovepi.analogRead(light_sensor)
# Calculate resistance of sensor in K
resistance = (float)(1023 - sensor_value) * 10 / sensor_value
print("sensor_value = %d resistance = %.2f" %(sensor_value, resistance))
if (sensor_value > threshold):
# Check validity of data
if math.isnan(temp) == False and math.isnan(humidity) == False:
# Prints output to screen
print(counter)
print("temp = %.02f F humidity = %.02f%%" %(temp, humidity))
# Write output to JSON file
with open("weather_station_data.json", "a") as write_file:
json.dump(data, write_file)
counter += 0.5
if (counter < 11):
write_file.write(',\n')
# LED logic
if (temp > 60 and temp < 85 and humidity < 80):
lights(0,0,1)
elif (temp > 85 and temp < 95 and humidity < 80):
lights(0,1,0)
elif (temp > 95):
lights(1,0,0)
elif (humidity > 80):
lights(0,1,1)
else:
lights(0,0,0)
time.sleep(time_gap)
else:
print("Data not recorded, sensor can not detect light")
time,sleep(10)
# Catch exception for dividing by zero
except ZeroDivisionError:
print("Zero reading on sensor")
except KeyboardInterrupt:
lights(0,0,0)
except IOError:
print("ERROR")
print("Data Recorded")
lights(0,0,0)
# Closing bracket on JSON file
with open("weather_station_data.json", "a") as write_file:
write_file.write('\n]')
|
e063305fc709976764dc32a65049db20f14025f2 | relman/sort-list | /main.py | 697 | 4.0625 | 4 | import sys
def sort_list(s):
"""
Returns sorted list.
:param s: list of words and numbers
"""
for i in range(0, len(s)):
for j in range(i + 1, len(s)):
if compare(s[i], s[j]):
s[i], s[j] = s[j], s[i]
return s
def compare(x, y):
"""
Returns 1 when x is greater than y.
:param x: string representation of word or number
:param y: string representation of word or number
"""
if x.isalpha() != y.isalpha():
return 0
if not x.isalpha():
return 1 if int(x) > int(y) else 0
return 1 if x > y else 0
if __name__ == '__main__':
print sort_list(sys.argv[1:])
|
07f718e76794a1dc07e26a7a02ca6ac0ea3871c0 | grecoe/teals | /8_game_controller/games/collegechooser.py | 1,856 | 4.1875 | 4 | # Include the logger so we can output from here as well
from utils.tracer import TraceDecorator
@TraceDecorator
def show_description():
print("""
Based on your choices, the program will help you pick a college
that most suits you.
Code is located at: /games/collegechooser.py
""")
@TraceDecorator
def play():
'''
This program uses lists and dictionaries to ask a user a preference on
college choices then ranks the school based on those selections.
'''
questions = {
"What location do you prefer? > ": ["New England", "West Coast", "New York", "South"],
"What size school do you prefer? > ": ["Small", "Middle", "Large", "HUGE"],
"What size city do you prefer to live in? > ": ["Small City", "Suburbs", "Big City", "Rural"]
}
schools = {
"Brown":
[0, 1, 3],
"Panoma":
[1, 1, 3],
"NYU":
[2, 3, 2],
"Alabama State":
[3, 1, 3]
}
# Key is question, value is answer
answers = {}
# Key is school name, value is ranking
rankings = {}
# Collect users input
for question in questions:
optionsList = questions[question]
for idx in range(len(optionsList)):
print(idx + 1, " ", optionsList[idx])
answers[question] = int(input(question)) - 1
# Rank the schools
for school in schools:
schoolRank = 0
optionsIndex = 0
schoolOptions = schools[school]
for answer in answers:
# This only works because we know the two lists are aligned....
if schoolOptions[optionsIndex] == answers[answer]:
schoolRank += 1
optionsIndex += 1
rankings[school] = schoolRank
print("\nYour Rankings")
for rank in rankings:
print(rank, " : ", rankings[rank])
|
af62b8ebe36413c16a21e68beb7cf07a68570763 | chayabenyehuda/LearnPython | /She Codes/guessing game.py | 395 | 4.0625 | 4 | Secret_name = "Chaya"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guess = False
while Secret_name != guess and not(out_of_guess):
if guess_limit > guess_count:
guess = input("enter a guess: ")
guess_count += 1
else:
out_of_guess = True
if out_of_guess:
print("you lose")
else:
print(f"you won after {guess_count} guesses!")
|
fcc79b7bdca87f806ead2e7f708be911cbae139f | JoannaEbreso/PythonProgress | /FileReverse.py | 361 | 3.703125 | 4 | input_file=open("input.txt","r")
output_file=open("output.txt","w")
for line_str in input_file:
new_str=''
line_str=line_str.strip()
for char in line_str:
new_str=char+new_str
print("new_str",file=output_file)
print('Line: {:<12s} is reversed to {:>12s}'. format(line_str,new_str))
input_file.close()
output_file.close()
|
cb707f001f803c1b7d3308654a097031dab87df4 | Lucas130/leet | /dynamic-planning/122-best-time-to-buy-and-sell-stock-i.py | 777 | 3.609375 | 4 | """
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
"""
class Solution:
def maxProfit(self, prices) -> int:
if len(prices) < 2:
return 0
sum_temp = 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
sum_temp += prices[i] - prices[i - 1]
return sum_temp
if __name__ == '__main__':
prices = [7, 1, 5, 3, 6, 4]
# prices = [7, 2, 3, 6, 1, 4, 4]
# prices = []
print(Solution().maxProfit(prices))
|
4d33c3b85eb632dc8c837b5b7c5c9541e4ad2d39 | rmjohnson/programming | /python/euler/problem19.py | 1,249 | 3.953125 | 4 | def check(d):
if d[0] == "S" and d[2] == 1:
return "T"
else:
return "F"
def monthdays(m,y):
if m == "Jan" or m == "Mar" or m == "May" or m == "Jul" or m == "Aug" or m == "Oct" or m == "Dec":
return 31
if m == "Feb" and y == 2000:
return 29
elif m == "Feb":
if y % 4 == 0 and y % 100 != 0:
return 29
else:
return 28
if m == "Sep" or m == "Apr" or m == "Jun" or m == "Nov":
return 30
count = 0
days = ["S","M","T","W","Th","F","Sa"]
months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
day = ["T","Jan",1,1901]
while day[3] <= 2000:
#if day[2] == 1 and day[3] == 2000:
#print day
#if day[2] == monthdays(day[1],day[3]) and day[3] == 2000:
#print day
if day[0] == "Sa":
day[0] = "S"
else:
day[0] = days[days.index(day[0])+1]
if day[2] == monthdays(day[1],day[3]):
day[2] = 1
if day[1] == "Dec":
day[1] = "Jan"
day[3] += 1
else:
day[1] = months[months.index(day[1])+1]
else:
day[2] += 1
if check(day) == "T":
print day[1],
print day[3]
count += 1
print count
|
f017bba9bbfc4f240d49636ecf9871fdad10d440 | yysung1123/competitive_programming | /generator/GA.py | 210 | 3.625 | 4 | #!/usr/bin/env python3
import random
n = 10000
arr = [i + 1 for i in range(n)]
print(n)
#random.shuffle(arr)
print(' '.join([str(i) for i in arr]))
#random.shuffle(arr)
print(' '.join([str(i) for i in arr]))
|
ae3224a76bc63be70373c3436f88d9fec3ff29f4 | sverchkov/generalizedtrees | /generalizedtrees/tree.py | 5,978 | 3.921875 | 4 | # Tree data structure
#
# Licensed under the BSD 3-Clause License
# Copyright (c) 2020, Yuriy Sverchkov
from collections.abc import Collection
from collections import deque
from typing import Iterable, Any
from logging import getLogger
logger = getLogger()
class Tree(Collection):
"""
A container-like tree data structure.
"""
class Node:
def __init__(self, tree: 'Tree', index: int, item: Any, depth: int, parent: int):
self.tree = tree
self.item = item
self._depth = depth
self._parent = parent
self._index = index
self._children = []
def parent(self):
return self.tree.node(self._parent)
@property
def depth(self):
return self._depth
@property
def is_root(self) -> bool:
return self._depth == 0
@property
def is_leaf(self) -> bool:
return not self._children
def __len__(self) -> int:
return len(self._children)
def __getitem__(self, key):
"""
We use slices to access child nodes
"""
return self.tree.node(self._children[key])
def __init__(self, contents=()):
"""
Create a tree
contents: heterogeneous iterable specifying the tree. The list is interpreted as
follows:
- The first item is the item at the root
- Subsequent items are subtrees following the same convention.
i.e. ['A', ['B', ['D']], ['C']] would initialize a tree with root
'A', children 'B' and 'C', and 'D' as a child of 'B'.
- Enclosing list may be omitted for leaves.
"""
self._nodes = []
self._tree_depth = -1
# Populate tree
if not isinstance(contents, Iterable) or contents:
stack = deque([(-1, contents)])
while stack:
parent, subtree = stack.pop()
if not isinstance(subtree, Iterable):
self.add_node(subtree, parent)
else:
i = iter(subtree)
index = self.add_node(next(i), parent)
stack.extend((index, subtr) for subtr in i)
@property
def depth(self) -> int:
return self._tree_depth
def __len__(self) -> int:
return len(self._nodes)
def _single_index(self, key):
return isinstance(key, int) or key == 'root'
def _1index(self, key):
k = 0 if key == 'root' else key
if isinstance(k, int) and k >=0 and k < len(self._nodes):
return k
else:
raise IndexError(
f'Key {key} is out of bounds for tree of '
f'size {len(self._nodes)} or is not a single value.')
def __getitem__(self, key):
if self._single_index(key):
return self.node(key).item
else:
return (n.item for n in self.node(key))
def node(self, key):
if self._single_index(key):
return self._nodes[self._1index(key)]
elif isinstance(key, slice):
return self._nodes[key]
elif isinstance(key, Iterable):
return (self._nodes[self._1index(k)] for k in key)
raise TypeError(f'Tree indices must be strings, integers, slices, or iterable')
@property
def root(self):
return self.node(0)
def add_node(self, item, parent_key=-1) -> int:
if parent_key == -1:
if self._nodes:
raise ValueError('Attempted to replace existing root node.')
else:
self._nodes.append(Tree.Node(self, 0, item, 0, -1))
self._tree_depth = 0
else:
self.add_children([item], parent_key)
# Assuming that node was ended to the end
return len(self._nodes)-1
def add_children(self, items, parent_key):
# Check parent index
parent_key = self._1index(parent_key)
# Get parent node object
parent: Tree.Node = self._nodes[parent_key]
# Determine depth of child nodes
depth = parent.depth + 1
# Determine child indeces in nodes array
indeces = range(len(self._nodes), len(self._nodes)+len(items))
# Create child nodes and add to nodes array
self._nodes.extend(
Tree.Node(self, index, item, depth, parent_key)
for index, item in zip(indeces, items))
# Register children with parent
parent._children.extend(indeces)
# Update tree depth
if depth > self._tree_depth:
self._tree_depth = depth
def __iter__(self):
"""
Depth-first iteration
"""
if (self):
stack = deque([0])
while stack:
n = stack.pop()
stack.extend(self._nodes[n]._children)
yield self._nodes[n].item
def __contains__(self, item):
return any(item is node.item or item == node.item for node in self._nodes)
def tree_to_str(tree: Tree, content_str = lambda x: str(x)) -> str:
# Constants for tree drawing. Defining them here in case we want to customize later.
space = ' '
trunk = '| '
mid_branch = '+--'
last_branch = '+--'
endline = '\n'
result:str = ''
stack = deque([tree.root])
continuing = [0 for _ in range(tree.depth+1)]
while stack:
node = stack.pop()
stack.extend(node[:])
continuing[node.depth] += len(node)
if node.depth > 0:
for d in range(node.depth-1):
result += trunk if continuing[d] else space
continuing[node.depth-1] -= 1
result += mid_branch if continuing[node.depth-1] else last_branch
result += content_str(node.item)
if stack:
result += endline
return result
|
6a1dcd57e7ba864558c3a823bd7e3d70fe146f68 | Fashgubben/TicTacToe | /tic_tac_toe.py | 5,522 | 3.5625 | 4 | import game_functions
from class_statistics import Statistics, Player
from check_for_winner import check_for_winner
from statistic_table import create_terminal_table, print_table, stat_gui
from check_input import get_valid_coordinates
def create_players():
"""Creates and returns two player objects"""
print('\n' + 'TIC TAC TOE'.center(23, '-'))
name_1 = input('Enter name of Player 1: ').title()
print('\nEnter "Skynet" to play against a computer.')
name_2 = input('Enter name of Player 2: ').title()
return Player(name_1, 'X'), Player(name_2, 'O'), Statistics()
def print_menu():
"""Prints out a menu"""
print('\n' + 'TIC TAC TOE'.center(23, '-'))
print('[1] - Play Tic Tac Toe\n[2] - View scoreboard\n[3] - View game history')
print('[4] - Clear game history\n[5] - Quit')
return input('\nEnter a menu number: ')
def menu_choices():
"""Program menu choices"""
while True:
users_choice = print_menu()
# Play a game
if users_choice == '1':
grid_size = game_functions.get_grid_size()
game_board = game_functions.create_board(grid_size)
game_functions.reset_move_count(player_1, player_2, total)
play_game = True
while play_game:
for player in player_list:
if player.name != 'Skynet':
game_functions.print_board(game_board, grid_size, player_1, player_2)
if game_functions.check_for_available_moves(game_board, grid_size):
# Get coordinates from players
while True:
try:
if player.name == 'Skynet':
coordinates = game_functions.get_computer_coordinates(player, grid_size, game_board)
else:
player_input = game_functions.get_input(player)
coordinates = get_valid_coordinates(game_board, grid_size, player_input,
player.name)
game_functions.place_mark(game_board, coordinates, player.symbol)
player.add_last_game_moves()
break
except ValueError as error_message:
print(error_message)
if check_for_winner(game_board, grid_size, player.symbol):
game_functions.print_board(game_board, grid_size, player_1, player_2)
print(f'\nCongratulations {player.name}! You are the winner!')
# Update statistics
player.add_win()
player.total_moves_winning_games += player.last_game_moves
game_functions.update_stats(player_1, player_2, total)
# Save game board
game_was_won = True
game_functions.save_game_result(game_board, player, player_1, player_2, grid_size,
game_was_won)
play_game = False
break
else: # If it's a draw
print('\nThe game is a tie! No one is a loser today!')
# Update statistics when it's a draw
game_functions.update_stats_tie(player_1, player_2, total)
game_functions.update_stats(player_1, player_2, total)
# Save game board
game_was_won = False
game_functions.save_game_result(game_board, player, player_1, player_2, grid_size, game_was_won)
play_game = False
# View statistics
elif users_choice == '2':
# Open gui-table
stat_gui(player_1, player_2, total)
# Print the statistics table
table = create_terminal_table(player_1, player_2, total)
print_table(table)
# Print game history
elif users_choice == '3':
print('\n' + 'TIC TAC TOE'.center(23, '-'))
print_game_history()
# Clear game history
elif users_choice == '4':
print('\n' + 'TIC TAC TOE'.center(23, '-'))
clear_game_history()
# Close game
elif users_choice == '5':
print('Good bye!')
break
else:
print('Please use a number from the menu.')
def print_game_history():
"""Prints all played games"""
with open('game_history.txt', 'r', encoding='utf-8') as saved_games:
for line in saved_games.readlines():
print(line.rstrip('\n'))
input('\n-Press enter to continue-')
def clear_game_history():
"""Clears the game history text-file"""
with open('game_history.txt', 'w', encoding='utf-8') as saved_games:
saved_games.write('')
print('\nGame history cleared!')
if __name__ == '__main__':
(player_1, player_2, total) = create_players()
player_list = [player_1, player_2]
menu_choices() |
dbc5eb8dbcb998b649574e1f06ef044a6231f2c2 | godwon2095/python_algorithm | /class_3_recursive/merge_sort_recursive.py | 1,142 | 4.125 | 4 | #2015110417 수학과 장성원
# -*- coding: utf-8 -*-
import pdb
def MergePartial(left_list, right_list):
sorted_list = []
while len(left_list) > 0 or len(right_list) > 0:
if len(left_list) > 0 and len(right_list) > 0:
if left_list[0] <= right_list[0]:
sorted_list.append(left_list[0])
left_list = left_list[1:]
else:
sorted_list.append(right_list[0])
right_list = right_list[1:]
elif len(left_list) > 0:
sorted_list.append(left_list[0])
left_list = left_list[1:]
elif len(right_list) > 0:
sorted_list.append(right_list[0])
right_list = right_list[1:]
return sorted_list
def MergeSort(num_list):
if len(num_list) <= 1:
return num_list
mid = len(num_list) // 2
left_list = num_list[:mid]
right_list = num_list[mid:]
left_list = MergeSort(left_list)
right_list = MergeSort(right_list)
print(num_list)
return MergePartial(left_list, right_list)
num_list = [1.5, 1, 2, 5, 2.5, 2.25, 0.5, 12.5, 7.5]
print(MergeSort(num_list)) |
c9e2b38f113e5dc3956a3b8fa9a6f6f0c88f65fb | rbhatta8/dota2-league-rep-learning | /rep-learning/scripts/visualization.py | 1,219 | 3.78125 | 4 | """
Script used to visualize results from any of the techniques
authors : Rohit Bhattacharya, Azwad Sabik
emails : rohit.bhattachar@gmail.com, azwadsabik@gmail.com
"""
# imports
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def visualize2d(X, Y, output_name):
'''
Visualizes in 2d
'''
# make a colour map that colours the points
# based on their unique labels
unique_labels = set(Y)
num_unique_labels = len(unique_labels)
unique_labels_dict = dict(zip(unique_labels, range(num_unique_labels)))
colour_map = [unique_labels_dict[l] for l in Y]
# save and plot
plt.scatter(X[:,0], X[:,1], c=colour_map)
plt.savefig(output_name)
plt.show()
def visualize3d(X, Y, output_name):
'''
Visualizes in 3d
'''
# make a colour map that colours the points
# based on their unique labels
unique_labels = set(Y)
num_unique_labels = len(unique_labels)
unique_labels_dict = dict(zip(unique_labels, range(num_unique_labels)))
colour_map = [unique_labels_dict[l] for l in Y]
# save and plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X[:,0], X[:,1], X[:,2], c=colour_map)
plt.savefig(output_name)
plt.show()
|
f23b5aa702baed110c605e96533ca569cbd465d0 | Prasad-Medisetti/STT | /My Python Scripts/BIN2OCT.py | 764 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 15 18:35:09 2020
@author: hp
"""
'''
Program to convert a binary number to octal number.
Input:
11010
Output:
32
1. Valid Input:
a) Only number consisting of 0s and 1s will be given as input
2. Invalid inputs:
a) Decimal b) Fraction c) String
d) Negative number
3. You should generate output as follows:
a) For right output print just the actual Octal Value without any other text.
b) If any error: print 'ERROR' without any other text.
For example:
Test Input Result
1 101 5
2 11010 32 32
'''
def Bin2Oct(n):
for i in n:
if i in '10':
continue
else:
return 'ERROR'
s = int(n,2)
return oct(s)[2:]
n = input()
print(Bin2Oct(n)) |
593c576dd4cd4cb4063ca8b9778d25119c08ff97 | Nevilli/unit_three | /d4_unit_three_warmups.py | 270 | 3.859375 | 4 | def area_of_rectangle(length, width):
"""
This function calculate the area of a rectangle
:param length: length of long side of rectangle
:param width: length of small side of rectangle
:return: area
"""
area = length * width
return area
|
c44139ab22af877b3c699e3fbdb3f147ade5441b | fasna123/TheSparksFoundatiion | /TSF_task2.py | 1,651 | 3.90625 | 4 | #importing necessary libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#importing dataset
data_set="http://bit.ly/w-data"
data=pd.read_csv(data_set)
#ploting dataset
data.plot(x='Hours', y='Scores', style='o')
plt.title('Hours vs Percentage')
plt.xlabel('Hours Studied')
plt.ylabel('Percentage Score')
plt.show()
#Preparing the data
X = data.iloc[:, :-1].values
y = data.iloc[:, 1].values
#Splitting of dataset into train set and test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
#Training the algorithm
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
print("training complete")
#Plotting the regression line
line=regressor.coef_*X_train+regressor.intercept_
plt.scatter(X_train,y_train)
plt.plot(X_train,line)
plt.show()
#Making predictions
y_pred = regressor.predict(X_test)
#Comparing actual vs predicted
df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})
print(df)
#Testing algorithm with new data
hours=9.8
new_pred=regressor.predict([[hours]])
print(f"The predicted score for studying {hours}hr is: {new_pred}")
#Performance evaluation of the algorithm
from sklearn import metrics
print("Performance Evaluation")
print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))
print('Mean Squared Error:', metrics.mean_squared_error(y_test, y_pred))
print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_pred))) |
fd4940111296beab6bf6b81ee9e30dd7ae1c6536 | Rotsteinblock/main.python | /main.py | 2,038 | 3.65625 | 4 | import math;
import collections;
minSchritt = 1; """ muss 1 sein?"""
L = 100; """ abstand der motoren in schritten"""
actMotorLaengeA = 20;
actMotorLaengeB = 70;
def getLaengeA(x, y):
return math.sqrt(x*x+y*y)
def getLaengeB(x, y):
return math.sqrt((L-x)*(L-x)+y*y)
def beta (a, b):
res = math.acos (-(b * b - a * a - L * L) / (2 * a * L))
return res;
def getPosX (a, b):
res = math.cos(beta(a, b))*a
return res
def getPosY (a, b):
res = math.sin(beta(a, b))*a
return res
def motorSetLaenge(a, b):
todoA = a - actMotorLaengeA
todoB = b - actMotorLaengeA
return
def macheGerade(x1, y1, x2, y2):
a1 = getLaengeA(x1, y1)
b1 = getLaengeB(x1, y1)
a2 = getLaengeA(x2, y2)
b2 = getLaengeB(x2, y2)
wegA = a2-a1
wegB = b2-b1
wegX = x2-x1
wegY = y2-y1
print("-->neue Gerade: from x,y=(" + str(x1) + "," + str(y1) + ") -> to x,y=(" + str(x2)+ "," + str(y2) + ")")
motorSetLaenge(a1, b1)
schritte = 0
if abs(wegY) < abs(wegX):
schritte = round(wegX/minSchritt)
else:
schritte = round(wegY/minSchritt)
for i in range(schritte):
x = (x1 + i*wegX/schritte)
y = (y1 + i*wegY/schritte)
a = round(getLaengeA(x, y))
b = round(getLaengeB(x, y))
rx = getPosX(a, b)
ry = getPosY(a, b)
print(" ->Pos " +str(i) + "/" + str(schritte) + ": a,b=[" + str(a) + "," + str(b)+"] x,y~(" + str(round(x)) + "," + str(round(y)) + ") rx,ry=(" + str(rx) + "," + str(ry) + ")")
motorSetLaenge(a, b)
continue
x = x2
y = y2
a = round(getLaengeA(x, y))
b = round(getLaengeB(x, y))
rx = getPosX(a, b)
ry = getPosY(a, b)
print(" ->Pos " +str(schritte) + "/" + str(schritte) + ": a,b=[" + str(a) + "," + str(b)+"] x,y~(" + str(round(x)) + "," + str(round(y)) + ") rx,ry=(" + str(rx) + "," + str(ry) + ")")
motorSetLaenge(a, b)
return
if __name__ == '__main__':
macheGerade(10, 20, 40, 10)
zth
|
059929bce0186fac00a5c472177383f3391976c4 | yashhR/competitive | /LeetCode/258. Add Digits.py | 449 | 3.734375 | 4 |
# def addDigits(num: int) -> int:
# def sum_digits(n):
# sumi = 0
# for digit in str(n):
# sumi += int(digit)
# return sumi
# while len(str(num)) > 1:
# num = sum_digits(num)
# return num
def add_digits(num):
if len(str(num)) > 1:
sumi = 0
for c in str(num):
sumi += int(c)
return add_digits(sumi)
else:
return num
print(add_digits(38)) |
bfc2b396219f22c34fab31f4616111206b0a61fa | jadball/python-course | /Level 2/29 Work in progress/Physics/02_animate_particle.py | 2,401 | 3.765625 | 4 | import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
fig.canvas.set_window_title("Planetary Orbits")
ax = fig.gca(projection="3d")
ax.set_title("Satellite Tracing Orbiting Earth")
elevation = 75
viewing_angle = 125
ax.view_init(elev=elevation, azim=viewing_angle)
earth, = ax.plot([0], [0], [0], 'bo')
orbit, = ax.plot([], [], [], lw=1, color='green', marker='o', markersize=1)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_xlim3d([-100.0, 100.0])
ax.set_ylim3d([-100.0, 100.0])
ax.set_zlim3d([-100.0, 100.0])
k = 10.0
m = 1.0
class Particle:
history_size = 250
def __init__(self, name, x, v):
self.history_buffer = np.empty((0, 3))
self.name = name
self.x = x
self.v = v
self.index = 0
self.history_buffer = np.append(self.history_buffer, [self.x], axis=0)
def getPosition(self):
return self.x
def next(self, dt):
# F = m * dv/dt => dv = F * dt / m
# dx/dt = v => dx = v * dt => x = x + dx
# = x + v * dt
x = self.x[0]
y = self.x[1]
z = self.x[2]
R = (x ** 2 + y ** 2 + z ** 2) ** 0.5
Rhat = np.array([x, y, z]) / R
F = -k * Rhat / R ** 2
dv = F * dt / m
self.v += dv
self.x += self.v * dt
self.index += 1
if self.index >= Particle.history_size:
self.history_buffer[self.index % Particle.history_size] = self.x
else:
self.history_buffer = np.append(self.history_buffer, [self.x], axis=0)
def history(self):
n = self.index % Particle.history_size
return np.roll(self.history_buffer, -n - 1, axis=0)
x0 = np.array([90.0, 0.0, 0.0])
v0 = np.array([0.1, 0.2, 0.1])
p = Particle("earth", x0, v0)
def init():
earth.set_data(0, 0)
earth.set_3d_properties(0)
return earth
def animate(frameNo):
p.next(dt=2)
h = p.history().T # must transpose buffer to extract X,Y and Z
X, Y, Z = h[0], h[1], h[2]
X = np.append(X, [0.0])
Y = np.append(Y, [0.0])
Z = np.append(Z, [0.0])
orbit.set_data(X, Y)
orbit.set_3d_properties(Z)
return orbit # the artist to be updated
a = animation.FuncAnimation(fig, animate, init_func=init, frames=100000, \
interval=50)
plt.show()
|
3f31550ffeebac06b70b55fd236f153e31d8d6a3 | shiwanibiradar/10days_python | /day2/while/squareseries.py | 110 | 3.625 | 4 | #addition of square of first 10 digit
num=int(input())
sa=0
for i in range(1,num+1):
sa=sa+(i*i)
print(sa)
|
49e3ca16cbee786301fd9eb83e257e05366369f9 | luismelendez94/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/1-search_replace.py | 248 | 3.984375 | 4 | #!/usr/bin/python3
def search_replace(my_list, search, replace):
new_list = my_list.copy()
index = 0
for element in my_list:
if element == search:
new_list[index] = replace
index += 1
return new_list
|
ffa913d15630ba72a90d919005816b034afb3121 | Aasthaengg/IBMdataset | /Python_codes/p00001/s737543331.py | 186 | 3.75 | 4 | f, s, t = 3,2,1
for i in range(10):
z = int(input())
if z >= f:
f,s,t = z, f, s;
elif z>=s:
s,t = z,s;
elif z>=t:
t = z
print(f);print(s);print(t) |
da9250834a1a7c27dd61fd2f2a219bda6855900c | haukurarna/2018-T-111-PROG | /solutions_to_programming_exercises/assignment26_for.py | 253 | 4.03125 | 4 | turns = int(input("Input the number of turns: "))
number_of_negatives = 0
for number in range(turns) :
choice = int(input("input a number: "))
if choice < 1 :
number_of_negatives += 1
print("number of negatives:", number_of_negatives)
|
728b5f84bbac119a177bd349ebce521e34cf296a | zotochev/VSHE | /week 02/tasks_02/02_33_len_line.py | 80 | 3.546875 | 4 | n = 1
count = -1
while n != 0:
count += 1
n = int(input())
print(count)
|
1d86f470b7ee5224a993cf06266f4d6a3c76e186 | joaoo-vittor/estudo-python | /OrientacaoObjeto/aula23.py | 1,109 | 4.3125 | 4 | """
aula 23
Implementando um iterator
"""
class MinhaLista:
def __init__(self):
self.__items = []
self.__index = 0
def add(self, value):
self.__items.append(value)
def __getitem__(self, index):
return self.__items[index]
def __setitem__(self, index, value):
if index >= len(self.__items):
self.__items.append(value)
return
self.__items[index] = value
def __delitem__(self, index):
del self.__items[index]
def __iter__(self):
return self
def __next__(self):
try:
item = self.__items[self.__index]
self.__index += 1
return item
except IndexError:
raise StopIteration
def __str__(self):
return f'{self.__class__.__name__} ({self.__items})'
if __name__ == '__main__':
lista = MinhaLista()
lista.add('João')
lista.add('Vitor')
lista[0] = 'Luiz'
lista[2] = 'Otavio'
print(lista[0])
print(lista[1])
print(lista)
del lista[2]
for valor in lista:
print(valor)
|
1b90f789fc56705aaa1eff9522c04e23f11b1751 | javierllaca/strange-loops | /challenges/trees/reconstruct_tree/main.py | 839 | 3.78125 | 4 | """
Reconstruct a binary tree
Input: inorder, preorder
Output: root of constructed tree
class Node: data (ints), leftChild, rightChild
"""
class Node:
pass
inorder = [2, 3, 5, 6, 7, 9]
preorder = [5, 3, 2, 7, 6, 9]
def binary_search(a, x, lo, hi):
if lo == hi:
return lo
mid = lo + (hi - lo) / 2
if x == a[mid]:
return mid
if x < a[mid]:
return binary_search(a, x, lo, mid)
else:
return binary_search(a, x, mid + 1, hi)
def reconstruct_tree(inorder, preorder):
if not inorder:
return None
root = preorder.pop(0)
root_index = binary_search(inorder, root, 0, len(inorder))
left_child = reconstruct_tree(inorder[:root_index], preorder)
right_child = reconstruct_tree(inorder[root_index + 1:], preorder)
return Node(root, left_child, right_child)
|
58e254e381165aab723f8e39141a26a5a328490c | davkim1030/algorithm | /dbn/03_greedy/01_거스름돈.py | 537 | 3.671875 | 4 | """
당신은 음식점의 계산을 도와주는 점원이다.
카운터에는 거스름돈으로 사용할 500원, 100원, 50원, 10원짜리 동전이
무한히 존재한다고 가정한다.
손님에게 거슬러 줘야 할 돈이 N원일 때,
거슬러줘야 할 동전의 최소 개수를 구하라.
단, 거슬러 줘야 할 돈 N은 항상 10의 배수이다.
"""
if __name__ == "__main__":
n = int(input())
coin_types = [500, 100, 50, 10]
count = 0
for coin in coin_types:
count += n // coin
n %= coin
print(count)
|
ab66a0e0aab0962ba4f5add094537aa039d7c85e | 4ELANC76/com404 | /1-basics/3-decision/1-if/bot.py | 288 | 3.96875 | 4 | book = input("What is that type of book?")
book = str(book)
if (book == "adventure"):
print("I like adventure books too!")
if (book == "fiction"):
print("Wow! A fiction book!")
if (book == "fantasy"):
print("My favourite fantasy book is Harry Potter")
print("Finshed reading the book.")
|
d4f3620f7022f75ad28bf9defc350ec7b710a8ab | cmungioli/meteorite-temps-project | /Meteorite_Temps_Project.py | 6,975 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 15 10:41:02 2019
@author: Carlo Mungioli
"""
import math
import sys
def input_data():
#This section creates lists for the radii and thermal conductivities of each layer.
#It also specifies necessary values such as temperatures and lengths of time.
#We have multiple try/except blocks so we can retry inputting values if the initial entry is invalid
radiusentered = False
thermcondentered = False
thotentered = False
tcoldentered = False
timeentered = False
while radiusentered == False:
try:
radiiList = [float(input("Radius of first layer (m): "))]
except:
print("Error: unexpected input entered")
continue
radiusentered = True
while thermcondentered == False:
try:
thermcondList = [float(input("Thermal conductivity of first layer (W m^-1 K^-1): "))]
except:
print("Error: unexpected input entered")
continue
thermcondentered = True
while thotentered == False:
try:
Thot = float(input("Temperature of outer surface (K): "))
except:
print("Error: unexpected input entered")
continue
thotentered = True
while tcoldentered == False:
try:
Tcold = float(input("Temperature of core (K): "))
except:
print("Error: unexpected input entered")
continue
tcoldentered = True
while timeentered == False:
try:
t = float(input("Length of time of heat pulse (s): "))
except:
print("Error: unexpected input entered")
continue
timeentered = True
kmultrList = [(radiiList[0] * thermcondList[0])]
yesnoentered = False
while yesnoentered == False:
yesnostr = input("Add another layer? (y/n): ")
if yesnostr == "y" or yesnostr == "yes" or yesnostr == "Y":
yesno = True
elif yesnostr == "n" or yesnostr == "no" or yesnostr == "N":
yesno = False
else:
print("Error: please enter yes or no")
continue
yesnoentered = True
while yesno == True:
#If the user wants to add another layer, it creates a new list to extend the old list with, then deletes them.
#This is the case with both the radii list and the thermal conductivity lists.
#This is because floating point numbers cannot be appended to lists directly.
#At the end, it asks again if the user would like to add another layer.
#This allows the user to add as many layers as possible.
radiusentered = False
thermcondentered = False
while radiusentered == False:
try:
radiiListaddto = [float(input("Radius of the next layer (m): "))]
except:
print("Error: unexpected input entered")
continue
radiusentered = True
while thermcondentered == False:
try:
thermcondListaddto = [float(input("Thermal conductivity of next layer (W m^-1 K^-1): "))]
except:
print("Error: unexpected input entered")
continue
thermcondentered = True
radiiList.extend(radiiListaddto)
thermcondList.extend(thermcondListaddto)
del radiiListaddto
del thermcondListaddto
yesnoentered = False
while yesnoentered == False:
yesno = input("Add another layer? (y/n): ")
if yesno == "y" or yesno == "yes" or yesno == "Y":
yesno = True
elif yesno == "n" or yesno == "no" or yesno == "N":
yesno = False
else:
print("Error: please enter yes or no")
continue
yesnoentered = True
ruser = input("Enter the radius to which the heat conduction rate will be found. (m): ")
return radiiList, thermcondList, kmultrList, Tcold, Thot, float(ruser), t
def test_dataset():
radiiList
thermcondList
kmultrList
Tcold = 200.0
Thot = 2500.0
ruser
t
return radiiList, thermcondList, kmultrList, Tcold, Thot, float(ruser), t
def file_data( fname):
"""read data from file. file format is csv:
#comment first line
4 fields, giving k, Tcold, Thot, ruser
n lines of 3 fields, giving radii, thermcond, kmultr
"""
with open( fname, 'rt') as fp:
ln = fp.readline() #comment line, ignore
k, Tcold, Thot, ruser, t = fp.readline().split(',')
radiiList, thermcondList, kmultrList = [],[],[]
for ln in fp.readlines():
lin = ln.split(',')
radiiList.append( lin[0].strip() )
thermcondList.append( lin[1].strip() )
kmultrList.append( lin[2].strip() )
return radiiList, thermcondList, kmultrList, Tcold, Thot, float(ruser), t
def do_calc(radiiList, thermcondList, kmultrList, Tcold, Thot, ruser, t):
"""Doing the calculations"""
R = sum(radiiList)
for x in range(1,len(radiiList)):
kmultrListaddto = [(radiiList[x] * thermcondList[x])]
kmultrList.extend( kmultrListaddto)
k = (sum(kmultrList)) / R
q = -1 * ((4 * math.pi * k * (Tcold - Thot)) / ((1 / ruser) - (1 / R)))
Q = q * t
return q, Q, k
def print_results(q, Q):
#Printing the values
print("The rate of heat conduction to the radius specified is: {} Joules/sec".format(q) )
print("The total heat conducted to the radius specified is: {} Joules".format(Q) )
def ice_compare( Q, Tcold, ruser):
"""calculate the mass of ice that would be melted by this level of heat.
It then compares this with the mass of ice that could fit within the
specified radius. Realistically the mass of ice that would melt under this
heat is slightly too high, as only the outer layer of ice is exposed to
the heat. However all this means is that if the answer is no, then the ice
definitely couldn't melt"""
m = Q / ((2108.0 * (273.15 - Tcold) + 334000.0))
mice = (917.0 * (4.0 / 3.0) * math.pi * (ruser ** 3.0))
if m > mice:
print("The ice cannot stay frozen within the radius specified")
else:
print("Ice with mass {} kgs would stay frozen at the radius specified"
.format(m) )
if __name__ == '__main__':
if len(sys.argv) > 1:
if os.path.isfile( sys.argv[1]):
radiiList, thermcondList, kmultrList, Tcold, Thot, ruser, t = file_data()
elif sys.argv[1] == '-t':
radiiList, thermcondList, kmultrList, Tcold, Thot, ruser, t = test_dataset()
else:
exit()
else:
radiiList, thermcondList, kmultrList, Tcold, Thot, ruser, t = input_data()
q, Q, k = do_calc( radiiList, thermcondList, kmultrList, Tcold, Thot, ruser, t)
print_results( q, Q)
ice_compare( Q, Tcold, ruser)
|
66364738f47ea07e4366fb78a014452e15392e60 | nicolopinci/geneticTimetable | /geneticClassAllocation.py | 13,828 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 25 14:48:41 2020
@author: nicolo
"""
from random import randrange
import copy
import random
import math
class Lecture:
def __init__(self, id, description, numberPeople, timeslots, color):
# Lecture constructor
self.id = id # ID of the lecture (example: LECTURE1)
self.description = description # description (example: "Introductory programming course")
self.numberPeople = numberPeople # people that attend the lecture
self.timeslots = timeslots # number of timeslots
self.color = color # this is to define the CSS style for the output
def __str__(self): # To print on console easily
return str(self.id) + " - " + self.description + " - " + str(self.numberPeople) + " people - " + str(self.timeslots) + " timeslots"
def transformIntoEvents(self): # SPlit a lecture into 1-timeslot events
eventList = []
for i in range(0, self.timeslots):
eventList.append(Event(str(self.id) + "_" + str(i), self.description, self.numberPeople, i, self.id))
return eventList
class Event:
def __init__(self, id, description, numberPeople, fragmentNr, lecture):
# Event constructor
self.id = id
self.description = description
self.numberPeople = numberPeople
self.fragmentNr = fragmentNr # fragment inside a lecture
self.lecture = lecture # id of the lecture
def __str__(self):
return str(self.id) + " - " + self.description + " - " + str(self.numberPeople) + " people, lecture " + str(self.lecture) + ", fragm " + str(self.fragmentNr)
def findLecture(self, lectures): # Given an event, find the corresponding lecture
for l in lectures:
if(l.id == self.lecture):
return l
return Lecture("","",0,0,"rgb(255,255,255)")
class Room:
def __init__(self, id, description, capacity, isEmpty):
self.id = id
self.description = description
self.isEmpty = isEmpty
self.currentEvent = Event("", "", 0, 0, "")
self.capacity = capacity
def fillRandom(self, number): # assign a random capacity
self.id = "ROOM"+str(number)
self.description = ""
self.capacity = randrange(1, 100)
self.isEmpty = True
class Chromosome:
def __init__(self, roomList):
self.roomList = roomList
def addEventToRoom(self, event, oldRoom): # given a room, add an event to it
room = copy.deepcopy(oldRoom)
added = False
for r in self.roomList:
if(r == room):
room.currentEvent = event
added = True
if(added == False):
room.currentEvent = event
self.roomList.append(room)
room.isEmpty = False
def deleteEvent(self, event): # delete an event from a room --> the room becomes empty
for room in self.roomList:
if(room.currentEvent == event):
room.isEmpty = True
def __str__(self): # used to print a room on console
out = ""
for room in self.roomList:
if(room.isEmpty == False):
out += "Room " + room.id + " (" + str(room.capacity) + " people): " + room.currentEvent.id + " (" + str(room.currentEvent.numberPeople) + " people)"
if(room.capacity < room.currentEvent.numberPeople):
out += " (*)"
out += "\n"
return out
def mutate(self): # swap two events
position1 = randrange(0, len(self.roomList))
position2 = randrange(0, len(self.roomList))
temp = self.roomList[position1].currentEvent
self.roomList[position1].currentEvent = self.roomList[position2].currentEvent
self.roomList[position2].currentEvent = temp
def fitness(self): # fitness = satisfied people*timeslot
satisfiedPeople = 0
for room in self.roomList:
if(room.currentEvent.numberPeople <= room.capacity):
satisfiedPeople += room.currentEvent.numberPeople
return satisfiedPeople
def crossover(self, otherChromosome): # for each position, choose one element from one of the chromosomes, if possible, otherwise go forward and look for an event that hasn't been inserted yet
firstList = copy.deepcopy(self.roomList)
secondList = copy.deepcopy(otherChromosome.roomList)
firstList = sorted(firstList, key=lambda x:x.id)
secondList = sorted(secondList, key=lambda x:x.id)
crossedList = []
addedEvents = []
for i in range(0, len(firstList)):
if((firstList[i].currentEvent not in addedEvents) and (secondList[i].currentEvent not in addedEvents)):
casualElement = randrange(0,1)
if(casualElement == 0):
crossedList.append(firstList[i])
addedEvents.append(firstList[i].currentEvent)
else:
crossedList.append(secondList[i])
addedEvents.append(secondList[i].currentEvent)
elif((firstList[i].currentEvent not in addedEvents) or (secondList[i].currentEvent not in addedEvents)):
if(firstList[i].currentEvent not in addedEvents):
crossedList.append(firstList[i])
addedEvents.append(firstList[i].currentEvent)
else:
crossedList.append(secondList[i])
addedEvents.append(secondList[i].currentEvent)
else:
j = 0
while j<len(firstList):
if(firstList[j] not in addedEvents):
crossedList.append(firstList[j])
addedEvents.add(firstList[j])
j = len(firstList)
elif(secondList[j] not in addedEvents):
crossedList.append(secondList[j])
addedEvents.add(secondList[j])
j = len(firstList)
else:
j = j+1
return Chromosome(crossedList)
def setRooms(self, rooms):
self.roomList = copy.deepcopy(rooms)
def generateEvents(inEvents, roomList): # given a room list, put events inside the rooms without changing the rooms in other ways
outEvents = []
events = copy.deepcopy(inEvents)
listLength = len(events)
permutation = list(range(listLength))
permutation = random.sample(permutation, len(permutation))
for r in range(0, min(len(permutation), len(roomList))):
outEvents.append(events[permutation[r]])
return outEvents
mu = 0.2 # mutation rate
chi = 0.5 # crossover rate
rooms = []
allEvents = []
lectures = []
timetable = []
chromosomes = []
maxChromosomes = 100
numberLectures = 50
availableTimeslots = 10
numberRooms = 100
totalSatisfied = 0
totalInvolved = 0
# The lines below are used to define the output code
f = open("timetable.html","w")
f.write("<html>")
f.write("<head>")
f.write("</head>")
f.write("<body>")
f.write("<ul>")
for e in range(0, numberLectures):
peopleLecture = randrange(1, 100)
numberTimeslots = randrange(1, 10)
red = str(randrange(100, 220))
green = str(randrange(100, 220))
blue = str(randrange(100, 220))
color = "rgb("+red+","+green+","+blue+")"
lectures.append(Lecture("LECTURE"+str(e), "", peopleLecture, numberTimeslots, color))
f.write("<li>" + lectures[e].id + " - " + str(peopleLecture) + " people - " + str(numberTimeslots) + " timeslots</li>")
allEvents += lectures[e].transformIntoEvents()
f.write("</ul>")
currentTS = 0
for r in range(0, numberRooms): # add capacity to all the rooms
room = Room("","",0,True)
room.fillRandom(r)
rooms.append(copy.deepcopy(room))
for c in range(0, maxChromosomes): # initialize chromosomes
chromosome = Chromosome([])
chromosome.setRooms(rooms)
chromosomes.append(chromosome)
for l in lectures: # define total people involved to give final rate to the room organization
totalInvolved += l.numberPeople*l.timeslots
while(currentTS < availableTimeslots): # for every timeslot
currentTS += 1
events = []
totalPersons = 0
count = 0
for l in range(0, len(lectures)): # split into events and calculat the number of people involved for a given timeslot
minFragment = float('inf')
minEvent = Event("","",0,0,"")
for e in range(0, len(allEvents)):
if(lectures[l].id == allEvents[e].lecture):
if(allEvents[e].fragmentNr < minFragment):
minFragment = allEvents[e].fragmentNr
minEvent = copy.deepcopy(allEvents[e])
events.append(minEvent)
totalPersons += minEvent.numberPeople
newChromosomes = []
for k in range(0, maxChromosomes): # generate new chromosomes for the current timeslot
permutatedEvents = generateEvents(events, rooms)
rooms = []
for r in range(0, min(len(permutatedEvents), len(chromosomes[k].roomList))):
newRoom = copy.deepcopy(chromosomes[k].roomList[r])
newRoom.currentEvent = permutatedEvents[r]
newRoom.isEmpty = False
rooms.append(newRoom)
newChromosomes.append(Chromosome(rooms))
chromosomes = newChromosomes
evolution = True
numberEquals = 0
previousFitness = 0
while(evolution):
count = count + 1
sortedChromosomes = sorted(chromosomes, key=lambda x:x.fitness(), reverse = True) # sort chromosomes by fitness
sortedChromosomes = sortedChromosomes[0:maxChromosomes] # keep only the best chromosomes
if(sortedChromosomes[0].fitness() == previousFitness): # detect no improvement
numberEquals += 1
else:
numberEquals = 0
previousFitness = sortedChromosomes[0].fitness()
toMutate = math.floor(mu*len(sortedChromosomes))
toCrossover = math.floor(chi*len(sortedChromosomes)/2)*2
print("TS " + str(currentTS) + " - Generation " + str(count) + ": " + str(sortedChromosomes[0].fitness()) + " on " + str(totalPersons))
print(sortedChromosomes[0])
if(numberEquals == 10 or sortedChromosomes[0].fitness() == totalPersons): # stopping condition
timetableChromosome = copy.deepcopy(sortedChromosomes[0])
timetable.append(timetableChromosome)
evolution = False
bestEvents = []
for r in range(0, len(sortedChromosomes[0].roomList)):
if(sortedChromosomes[0].roomList[r].currentEvent.numberPeople <= sortedChromosomes[0].roomList[r].capacity):
bestEvents.append(sortedChromosomes[0].roomList[r].currentEvent)
totalSatisfied += sortedChromosomes[0].roomList[r].currentEvent.numberPeople
newAllEvents = []
for ev in range(0, len(allEvents)):
foundEvent = False
for be in range(0, len(bestEvents)):
if(allEvents[ev].id == bestEvents[be].id):
foundEvent = True
if(foundEvent == False):
newAllEvents.append(allEvents[ev])
allEvents = newAllEvents
elite = copy.deepcopy(sortedChromosomes)
elite = elite[0:toCrossover] # define elite
worst = copy.deepcopy(sortedChromosomes[(len(sortedChromosomes) - toMutate):]) # prepare the worst for mutation
childs = []
for c in range(0, len(elite)-1): # apply crossover
childs.append(elite[c].crossover(elite[c+1]))
for m in range(0, len(worst)): # apply mutation
worst[m].mutate()
chromosomes = childs + sortedChromosomes + worst # put all together
# Print the result as an HTML file
f.write("<table style=\"border-collapse: collapse; border: 1px solid black;\">")
for col in range(0, len(timetable[0].roomList)):
f.write("<th style=\"border: 1px solid black; padding: 5px;\">")
f.write(timetable[0].roomList[col].id)
f.write("<br/>")
f.write("<span style=\"font-size: small;\">")
f.write("(max " + str(timetable[0].roomList[col].capacity) +" people)")
f.write("</span>")
f.write("</th>")
for row in range(0, len(timetable)):
f.write("<tr style=\"border: 1px solid black;\">")
for col in range(0, len(timetable[row].roomList)):
f.write("<td style=\"border: 1px solid black; padding: 5px; ")
if(timetable[row].roomList[col].currentEvent.numberPeople <= timetable[row].roomList[col].capacity):
f.write("background-color: " + timetable[row].roomList[col].currentEvent.findLecture(lectures).color + ";\">")
f.write(timetable[row].roomList[col].currentEvent.id)
f.write("<br/>")
f.write("<span style=\"font-size: small;\">")
f.write("(" + str(timetable[row].roomList[col].currentEvent.numberPeople) +" people)")
f.write("</span>")
else:
f.write("\">")
f.write("</td>")
f.write("</tr>")
f.write("</table>")
f.write("There are " + str(totalSatisfied) + " people satisfied on a total of " + str(totalInvolved))
f.write("</body>")
f.write("</html>")
f.close() |
3c101a692f1ed5c596c8b4c64ded2228adb18023 | AyushVachaspati/Mnist_MultiLayerPerceptron_Class | /Mnist.py | 6,065 | 3.65625 | 4 | import numpy as np
import tensorflow as tf
class Mnist:
num_pixels = 28*28
batch_size = 16
num_labels = 10
layers_cells = [800,]
sess = tf.Session()
#model global variables which are required to give input and get output
minimize = None
y_pred = None
pixels = None
labels = None
def __init__(self,num_pixels=28*28,batch_size=16,num_labels=10,layers_cells=[800]):
"""num_pixels : number of input features/pixels in the image. default 28x28.
batch_size : size of batch for mini batch gradient descent. default 16
num_labels : number of digits to be recognized. default 10
layer_cells : list of number of cells in each layer of MLP. defult [800,]"""
self.num_pixels = num_pixels
self.batch_size = batch_size
self.num_labels = num_labels
self.layers_cells = layers_cells
self.pixels = tf.placeholder(dtype = tf.float32, shape = [batch_size, num_pixels])
self.labels = tf.placeholder(dtype = tf.float32, shape = [batch_size,num_labels])
def build_graph(self,):
"""This function builds the graph for the model and initializes the variables to be trained"""
network = [self.pixels]
with tf.variable_scope("hidden_layers"):
for i in range(len(self.layers_cells)):
temp = tf.contrib.layers.fully_connected(network[i],
num_outputs = self.layers_cells[i],
activation_fn=tf.nn.relu)
network.append(temp)
with tf.variable_scope("output_layer"):
output = tf.contrib.layers.fully_connected(network[-1],
num_outputs = self.num_labels,
activation_fn=tf.nn.softmax)
with tf.variable_scope("prediction"):
self.y_pred = tf.argmax(output,axis = 1)
with tf.variable_scope("loss"):
cross_entropy = tf.losses.softmax_cross_entropy(self.labels,output)
learning_rate = 5e-4
self.minimize = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy)
init_op = tf.global_variables_initializer()
self.sess.run(init_op)
def save_model(self):
"""This function saves the variable states for the trained model in order to restore it later.
Directory saved_model must exist"""
saver = tf.train.Saver()
path = saver.save(self.sess,"./saved_model/model.ckpt")
print "Model saved @ " + path
return path
def restore_model(self):
"""This function restores a previously saved model
from saved_model directory"""
saver = tf.train.Saver()
saver.restore(self.sess, "./saved_model/model.ckpt")
def get_one_hot_labels(self,labels):
"""labels: batch size number of labels"""
encoded_labels = np.zeros([self.batch_size, self.num_labels])
for i in range(len(labels)):
encoded_labels[i][labels[i]] = 1
return encoded_labels
def get_accuracy(self,test_pixels, test_labels):
"""This function tests the accuracy of the current model on the test set.
test_pixels: matrix of pixels values for the test set
test_labels: the labels corresponding to the pixels"""
no_of_batches = len(test_pixels)/self.batch_size
ptr = 0
total = 0
correct = 0
for i in range(no_of_batches):
x = test_pixels[ptr:ptr+self.batch_size]
y = self.get_one_hot_labels(test_labels[ptr:ptr+self.batch_size])
pred_labels = self.sess.run(self.y_pred,{self.pixels: x, self.labels: y})
correct += sum(pred_labels == test_labels[ptr:ptr+self.batch_size])
total += len(pred_labels)
ptr += self.batch_size
return (correct*100.0)/total
def predict_labels(self, pixels):
"""Takes a matrix of pixels for which the labels are to be predicted and returns the
predicted labels for the same as an numpy array"""
pred_labels = []
#normalization of input features
pixels = (pixels - pixels.min())/float(pixels.max()-pixels.min())
no_of_batches = len(pixels)/self.batch_size
ptr = 0
for i in range(no_of_batches):
x = pixels[ptr:ptr+self.batch_size]
temp = self.sess.run(self.y_pred,{self.pixels: x})
pred_labels += list(temp)
ptr += self.batch_size
x = pixels[ptr : ]
for i in range(self.batch_size - len(x)):
x = np.append(x,[np.zeros((self.num_pixels))],axis=0)
temp = self.sess.run(self.y_pred,{self.pixels: x})
pred_labels += list(temp)
return np.array(pred_labels[:len(pixels)])
def train(self,epoch,train_pixels,train_labels,test_pixels,test_labels):
#normalize the pixel data
train_pixels = (train_pixels - train_pixels.min())/float(train_pixels.max()-train_pixels.min())
test_pixels = (test_pixels - test_pixels.min())/float(test_pixels.max()-test_pixels.min())
folder_id = "1BcFfaaQ2dSjkRb-Vn1zwROMAHB_eGl-h" #Mnist folder in google drive
filename = "saved_model.tar.gz"
curr_accuracy = 0
saved_accuracy = 0
for i in range(epoch):
no_of_batches = len(train_pixels)/self.batch_size
ptr = 0
for j in range(no_of_batches):
if j%1000 == 0 :
print j
x = train_pixels[ptr:ptr+self.batch_size]
y = self.get_one_hot_labels(train_labels[ptr:ptr+self.batch_size])
self.sess.run(self.minimize,{self.pixels: x, self.labels: y})
ptr+= self.batch_size
curr_accuracy = self.get_accuracy(test_pixels,test_labels)
print "accuracy = " + str(curr_accuracy)
if curr_accuracy >= saved_accuracy:
self.save_model()
saved_accuracy= curr_accuracy
|
2b06ca32a7c854f3458acfa7e6b330f25566ebfe | Billshimmer/blogs | /algorithm_problem/interleaving_string.py | 855 | 3.53125 | 4 | #!/usr/bin/python
# -*- coding: latin-1 -*-
# leetcode 97
class Solution(object):
def isInterleave(self, s1, s2, s3):
m, n = len(s1), len(s2)
if len(s3) != m + n:
return False
dp = [[False for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(m+1):
for j in range(n+1):
if i==0 and j==0:
dp[i][j] = True
elif i==0:
dp[i][j] = dp[i][j-1] and s2[j-1] == s3[i+j-1]
elif j==0:
dp[i][j] = dp[i-1][j] and s1[i-1] == s3[i+j-1]
else:
dp[i][j] = (dp[i-1][j] and s1[i-1] == s3[i+j-1]) or (dp[i][j-1] and s2[j-1] == s3[i+j-1])
print dp
return dp[m][n]
if __name__ == "__main__":
print(Solution().isInterleave('aa', 'bb', 'aabb')) |
53053109050ae1d774688baab54d957bfa48fe1b | Isaac-Lee/BOJ-Algorithm | /Python_Solutions/test2.py | 638 | 3.671875 | 4 | from collections import deque
def neighbors(current, grid):
x, y = current
for i in range(x-1, x+2):
for j in range(y-1, y+2):
if i == x and j == y:
continue
if 0 <= i < len(grid) and 0 <= j < len(grid[0]):
yield i, j
def bfs(grid, start, end):
queue = deque([start])
visited = {start}
while queue:
current = queue.popleft()
if current == end:
return True
for next in neighbors(current, grid):
if next not in visited:
visited.add(next)
queue.append(next)
return False
|
e5aea9a3a280480983cf3a2df73fe7d1b186ad43 | leoorshii/Udacity-samples | /entropy.py | 354 | 3.5 | 4 | import numpy as np
# Write a function that takes as input two lists Y, P,
# and returns the float corresponding to their cross-entropy.
def cross_entropy(Y, P):
R = np.multiply(Y, np.log(P)) + np.multiply(np.subtract(1,Y), np.log(np.subtract(1,P)))
pass
return np.sum(-R)
P = [0.4, 0.6, 0.1, 0.5]
Y = [1, 0, 1, 1]
print(cross_entropy(Y, P)) |
d8aeb7d5e9e2210f16855882c5e036e40eb4be42 | halkernel/data-structure-and-algorithms | /search-strategies/node.py | 368 | 3.578125 | 4 |
class Node:
def __init__(self, state, parent):
self.state = state
self.parent = parent
def reveal(self):
for i in range(3):
print ("{} {} {}".format(*self.state[3*i:3*i+3]))
print()
def z_index(self):
return self.state.index(0)
def __repr__(self):
return '<Node {}>'.format(self.state)
|
27724aad83b927b8ee363bc54419ac0c6a83bc9a | MichelPinho/exerc-cios | /Desafio_70_Preço_de_Produto.py | 945 | 3.875 | 4 | # Crie um programa que leia o nome e o preço de vários produtos. O programa deverá
# perguntar se o usuário vai continuar ou não. No final, mostre:
# qual é o total gasto na compra.
# quantos produtos custam mais de R$1000.
# qual é o nome do produto mais barato.
totmil = preço = soma = cont = 0
barato = ' '
while True:
nome = str(input('Nome do produto: '))
preço = float(input('Preço do produto: '))
soma += preço
cont += 1
if preço > 1000:
totmil += 1
if cont == 1 or preço < menor:
menor = preço
barato = nome
continuar = ' '
while continuar not in 'SN':
continuar = str(input('Deseja continuar [S/N]')).upper().strip()[0]
if continuar == 'N':
break
print(f'Foram comprados {totmil} unidades acima de R$ 1.000,00.')
print(f'A soma dos produtos são R$ {soma:.2f}')
print(f'O produto mais barato é {barato} e o preço é R$ {menor}')
|
7fe7c58a225358f4a23bd4e1ffd28055835321aa | anirudhbiyani-zz/random-scripts | /DuplicateFileChecker.py | 1,394 | 3.8125 | 4 | #!/usr/bin/env python
'''
Checks for duplicate files in a particular given directory based on SHA256 hashes.
'''
__author__ = "Aniruddha Biyani"
__version__ = "1.0"
__maintainer__ = "Aniruddha Biyani"
__email__ = "contact@anirudhbiyani.com"
__status__ = "Production"
__date__ = "20150312"
import hashlib, os, pprint, thread
def main():
print 'Please enter the absolute path in the input.'
dirname = raw_input('Enter the directory in which you want to find the duplicates: ')
dirname = dirname.strip()
allsizes = []
duplicates = set()
for (thisDir, subsHere, filesHere) in os.walk(dirname):
for filename in filesHere:
# if filename.endswith('.py'): This to check for a particular type of file.
fullname = os.path.join(thisDir, filename)
# fullsize = os.path.getsize(fullname)
with open(fullname, "rb") as f:
contents = f.read()
sha2hash = hashlib.sha256(contents).hexdigest()
allsizes.append((fullname, sha2hash))
# pprint.pprint(allsizes) - Just a debug to list the whole "list".
for intr in allsizes:
for i in allsizes:
if intr != i:
if i[0] not in duplicates:
if intr[1] == i[1]:
print intr[0] + " is a duplicate of file " + i[0]
duplicates.add(intr[0])
if __name__ == '__main__':
main()
|
7a7f7f473f83d2cdfd117459356e5cfb673f5439 | polyguo/algomolbiol | /Graph.py | 13,233 | 3.546875 | 4 | from Bio import SeqIO
#
# Class Description Comming Soon
#
class Graph:
"""A simple Graph class"""
#
# This method create the empty members of the class
#
def __init__(self):
self.vertexhash = []
self.a19merhash={}
self.adjlist=[]
self.reverse=[]
#
# Method maps vertices to an index and viceversa, and fills and adjacency list
# of overlapping vertices, using sequence reads from a file.
#
def initWithSeqReads(self,file,type):
k = 20 # Edge size, vertex size is k-1
for record in SeqIO.parse(file, type):
for i in range(0, len(record) - (k-2)):
edgeseq = str(record[i:i+k].seq)
source = edgeseq[:k-1]
sink = edgeseq[1:]
for vertex in [source, sink]:
if vertex not in self.a19merhash:
# For each new vertex, maps the vertex to a unique index and appends
# an empty list to the adjacency list
self.a19merhash[vertex] = len(self.a19merhash)
self.vertexhash.append(vertex)
self.adjlist.append([])
self.reverse.append([])
# Fills in the adjacency list
self.adjlist[self.a19merhash[source]].append(self.a19merhash[sink])
self.reverse[self.a19merhash[sink]].append(self.a19merhash[source])
def initWithFile(file):
return 'not implemented yet'
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# This method initialize the graph members with the edges and vertex in
# the EdgesList.
# Input:
# EdgesList is a list that contain a list for each edges in the graph.
# Example [["V1","V2"],["V2","V3"]] for the graph V1->V2->V3.
# Output: none
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def initWithEdges(self,EdgesList):
for i in range(0,len(EdgesList)):
for e in EdgesList[i]:
if not(e in self.a19merhash):
if (not(len(self.a19merhash))):
self.a19merhash[e] = 0
self.vertexhash.append(e)
else:
self.a19merhash[e] = len(self.a19merhash)
self.vertexhash.append(e)
# Filling the adjacency list with empty list
for i in range(0,len(self.a19merhash)):
self.adjlist.append([])
self.reverse.append([])
# Filling the adjacency list
for i in range(0,len(EdgesList)):
self.adjlist[self.a19merhash[EdgesList[i][0]]].append(self.a19merhash[EdgesList[i][1]])
self.reverse[self.a19merhash[EdgesList[i][1]]].append(self.a19merhash[EdgesList[i][0]])
#
# Return a list with the degree of each vertex
#
def vertexDegrees(self):
degrees = [];
for i in range(0,len(self.adjlist)):
degrees.append(len(self.adjlist[i]))
return degrees
#
# Return a the degree of the input vertex
#
def vertexDegree(self,vertex):
return len(self.adjlist[vertex])
def indegree(self, vertex):
"Compute the indegree of the given VERTEX."
return len(self.reverse[vertex])
#
# Create a file tha can be imported to cytoscape for visualise the graph
#
def createCytoscapeFile(self,filepath):
OutFile = open(filepath,'w')
for vout in range(0,len(self.adjlist)):
for vin in self.adjlist[vout]:
OutFile.write(self.vertexhash[vout]+" predecessor "+self.vertexhash[vin]+"\n")
OutFile.close()
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Breadth-First Search Method: This methos apply a breadth-first search
# for find all the vertex that can be reach from a given source vertex s.
# Input:
# s <the source vertex.>
# Output:
# visited <a list with the verxter that can be reach from the source.>
#
# Last update(03/28/2012)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def bfs(self,s):
color=[]
distance=[]
predecessor=[]
visited = []
for i in range(0,len(self.vertexhash)):
color.append('W')
distance.append(())
predecessor.append('NIL')
color[s] = 'G'
distance[s] = 0
predecessor[s] = 'NIL'
Q = []
Q.append(s)
while (len(Q) != 0):
u = Q.pop(0)
for v in self.adjlist[u]:
if (color[v] == 'W'):
color[v] = 'G'
distance[v] = distance[u]+1
predecessor[v] = u
Q.append(v)
color[u] = 'B'
visited.append(u);
return visited
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Breadth-First Search Reverse Method: This methos apply a breadth-first
# search for find all the vertex that can be reach from a given source
# vertex s, but traversing the graph in reverse direction.
# Input:
# s <the source vertex.>
# Output:
# visited <a list with the verxter that can be reach from the source.>
#
# Last update(03/28/2012)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def bfsr(self,s):
color=[]
distance=[]
predecessor=[]
visited = []
for i in range(0,len(self.vertexhash)):
color.append('W')
distance.append(())
predecessor.append('NIL')
color[s] = 'G'
distance[s] = 0
predecessor[s] = 'NIL'
Q = []
Q.append(s)
while (len(Q) != 0):
u = Q.pop(0)
for v in self.reverse[u]:
if (color[v] == 'W'):
color[v] = 'G'
distance[v] = distance[u]+1
predecessor[v] = u
Q.append(v)
color[u] = 'B'
visited.append(u);
return visited
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Breadth-First Search Bi-directional Method: This methos apply a
# breadth-first search for find all the vertex that can be reach from a
# given source vertex s, but traversing the graph in both directions.
# Input:
# s <the source vertex.>
# Output:
# visited <a list with the verxter that can be reach from the source.>
#
# Last update(03/28/2012)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def bfsbd(self,s):
color=[]
distance=[]
predecessor=[]
visited = []
for i in range(0,len(self.vertexhash)):
color.append('W')
distance.append(())
predecessor.append('NIL')
color[s] = 'G'
distance[s] = 0
predecessor[s] = 'NIL'
Q = []
Q.append(s)
while (len(Q) != 0):
u = Q.pop(0)
bothdirection = self.reverse[u][:] # make a copy, instead of aliasing reverse and killing the graph
bothdirection.extend(self.adjlist[u])
bothdirection = list(set(bothdirection))
for v in bothdirection:
if (color[v] == 'W'):
color[v] = 'G'
distance[v] = distance[u]+1
predecessor[v] = u
Q.append(v)
color[u] = 'B'
visited.append(u);
return visited
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Conected Components Method: This methos find the numeber of connected
# components in the graph.
#
# Input:
# <none>
# Output:
# count <the number of connected componentes in the graph>
#
# Last update(03/28/2012)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def cc(self):
count = 0
color=[]
def paint(v):
color[v] = 'B'
return
for i in range(0,len(self.vertexhash)):
color.append('W')
while color.count('W'):
visited = self.bfsbd(color.index('W'))
map(paint,visited)
count = count + 1
return count
def transposed(self):
transposed = {i:[] for i in range(len(self.vertexhash))}
for vertex in range(len(self.vertexhash)):
for neighbor in self.adjlist[vertex]:
transposed[neighbor].append(vertex)
return transposed
def finishorder(self, order):
for v in set(order):
order.remove(v)
return order
def scc(self):
def dfs(vertex,neighbors,whole):
visited = []
def dfsaux(vertex):
def dfsrec(vertex):
visited.append(vertex)
collect=[]
for neighbor in neighbors[vertex]:
if neighbor not in visited:
collect.append(neighbor)
collect += dfsrec(neighbor)
collect.append(neighbor)
return collect
result = [vertex]
result += dfsrec(vertex)
result.append(vertex)
if whole:
rest = list(set(neighbors.keys()).difference(result))
while rest:
result.append(rest[0])
result += dfsrec(rest[0])
result.append(rest[0])
rest = list(set(neighbors.keys()).difference(result))
return result
return dfsaux(vertex)
adjacencies = {i:self.adjlist[i] for i in range(len(self.adjlist))}
S = self.finishorder(dfs(0,adjacencies,True))
transposed = self.transposed()
components=0
while S:
v=S.pop()
component=list(set(dfs(v,transposed,False)))
for vertex in component:
if vertex in S:
S.remove(vertex)
for adjacency in transposed.itervalues():
if vertex in adjacency:
adjacency.remove(vertex)
components += 1
return components
def undirected(self):
undirected = [[]*i for i in xrange(len(self.vertexhash))]
for i in xrange(len(self.vertexhash)):
undirected[i]=self.adjlist[i]+self.reverse[i]
return undirected
def components(self):
undirected=self.undirected()
def known(here):
visited=[]
def knownaux(vertices, visited):
neighbours=[]
for vertex in vertices:
for neighbour in undirected[vertex]:
if neighbour not in visited:
neighbours.append(neighbour)
if neighbours:
return knownaux(neighbours, visited+neighbours)
else:
return visited
return knownaux([here],visited)
def componentaux(vertices):
if vertices:
return 1+componentaux(list(set(vertices).difference(known(vertices[0]))))
else:
return 0
return componentaux(self.a19merhash.values())
# # # # # # # # # # # # # # # # # # # # # # # # # #
# _____ _ ______ #
# |_ _| | | |___ / #
# | | ___ ___| |_ / / ___ _ __ ___ #
# | |/ _ | __| __| / / / _ \| '_ \ / _ \ #
# | | __|__ \ |_ ./ /___| (_) | | | | __/ #
# \_/\___|___/\__| \_____/ \___/|_| |_|\___| #
# # # # # # # # # # # # # # # # # # # # # # # # # #
if __name__ == '__main__':
G = Graph()
Edges = [["two","zero"],["two","one"],["three","two"],["three","one"],["fourth","three"],["fourth","two"],["five","three"],["five","fourth"],["six","seven"],["seven","eigth"],["nine","ten"]];
Components = [['c','g'],['g','f'],['f','g'],['h','h'],['d','h'],['c','d'],['d','c'],['g','h'],['a','b'],['b','c'],['b','f'],['e','f'],['b','e'],['e','a']]
G.initWithEdges(list(Edges))
print G.adjlist
print G.reverse
for v in G.vertexhash:
print v
print G.bfsbd(G.a19merhash[v])
print G.cc()
#G.createCytoscapeFile("test.sif");
print "Outdegrees?", G.vertexDegrees()
print "Indegrees", [G.indegree(vertex) for vertex in range(len(G.vertexhash))]
print "Debug"
#for vertex in G.a19merhash.values(): print vertex, G.adjlist[vertex],G.transposed()[vertex]
print "Strongly Connected Components", G.scc()
print "Connected Components", G.components()
## read a small test sequence database.
#G.initWithSeqReads("test.fasta", "fasta")
#print len(G.vertexhash)
#print G.components()
|
c348a516c5d12783a19922a34b603d4c56606ec3 | ziyaad18/LibariesPython | /addition.py | 184 | 3.75 | 4 | def add_numbers(x,y):
'''
>>> add_numbers(1,1)
2
'''
answer = x + y
return answer
def sub_numbers(num1, num2):
answers = num1 - num2
return answers
|
2af9dbc1ec89e9cf0ceddf2728efb2ab5a51d6e7 | Arilonchik/Learning-python | /Eltech.py | 693 | 3.609375 | 4 | import math
while True:
com = input()
if com == 'a':
p, q = map(float, input().split('+j'))
print('p=', p)
print('q=j*', q)
am = math.sqrt((p**2) + q**2)
print('Am=', am)
if p > 0:
psi = math.degrees(math.atan(q/p))
if p < 0:
psi = math.degrees(math.atan(q/p)) + 180
print('psi =', psi)
print(f'ans={am}*e^j{psi}')
if com == 'c':
am, psi = map(float, input().split('e'))
print('Am=', am)
print('psi=', psi)
p = am*(math.cos(math.radians(psi)))
q = am*(math.sin(math.radians(psi)))
print(f'p={p}, q={q}')
print(f'ans = {p} {q}j') |
5376559a181ddbc12ce1bccf265984c31b279ffb | musungur/subClass_Private-Public_Methods | /empl-class.py | 1,996 | 3.9375 | 4 | # working with class
class Employees:
"""This is employees records"""
def __init__(self,name,idn,birth,status,dept,post):
self.name = name
self.id = idn
self.birth = birth
self.merital = status
self.department = dept
self.title = post
pass
# intro
def __str__(self):
return f"My name is {self.name}. I have joined as {self.title} in {self.department}"
pass
# directors details
def __directors(self):
return f"{self.name},{self.id},{self.merital},{self.department},{self.title}"
# instances begins
ict1 = Employees("Robert","29782071",1999,"single","ict","ict manager")
ict2 = Employees("Jitendra","389120",1989,"married","ict","ict head")
print(ict1.name)
print(ict1)
print(ict2.name)
print(ict2)
# who is ict1
print(ict1.__str__())
pass
print(" who is ict2")
print(f"***\nwho is ict2\n{ict2.__str__()}\n***")
print("\n call a private method")
print(ict1._Employees__directors())
# private employees
pass
print("private employees\n")
pass
print(ict1._Employees__directors())
print(ict1)
class Shelys(Employees):
def __init__(self,name,idn,birth,status,post,dept,joining):
super().__init__(name,idn,birth,status,dept,post)
self.joindate = joining
def __repr__(self):
return f"name: {self.name},id: {self.id},Date of birth: {self.birth},Status: {self.merital},Department: {self.department},Job title: {self.title},Joining Date: {self.joindate}"
ict_shelys = Shelys("Zuma","10002",1942,"single","ict","executive ict",1972)
print(isinstance(ict_shelys,Shelys))
print("__str & __repr__ display below")
print(ict_shelys.__repr__())
print(ict_shelys.__str__())
print("**call private method from main class**")
print(ict_shelys._Employees__directors())
print(issubclass(Shelys,Employees))
pass
# appending, inserting into a list
item = []
item.append(ict1.__str__())
item.insert(0,ict_shelys.__repr__())
pass
# display
print("\n****")
print(f"{item}\n***")
|
7a73b64fb60c2029c8be49a37ac080e89e200967 | minhduc9699/PhamMinhDuc-fundamental-c4e16 | /S3/creat.py | 191 | 3.609375 | 4 | fthing = ['C', 'C++', 'C#', 'Java']
print('Hi there, here your favorite things so far')
print(*fthing, sep=', ')
fthing.append(input('name thing you want to add '))
print(*fthing, sep=', ')
|
642db91a5afb29e34a43249d4d04ec707df7e1d6 | samuelcm/classes | /quadrado.py | 431 | 4.0625 | 4 | #Classe Quadrado: Crie uma classe que modele um quadrado:
#Atributos: Tamanho do lado
#Métodos: Mudar valor do Lado, Retornar valor do Lado e calcular Área
class Quadrado():
def __init__ (self, lado = None):
self.lado = lado
def alterar_lado(self):
lado = float(input("Lado: "))
self.lado = lado
def mostrar_lado(self):
print(self.lado)
def area(self):
print(self.lado*2)
|
4163cbd9e0971cb0f4131081c6304d235f0d83e9 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4312/codes/1671_1102.py | 918 | 3.953125 | 4 | # Teste todas as possibilidades de entradas 'H', 'h' e 'x'
# Se seu programa funciona para apenas um caso de tese, isso não quer dizer que ele vai funcionar para todos os outros
# Teste seu código aos poucos.
# Não teste tudo no final, pois fica mais difícil de identificar erros.
# Use as mensagens de erro para corrigir seu código.
from math import*
H = float(input("Digite a altura: "))
h = float(input("Digite o nivel de combustivel: "))
r = float(input("Digite o raio: "))
print("Entradas:" ,H, "," ,r, "," ,h)
if(h < 0 or H < 0 or r < 0):
vol = -1
print("Entrada invalidas")
elif(h < r):
vol = (1./3) * pi * h**2 * (3 * r - h)
elif(h < H - r):
vol = (2./3) * pi * r**3 + pi * r**2 * (h - r)
elif(h <= H):
vol = (4./3) * pi * r**3 + pi * r**2 * (H - 2 * r) - (1/3) * pi * (H - h)**2 * (3 * r - H + h )
else:
vol = -1
print("Entrada invalidas")
msg = round(vol, 6)
print("Volume:" , msg , "litros")
|
a2ab1898246543f214a9719ed6b482eb2f4b4270 | RyanLewisJr/Python-Tree | /binary_tree1.py | 5,061 | 3.8125 | 4 |
class TNode:
def __init__(self, elem=None, left=None, right=None):
self.elem = elem
self.left = left
self.right = right
class Tree:
def __init__(self):
self.root = TNode()
def add(self, elem):
node = TNode(elem)
if not self.root:
self.root = node
return
else:
queue = []
queue.append(self.root)
while queue:
cur_node = queue.pop()
if cur_node.left is None:
cur_node.left = node
elif cur_node.right is None:
cur_node.right = node
else:
queue.append(cur_node.left)
queue.append(cur_node.right)
def preorder(self, root):
if root:
print(root.elem)
self.preorder(root.left)
self.preorder(root.right)
def inorder(self, root):
self.inorder(root.left)
if root:
print(root.elem)
self.inorder(root.right)
def postorder(self, root):
self.postorder(root.left)
self.postorder(root.right)
if root:
print(root.elem)
def level_order(self, root):
if not root:
return
queue = []
queue.append(root)
while queue:
cur_node = queue.pop()
print(cur_node.elem)
if cur_node.left:
queue.append(cur_node.left)
if cur_node.right:
queue.append(cur_node.right)
def height(self, root):
if not root:
return 0
elif not root.left and not root.right:
return 1
else:
hl = self.height(root.left)
hr = self.height(root.right)
return max(hl, hr)+1
def Nodes(self, root):
if not root:
return 0
elif not root.left and not root.right:
return 1
else:
return self.Nodes(root.left)+self.Nodes(root.right)+1
def Leaves(self, root):
if not root:
return 0
elif not root.left and not root.right:
return 1
else:
return self.Leaves(root.left)+self.Leaves(root.right)
def Non_Leaves(self, root):
return self.Nodes(root)-self.Leaves(root)
def Symmetry(self, root):
if not root:
return True
elif not root.left and not root.right:
return True
elif not root.left or not root.right:
return False
else:
l = self.Symmetry(root.left)
r = self.Symmetry(root.right)
return l & r
def reverse(self, root):
tmp = root.left
root.left = root.right
root.right = tmp
self.reverse(root.left)
self.reverse(root.right)
def width(self, root):
if not root:
return 0
queue = []
queue.append(root)
width = 0
count = 0
lastNode = root
newLastNode = None
while queue:
cur_node = queue.pop()
count += 1
if cur_node.left:
queue.append(cur_node.left)
newLastNode = cur_node.left
if cur_node.right:
queue.append(cur_node.right)
newLastNode = cur_node.right
if cur_node is lastNode:
lastNode = newLastNode
if count > width:
width = count
count = 0
def Kth_Nodes(self, root, k):
if k is 0 or not root:
return 0
elif not root.left and not root.right:
return 1
else:
return self.Kth_Nodes(root.left, k-1)+self.Kth_Nodes(root.right, k-1)
def Haff_calc(self, root):
if not root:
return 0
queue = []
queue.append(root)
h = 1
total = 0
lastNode = root
newlastNode = None
while queue:
cur_node = queue.pop()
total += h*cur_node
if cur_node.left:
queue.append(cur_node.left)
newlastNode = cur_node.left
if cur_node.right:
queue.append(cur_node.right)
newlastNode = cur_node.right
if cur_node is lastNode:
lastNode = newlastNode
h += 1
def Leaf(self, root):
if not root:
return
elif not root.left and not root.right:
print(root.elem)
else:
self.Leaf(root.left)
self.Leaf(root.right)
def same(self, root1, root2):
if not root1 and not root2:
return True
elif not root1 or not root2:
return False
else:
hl = self.same(root1.left, root2.left)
hr = self.same(root1.right, root2.right)
return hl & hr
t = Tree()
for i in range(16):
t.add(i)
t.preorder(t.root)
t.inorder(t.root)
t.postorder(t.root)
|
c7c073b1cecc9157cac264fb89097e95847daf45 | pyltsin/dlcourse_ai | /assignments/assignment2/model.py | 2,783 | 3.5 | 4 | import numpy as np
from layers import FullyConnectedLayer, ReLULayer, softmax_with_cross_entropy, l2_regularization
class TwoLayerNet:
""" Neural network with two fully connected layers """
def __init__(self, hidden_layer_size, i, o, reg):
"""
Initializes the neural network
Arguments:
hidden_layer_size, int - number of neurons in the hidden layer
reg, float - L2 regularization strength
"""
self.reg = reg
self.layers = []
for num_layer in range(1):
self.layers.append(FullyConnectedLayer(i,hidden_layer_size))
self.layers.append(ReLULayer())
self.layers.append(FullyConnectedLayer(hidden_layer_size,o))
def compute_loss_and_gradients(self, X, y):
"""
Computes total loss and updates parameter gradients
on a batch of training examples
Arguments:
X, np array (batch_size, input_features) - input data
y, np array of int (batch_size) - classes
"""
# TODO Compute loss and fill param gradients
# by running forward and backward passes through the model
# After that, implement l2 regularization on all params
# Hint: use self.params()
X_next = X.copy()
for layer in self.layers:
X_next = layer.forward(X_next)
loss, grad = softmax_with_cross_entropy(X_next, y)
loss_l2 = 0
for params in self.params():
w = self.params()[params]
loss_d, grad_d = l2_regularization(w.value, self.reg)
loss_l2+=loss_d
loss+=loss_l2
for layer in reversed(self.layers):
grad = layer.backward(grad)
grad_l2 = 0
for params in layer.params():
w = layer.params()[params]
loss_d, grad_d = l2_regularization(w.value, self.reg)
w.grad+=grad_d
grad+=grad_l2
return loss
def predict(self, X):
"""
Produces classifier predictions on the set
Arguments:
X, np array (test_samples, num_features)
Returns:
y_pred, np.array of int (test_samples)
"""
# TODO: Implement predict
# Hint: some of the code of the compute_loss_and_gradients
# can be reused
for layer in self.layers:
X = layer.forward(X)
y_pred = np.argmax(X, axis=1)
return y_pred
def params(self):
result = {}
for layer_num in range(len(self.layers)):
for i in self.layers[layer_num].params():
result[str(layer_num) + "_" + i] = self.layers[layer_num].params()[i]
return result
|
35c175bfa8e6c68bb5cb4996044e3a840e79bb23 | binzi6/PythonStudy20200302-1 | /PythonStudy20200302_1.py | 1,457 | 4.3125 | 4 |
print ('Hello, Python!')
# 第一个注释
print ("Hello, Python!") # 第二个注释
'''
这是多行注释,使用单引号。
这是多行注释,使用单引号。
这是多行注释,使用单引号。
'''
"""
这是多行注释,使用双引号。
这是多行注释,使用双引号。
这是多行注释,使用双引号。
"""
#作用域同时缩进 不用{}
if True:
print ("Answer")
print ("True")
else:
print ("Answer")
# 没有严格缩进,在执行时会报错
#print ("False")
#数字类型计算 代码多行显示使用\
item_one =1;item_two=2;item_three=3.567;
total = item_one + \
item_two + \
item_three
print (total)
#字符串
word = 'word'
sentence = "这是一个句子。"
paragraph = """这是一个段落。
包含了多个语句"""
print (word,sentence,paragraph)
#循环 数组
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
for ssddfd in days:
print (ssddfd)
a = b = c = 1
print (a,b,c)
a, b, c = 1, 2, "john"
print (a,b,c)
#字符串截取
s = 'abcdef'
print(s[1:5])
str = 'Hello World!'
print (str) # 输出完整字符串
print (str[0]) # 输出字符串中的第一个字符
print (str[2:5]) # 输出字符串中第三个至第六个之间的字符串
print (str[2:]) # 输出从第三个字符开始的字符串
print (str * 2) # 输出字符串两次
print (str + "TEST") # 输出连接的字符串
|
2f141778308a351b53577c8d923adf9b285dad2e | RichardRosario/python-workouts | /working_files.py | 2,445 | 3.53125 | 4 | import csv
from datetime import datetime
# Create a string called first_forty that is comprised of the first 40 characters of emotion_words2.txt.
path = "D:\python-workouts\workouts\AAL_data.csv"
file = open(path, newline='')
reader = csv.reader(file)
header = next(reader)
# print(header)
data = []
for row in reader:
#row = ['date', 'open', 'high', 'low', 'close', 'volume', 'Name']
date = datetime.strptime(row[0], '%Y-%m-%d')
open_price = float(row[1])
high_price = float(row[2])
low_price = float(row[3])
close_price = float(row[4])
trade_vol = int(row[5])
name = str(row[6])
data.append([date, open_price, high_price,
low_price, close_price, trade_vol, name])
# compute and store daily returns
returns_path = "D:\python-workouts\workouts\AAL_returns.csv"
file = open(returns_path, 'w')
writer = csv.writer(file)
writer.writerow(['Date', "Return"])
# iterate through the data
for i in range(len(data)-1):
todays_row = data[i]
# print(todays_row)
todays_date = todays_row[0]
todays_price = todays_row[1]
yesterday_row = data[i+1]
yesterday_price = yesterday_row[1]
daily_return = (todays_price - yesterday_price) / yesterday_price
# writer.writerow([todays_date, daily_return])
formatted_date = todays_date.strftime('%m/%d/%Y')
writer.writerow([formatted_date, daily_return])
# print("Date: {}, Daily ROI: {}".format(formatted_date, daily_return))
# Write code to find out how many lines are in the file emotion_words.txt as shown above. Save this value to the variable num_lines. Do not use the len method.
# num_lines = sum(
# [1 for i in open("D:\python-workouts\workouts\course4\sample.txt", "r").readlines() if i.strip()])
# print(num_lines)
# find number of characters in a file
f = open("D:\python-workouts\workouts\AAL_returns.csv", "r")
data = f.read().replace(" ", "")
# print(data)
num_chars = len(data)
# print("There are {} of characters in this file!".format(num_chars))
line = open('SP500.txt', 'r').readlines()
# print(line)
sum = 0
list = []
for lin in line[6:18]:
lin = lin.split(',')
sum += float(lin[1])
list += [lin[5]]
mean_SP = sum/12
# print(mean_SP)
interest = list[0]
for i in range(len(list)):
if list[i] > interest:
interest = list[i]
max_interest = float(interest)
print(max_interest)
|
4505c69542bc8850c7e3a94cf54d1fb0d3562d58 | pomacb/CursorPython | /YoungDevelopers/Homework3/arithmetic_2.2.py | 236 | 3.84375 | 4 | var1 = int(input ("Enter number1: "))
var2 = int(input ("Enter number2: "))
var3 = int(input ("Enter number3: "))
var4 = int(input ("Enter number4: "))
sum1 = var1+var2
sum2 = var3+var4
print ("Result is: {0:.2f}".format (sum1/sum2))
|
49311aae6e04a6e08dc69072120b9ae67b9f50d7 | wenjiazhangvincent/cs131 | /hw1_release/0.py | 154 | 3.625 | 4 | import numpy as np
k1 = np.array((1,4,6,4,1)).reshape(5,1)
k2 = np.array((1,4,6,4,1)).reshape(1,5)
print (k1)
print (k2)
print (k1.shape)
print (k2.shape) |
16e5abb82fbdb55c173baf578ecbb7cdd6603c33 | bharddwaj/Intro-CS-Course | /temp_conversion.py | 1,464 | 4.25 | 4 | '''
Created on Jan 28, 2019
@author: Bharddwaj Vemulapalli
username: bvemulap
I pledge my honor that I have abided by the Stevens Honor System.
'''
from smtpd import program
'''
Put functions at the top of the program
'''
def fahrenheit(celsius):
'''Returns the input Celsius degrees in Fahrenheit'''
return 9/5 * celsius + 32
def celsius(fahrenheit):
'''Returns the input Fahrenheit degrees in Celsius'''
return 5/9 * (fahrenheit - 32)
'''
Call the functions below the function definitions
'''
c = float(input("Enter the degrees in Celsius: "))
f = fahrenheit(c)
# You can print multiple items in one statement if you put a comma after each
#item, it prints a space and then goes on to print the next item
print(c, 'C =', f, 'F')
#You can print this way too, but allowing exactly two decimal places
print('%.2f C = %.2f F' %(c,f))
f = float(input("Enter the degrees in Fahrenheit: "))
c = celsius(f)
print(f,'F =', c,'C')
print('%.2f F = %.2f C' %(f,c))
'''
Try composition of functions.
Converting a Fahrenheit temperature to Celsius and back to Fahrenheit should
give you the original Fahrenheit temperature
'''
print() #print by itself prints a new line
f = float(input("Enter the degrees in Fahrenheit: "))
#Use assert to check if the returned value if equal to the expected value
assert(fahrenheit(celsius(f)) == f)
#No output should be produced unless the assertion fails which means you have
#error either in your code or in your expectation |
60b43031a410e8679c134aa695a892da52639d4d | pabloares/misc-python-exercises | /number-lines-file.py | 454 | 3.546875 | 4 | import sys
NUM_LINES=10
if len(sys.argv) != 3:
print("Missing file(s) name")
quit()
try:
fd = open(sys.argv[1], "r")
except FileNotFoundError:
print("File does not exist")
else:
fdd = open(sys.argv[2], "w")
line = fd.readline()
count = 1
while line != "":
# line = line.rstrip()
count += 1
fdd.write("%d: " % count)
fdd.write(line)
line = fd.readline()
fd.close()
fdd.close()
|
098d69057c1dce11dfed7a33f25be11a7a98da6b | soumilk/100DaysOfCode | /tanaymehta28/Day 07/tf mnist.py | 3,002 | 3.953125 | 4 | # This Neural Network is trained on MNIST image dataset.
# But two great things about this model are:
# 1. It classifies images but it is NOT a Convolutional Network.
# 2. It uses no high-level Tensorflow API (like, tf.keras and tf.estimator or tf.learn)
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('/tmp/data/',one_hot=True)
# Hyper-parameters
batch_size = 150
learning_rate = 0.001
input_neuron = 28*28 #Dimensions of the Input Data
hidden_layer_one = 768 # Number of neurons in the first Hidden layer
hidden_layer_two = 768 # Number of neurons in the Second Hidden layer
hidden_layer_three = 768 # Number of neurons in the Third Layer
output_neuron = 10 # Number of the classes we want to predict
# Basic input and output Placeholders
x = tf.placeholder(tf.float32,[None,input_neuron])
y = tf.placeholder(tf.float32,[None,output_neuron])
# Basic Computation Graph for the Neural Network
def Neural_Network(data):
# Hidden Layer and Output Layer Weights Initialization
hidden_one_w = tf.Variable(tf.random_uniform([input_neuron,hidden_layer_one],seed=12))
hidden_two_w = tf.Variable(tf.random_uniform([hidden_layer_one,hidden_layer_two],seed=12))
hidden_three_w = tf.Variable(tf.random_uniform([hidden_layer_two,hidden_layer_three],seed=12))
output_w = tf.Variable(tf.random_uniform([hidden_layer_three,output_neuron],seed=12))
# Hidden Layer and Output Layer Biases Initialization
hidden_one_bias = tf.Variable(tf.random_uniform([hidden_layer_one],seed=12))
hidden_two_bias = tf.Variable(tf.random_uniform([hidden_layer_two],seed=12))
hidden_three_bias = tf.Variable(tf.random_uniform([hidden_layer_three],seed=12))
output_bias = tf.Variable(tf.random_uniform([output_neuron],seed=12))
# Main Computation Graph for Matrix Multiplication and Addition
h_1 = tf.add(tf.matmul(x,hidden_one_w),hidden_one_bias)
h_2 = tf.add(tf.matmul(h_1,hidden_two_w),hidden_two_bias)
h_3 = tf.add(tf.matmul(h_2,hidden_three_w),hidden_three_bias)
out = tf.add(tf.matmul(h_3,output_w),output_bias)
return out
# Training the Neural Network
def train_neural_network(x):
prediction = Neural_Network(x)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for epoch in range(25):
epoch_loss = 0
for _ in range(int(mnist.train.num_examples/batch_size)):
epoch_x, epoch_y = mnist.train.next_batch(batch_size)
_, c = sess.run([optimizer,cost], feed_dict={x: epoch_x,y: epoch_y})
epoch_loss += c
print('Epoch',epoch,'completed out of',epochs,'loss:',epoch_loss)
correct = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct,'float'))
print('Accuracy:',accuracy.eval({x: mnist.test.images, y:mnist.test.labels}))
# Function Call
train_neural_network(x)
|
866bc66ac979726153fee2824bc19a7229a47a04 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/c2aaee6311944f41ad6ee958481af8b1.py | 501 | 4.21875 | 4 | #
# Skeleton file for the Python "Bob" exercise.
#
def hey(what):
#check if what is a string and if there is \t in what
if not what or "\t" in what:
return "Fine. Be that way!"
#if what is upper we are screaming
if what.isupper() == True:
return "Whoa, chill out!"
#if what stripped of spaces ends with ? that means we have a question
if what.strip()[-1] == "?":
return "Sure."
#for anything else we don't care
else:
return "Whatever."
|
c9d700dfb9323caec0f98542041700237dd526f2 | waveman68/MIT6001x_Intro2CS_and_Python | /L6_ndigits.py | 766 | 3.890625 | 4 | __author__ = 'Sam Broderick'
# Note to grader: the """DocString""" adheres to Python style guide.
def ndigits(x):
"""
This function takes an integer and returns its number of digits
:param x: int - input
:rtype: int - number of digits in x
"""
if type(x) != int: # basic error handling of non-int
print('The value of x is not an integer')
return None
if abs(x) < 10:
return 1 # single digit case
x_recursive = int((x - x % 10)/10) # remove last digit using modulo
return 1 + ndigits(x_recursive)
# ================================
# Unit tests
# ================================
# print(ndigits(-1234))
# print(ndigits(-12345678))
# print(ndigits(42.12))
|
2d0ff0bc69baf352a52e3b4ad57620f0127dc139 | lmacionis/Exercises | /14. List Algorithms/Exercise_1.py | 8,423 | 4.375 | 4 | """
The section in this chapter called Alice in Wonderland, again! started with the observation that the merge
algorithm uses a pattern that can be reused in other situations. Adapt the merge algorithm to write
each of these functions, as was suggested there:
a. Return only those items that are present in both lists.
b. Return only those items that are present in the first list, but not in the second.
c. Return only those items that are present in the second list, but not in the first.
d. Return items that are present in either the first or the second list.
e. Return items from the first list that are not eliminated by a matching element in the second list.
In this case, an item in the second list “knocks out” just one matching item in the first list.
This operation is sometimes called bagdiff. For example bagdiff([5,7,11,11,11,12,13], [7,8,11])
would return [5,11,11,12,13]
"""
# a. Return only those items that are present in both lists.
# I think this is the correct way of doing it. Thou not sure.
def merge(xs, ys):
""" merge sorted lists xs and ys. Return a sorted result """
result = []
xi = 0
yi = 0
while True:
if xi >= len(xs): # If xs list is finished,
return result # And we're done.
if yi >= len(ys): # Same again, but swap roles
return result
# Both lists still have items, copy smaller item to result and add present to result
if xs[xi] == ys[yi]:
result.append(xs[xi])
xi += 1
yi += 1
elif xs[xi] <= ys[yi]:
xi += 1
else:
yi += 1
xs = [1,3,3,4,5,7,9,11,13,15,17,19,24]
ys = [4,5,8,12,16,20,24]
zs = xs+ys
zs.sort()
print(merge(xs, ys))
# b. Return only those items that are present in the first list, but not in the second.
# I think that I misunderstood the condition and returned the duplicates when I needed to remove them
# Lower you will find the right result.
# If the the a part is good, then this is also good.
def merge(xs, ys):
""" merge sorted lists xs and ys. Return a sorted result """
result = []
xi = 0
yi = 0
most_recent_elem = None
while True:
if xi >= len(xs): # If xs list is finished,
return result # And we're done.
if yi >= len(ys): # Same again, but swap roles
return result
# Adding duplicates to result
if xs[xi] != most_recent_elem:
most_recent_elem = xs[xi]
elif xs[xi] == most_recent_elem: # Or you can just use else
result.append(xs[xi])
most_recent_elem = xs[xi]
# Both lists still have items, copy smaller item to result.
if xs[xi] <= ys[yi]:
xi += 1
else:
xi += 1
yi += 1
xs = [1,3,3,4,5,7,9,11,11,13,15,17,19,19]
ys = [4,5,8,12,16,20,24]
zs = xs+ys
zs.sort()
print(merge(xs, ys))
# b. Return only those items that are present in the first list, but not in the second.
# This algorithm compares two lists, removes matching elements from the first list and prints it out.
# I think I needed only to return the first lists elements, but thought it's was too simple
# and that's why I misunderstood the condition
def merge(xs, ys):
""" merge sorted lists xs and ys. Return a sorted result """
result = []
xi = 0
yi = 0
most_recent_elem = None
while True:
if xi >= len(xs): # If xs list is finished,
result.extend(xs[xi:])
return result # And we're done.
if yi >= len(ys): # Same again, but swap roles
result.extend(xs[xi:])
return result
# Both lists still have items, copy smaller and present item to result.
most_recent_elem = ys[yi]
if xs[xi] != most_recent_elem:
if ys[yi] <= xs[xi]:
yi += 1
else:
result.append(xs[xi])
xi += 1
else:
xi += 1
yi += 1
xs = [1,3,3,4,5,7,9,11,11,13,15,17,19,19,24,30,40]
ys = [4,5,8,12,16,20,24,30]
zs = xs+ys
zs.sort()
print(merge(xs, ys))
# c. Return only those items that are present in the second list, but not in the first.
# I think that I misunderstood the condition and returned the duplicates when I needed to remove them
# Lower you will find the right result.
def merge(xs, ys):
""" merge sorted lists xs and ys. Return a sorted result """
result = []
xi = 0
yi = 0
most_recent_elem = None
while True:
if xi >= len(xs): # If xs list is finished,
return result # And we're done.
if yi >= len(ys): # Same again, but swap roles
return result
# Adding duplicates to result
if ys[yi] != most_recent_elem:
most_recent_elem = ys[yi]
else:
result.append(ys[yi])
most_recent_elem = ys[yi]
# Both lists still have items, copy smaller item to result.
if xs[xi] <= ys[yi]:
xi += 1
yi += 1
else:
yi += 1
xs = [1,3,3,4,5,7,9,11,11,13,15,17,19]
ys = [4,4,5,8,8,12,16,20,24,24]
zs = xs+ys
zs.sort()
print(merge(xs, ys))
# c. Return only those items that are present in the second list, but not in the first.
# This algorithm compares two lists, removes matching elements from the second list and prints it out.
# I think I needed only to return the seconds lists elements, but thought it's was too simple
# and that's why I misunderstood the condition.
def merge(xs, ys):
""" merge sorted lists xs and ys. Return a sorted result """
result = []
xi = 0
yi = 0
most_recent_elem = None
while True:
if xi >= len(xs): # If xs list is finished,
result.extend(ys[yi:])
return result # And we're done.
if yi >= len(ys): # Same again, but swap roles
result.extend(ys[yi:])
return result
# Both lists still have items, copy smaller and present item to result.
most_recent_elem = xs[xi]
if ys[yi] != most_recent_elem:
if xs[xi] <= ys[yi]:
xi += 1
else:
result.append(ys[yi])
yi += 1
else:
xi += 1
yi += 1
xs = [1,3,3,4,5,7,9,11,11,13,15,17,19,19,24,40]
ys = [4,5,8,12,16,20,24,30]
zs = xs+ys
zs.sort()
print(merge(xs, ys))
# d. Return items that are present in either the first or the second list.
# I think that's it, but it looks to easy
def merge(xs, ys):
""" merge sorted lists xs and ys. Return a sorted result """
result = []
xi = 0
yi = 0
while True:
if xi >= len(xs): # If xs list is finished,
result.extend(xs[xi:]) # Add remaining items from ys
return result # And we're done.
if yi >= len(ys): # Same again, but swap roles
result.extend(xs[xi:])
return result
# Both lists still have items, copy smaller item to result.
if xs[xi] <= ys[yi]:
result.append(xs[xi])
xi += 1
else:
yi += 1
xs = [1,3,3,4,5,7,9,11,11,13,15,17,19]
ys = [4,4,5,8,8,12,16,20,24,24]
zs = xs+ys
zs.sort()
print(merge(xs, ys))
# e. Return items from the first list that are not eliminated by a matching element in the second list.
# That what I thought I was asked to do in b, c parts.
def merge(xs, ys):
""" merge sorted lists xs and ys. Return a sorted result """
result = []
xi = 0
yi = 0
most_recent_elem = None
while True:
if xi >= len(xs): # If xs list is finished,
result.extend(xs[xi:])
return result # And we're done.
if yi >= len(ys): # Same again, but swap roles
result.extend(xs[xi:])
return result
# Both lists still have items, copy smaller and present item to result.
most_recent_elem = ys[yi]
if xs[xi] != most_recent_elem:
if ys[yi] <= xs[xi]:
yi += 1
else:
result.append(xs[xi])
xi += 1
else:
xi += 1
yi += 1
xs = [5,7,11,11,11,12,13]
ys = [7,8,11]
zs = xs+ys
zs.sort()
print(merge(xs, ys))
|
e484633c0f69c018461f3df2d1a45e143768b9b6 | RamaraoAllamraju/LowesTrainingSessionPYTHON | /day1Python/Test.py | 1,771 | 3.828125 | 4 | '''
Created on Mar 18, 2019
@author: rallamr
'''
from _ast import Num
from selenium.webdriver import opera
### Removing spaces in between string ###
a = "Lowes India PVT LTD "
print(a.strip())
b=""
mylist = a.split(" ")
for lis in mylist:
if(lis!=""):
#print("It is not space")
b = b+lis
print(b)
### EVEN ###
a = 101
for i in range(1,a):
if(i%2==0):
print(i)
### REMOVE all occurances of 2 ###
li = [1,2,3,4,1,1,2,2,2,2,2]
li.remove(2)
print(li)
### REVERSE the list ###
li = [1,2,3,4,5,6,7,2]
li.reverse()
print(li)
li = [1,2,3,4,5,6,7,2]
li.sort(reverse=True)
print(li)
### Program to check number of char in a string
myStr = "Ramarao"
print(len(myStr))
### program to check given number is odd or even
a = 101
if(a%2==0):
print("EVEN")
else:
print("ODD")
### program to find sum in list num = [1,2,3,4,5] using for, while loops
sum = 0
numb = [1,2,3,4,5]
for i in numb:
sum = sum+int(i)
print(sum)
sum = 0
numb = [6,7,8,9,10]
length = len(numb)
while(length!=0):
length = length-1;
sum = sum+numb[length]
print("Latest sum :",sum)
### Program to get elements from list fruits = ["apple","oranges","Grapes"]
fruits = ["apple","oranges","grapes"]
for i in fruits:
print(i)
### program to demonstrate arthamatic operations by accepting user inputs
a = int(input("Enter the a value:"))
b = int(input("Enter the b value:"))
operator = input("Enter the operator:")
if(operator=="*"):
print("Result: ",a*b)
elif(operator=="+"):
print("Result: ",a+b)
elif(operator=="/"):
print("Result: ",a/b)
elif(operator=="%"):
print("Result: ",a%b)
else:
print("Invalid operator") |
735da1e22239288dead9cac41bdc7144dbaf8fd9 | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/pdykey001/question1.py | 1,179 | 3.75 | 4 | """Uct BBS program
Keyoolin Padayachee
16 April 2014
"""
#Creating of the 2 files
file=["42.txt","1015.txt"]
fileRef=["The meaning of life is blah blah blah ...","Computer Science class notes ... simplified\nDo all work\nPass course\nBe happy"]
selection=""
message=""
while selection!="X":
#display the menu when selection is not exit
print("Welcome to UCT BBS")
print("MENU")
print("(E)nter a message")
print("(V)iew message")
print("(L)ist files")
print("(D)isplay file")
print("e(X)it")
selection=input("Enter your selection:\n").upper()
if selection == "X":
print("Goodbye!")
break
elif selection == "E": message=input("Enter the message:\n")
elif selection == "V":
if message=="" : print("The message is: no message yet")
else : print("The message is:",message)
elif selection == "L": print("List of files: "+file[0],file[1],sep=", ")
elif selection == "D":
fileSelect=input("Enter the filename:\n")
if fileSelect in file:
print(fileRef[file.index(fileSelect)])
else: print("File not found")
|
5ef0f240f4457900f50097e955f2c7dc47c1eeee | codingXllama/LearnToProgram | /Step1/HowImportIsYourBirthday.py | 657 | 4.5625 | 5 | # This program checks for how important is your birthday
# Purpose of this program is to understand the purpose and usage of logical and/or operators , and multi if statements with the not keyword
# Getting user's age
userAge = eval(input("Enter your Age: "))
if userAge >= 1 and userAge <= 12:
print("Your Birthday is Important ")
elif userAge == 21 or userAge == 50:
print("Your Birthday is Important !")
# We now check if the user age is less than 65 , then their birthday is important , else their birthday is not important
elif not userAge < 65:
print("Your Birthday is Important!")
else:
print("Your Birthday is Not Important :(")
|
6877a40f9b4683a9c23a461adff0568b9be59710 | MiyabiTane/myLeetCode_ | /May_LeetCoding_Challenge/30_K_Closest_Points_to_Origin_2.py | 1,051 | 3.515625 | 4 | def kClosest(points, K):
def partition(points, l, r):
#一番右側の数字で分ける(左:小さい、右:大きい)時にその数字がどこにくるか
pivot = points[r]
a = l
for i in range(l, r):
if (points[i][0]**2 + points[i][1]**2) <= (pivot[0]**2 + pivot[1]**2):
points[a], points[i] = points[i], points[a]
a += 1
points[a], points[r] = points[r], points[a]
return a
def QuickSort(points, l, r, K):
if l < r:
p = partition(points, l, r)
if p == K:
return
elif p < K:
QuickSort(points, p+1, r, K)
else:
QuickSort(points, l, p-1, K)
QuickSort(points, 0, len(points) - 1, K)
return points[:K]
ans = kClosest([[68, 97], [34, -84], [60, 100], [2, 31], [-27, -38],
[-73, -74], [-55, -39], [62, 91], [62, 92], [-57, -67]], 5)
print(ans)
#参考動画:https: // www.youtube.com/watch?v = ywWBy6J5gz8
|
e83b2b9d28c57b4ba51a349488fbbf859c70f0d3 | Alexvi011/CYPHugoPV | /libro/problemas_resueltos/capitulo2/problema2_2.py | 283 | 3.765625 | 4 | P=int(input("Introduce tu valor P: "))
Q=int(input("Introduce tu valor Q: "))
EXP= (P**3)+(Q**4)-(2*P**2)
if EXP<680:
print(f"Los valores P:{P}, y Q:{Q} satisfacen la expresion")
else:
print(f"Los valores P:{P}, y Q:{Q} no satisfacen la expresion")
print("Fin del programa")
|
678bba897b6979955c02b136ccb500d755f81723 | 26Sir/ceshi | /fangfa/defaultpara.py | 1,068 | 3.921875 | 4 | #conding=utf-8
'''
# def student(age,naem,sex,guoji="中国"):
# return age,naem,sex,guoji
#
# print("任伟","")
def boy(profile,*mytuple):
out_put = ""
for parameter in mytuple:
if not out_put:
out_put = out_put + parameter
else:
out_put = out_put + "," + parameter
return profile ,":",out_put
print (boy('age',"任伟","男","山西运城人","28岁"))
def add(x,**key):
total = x
for arg,value in key.items():
print("hei,加了",arg)
total += value
return total
print(add(10,a=11,b=12,c=13))
def add(x,key):
# 不定长函数,用于页面接口新增参数时不需要改变方法了
total = x
for arg,value in key.items():
print("hei,加了",arg)
total += value
return total
input_dic={"x":11,"y":12}
print(add(10,input_dic))
# lambda
add = lambda x,y : x+y
print(add(1,2))
'''
# map,注意python3中map()返回iterators类型,不再是list类型。进行list转换即可
def sqr(x):
return x ** 2
a = [4,5,8]
print(list(map(sqr,a)))
|
e36ba285d16f0676270d3833d1aa0880e54c8a17 | Llontop-Atencio08/t07_Llontop.Rufasto | /Rufasto_Torres/Bucles.Mientras.py | 1,427 | 3.96875 | 4 | Ejercicio01
#Pedir edad de ingreso a la escuela PNP
edad=10
edad_invalida=(edad<16 or edad >25)
while(edad_invalida):
edad=int(input("ingrese edad:"))
edad_invalida=(edad<16 or edad >25)
#fin_while
print("edad valida:",edad)
#Ejercicio02
#Pedir nota de sustentacion de tesis
nota=0
nota_desaprobada=(nota<12 or edad >20)
while(nota_desaprobada):
nota=int(input("Ingrese nota:"))
nota_desaprobada=(nota<12 or edad >20)
#fin_while
print("Nota aprobada:",nota)
#Ejercicio03
#Pedir puntaje minimo para ingresar a la UNPRG
puntaje=12.20
puntaje_invalido=(puntaje<90.00 or puntaje>300.00)
while(puntaje_invalido):
puntaje=float(input("Ingrese puntaje:"))
puntaje_invalido=(puntaje<90.00 or puntaje>300.00)
#fin_while
print("Puntaje alcanzado:",puntaje)
#Ejercicio04
#Pedir ponderado de un alumno para ver si ocupa el tercio superior
ponderado=9.6
ponderado_no_valido=(ponderado<15.00 or ponderado>20.00)
while(ponderado_no_valido):
ponderado=float(input("Ingrese ponderado:"))
ponderado_no_valido=(ponderado<15.00 or ponderado>20.00)
#fin_while
print("Ponderado valido:",ponderado)
#Ejercicio05
#Pedir temperatura de una persona
temperatura=23.0
temperatura_alta=(temperatura<35.0 or temperatura>38.0)
while(temperatura_alta):
temperatura=float(input("Ingrese temperatura:"))
temperatura_alta=(temperatura<35.0 or temperatura>38.0)
#fin_while
print("Temperatura normal:",temperatura)
|
7e041933596934a5337724b9ce9fb659474a538f | coucoulesr/leetcode | /1008-construct-binary-search/1008-construct-binary-search.py | 1,440 | 4.09375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def bstFromPreorder(self, preorder):
# Special case: input is empty list
if not preorder:
return None
# Preorder condition: first value in input must be root
root = TreeNode(preorder[0])
# Special case: input size 1 (preorder[1::] not safe)
if len(preorder) == 1:
return root
# Call recursive addNode function which adds a node from the root
for value in preorder[1::]:
self.addNode(root, value)
return root
def addNode(self, root, value):
# If value to add is bigger than root, go right
if value > root.val:
# If there is no right child, value becomes right child
if not root.right:
root.right = TreeNode(value)
# If there is a right child, recurse on right child
else:
self.addNode(root.right, value)
# If value is smaller, go left
else:
# If there is no left child, value becomes left child
if not root.left:
root.left = TreeNode(value)
# If there is a left child, recurse on left child
else:
self.addNode(root.left, value) |
2b87bf27245da12d816ec44c9421135a60dd3594 | manutdmohit/pythonprogramexamples | /checktwostringsareanagramsornot.py | 225 | 4.03125 | 4 | s1=input('Enter first string:')
s2=input('Enter second string:')
#print(sorted(s1))
#print(sorted(s2))
if sorted(s1)==sorted(s2):
print('Both strings are anagrams')
else:
print('Both strings are not anagrams')
|
d7d73cfbb8581a204e92522c995e5960295c498a | nsimsofmordor/PythonProjects | /Projects/Python_Tutorials_Corey_Schafer/PPBT6 Conditionals.py | 544 | 4 | 4 | language = 'Python'
if language == 'Python':
print('Language is Python')
elif language == "Java":
print('Language is Java')
print(20*"-")
user = "admin"
logged_in = True
if user == "admin" and not logged_in:
print("Good Credits")
else:
print("Bad Credits")
print(20*"-")
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) # is a and b equal in memory?
print(id(a))
print(id(b))
print(20*"-")
c = a
print(c is a)
# Anything empty, none, or zero will result to false
num = 5
while num != False:
print(num)
num -= 1 |
c3aa7b4916d3dd8018d58b035ef9e5c91315205c | DavidRooban/savinpython | /arms range.py | 302 | 3.828125 | 4 | num=int(input("enter starting range"))
n=int(input("enter ending range"))
for i in range(num,n):
if(i>100000):
print("enter less than 100000")
sum = 0
temp = i
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if i == sum:
print(i)
|
6435492b816541028e17cf1e37306cc35c59b144 | comodoro180/Python | /Course1/Excersice3_1.py | 319 | 3.6875 | 4 | INCREMENT = 1.5
TOP_HRS = 40.0
gross_pay = 0.0
bonus = 0.0
hrs = input("Enter hours:")
hrs = float(hrs)
rate = input("Rate:")
rate = float(rate)
if hrs > TOP_HRS:
bonus = (hrs - TOP_HRS) * (rate * INCREMENT)
gross_pay = bonus + (TOP_HRS * rate)
elif hrs > 0.0:
gross_pay = hrs * rate
print(gross_pay)
|
7fa02099f75e64986e72554af9f62ccfff8c13e6 | fakhirsh/QuranAnalysis | /Src/queries/testQueries.py | 659 | 3.5625 | 4 |
import codecs
# Split each ayah into words
quran = codecs.open('../../Assets/QuranText/quran-simple-clean.txt', 'r', encoding="utf-8")
ayahCount = 0
uniqueWordCount = 0
totalWordCount = 0
uniqueWords = set()
for ayat in quran:
a = ayat.split('|')
chapterNo = a[0]
ayahNo = a[1]
ayahText = (a[2].split('\r'))[0]
ayahWords = ayahText.split(' ')
uniqueWords.update(ayahWords)
totalWordCount += len(ayahWords)
ayahCount += 1
print(uniqueWords)
uniqueWordCount += len(uniqueWords)
print("Total Ayas: ", ayahCount)
print("Total Unique Words: ", uniqueWordCount)
print("Total Words: ", totalWordCount)
|
b481fb93f6da6c78b1605deb53819faff88564f4 | timvink/TransferBoost | /transferboost/dataset.py | 1,137 | 3.578125 | 4 | import pkgutil
import io
import pandas as pd
def load_data(return_X_y=False, as_frame=False):
"""Loads a simulated data set with two targets, y_1 and y_2.
y_1 and y_2 are generated
Args:
return_X_y: (bool) If True, returns ``(data, target)`` instead of a dict object.
as_frame: (bool) give the pandas dataframe instead of X, y matrices (default=False).
Returns: (pd.DataFrame, dict or tuple) features and target, with as follows:
- if as_frame is True: returns pd.DataFrame with y as a target
- return_X_y is True: returns a tuple: (X,y)
- is both are false (default setting): returns a dictionary where the key `data` contains the features,
and the key `target` is the target
"""
file = pkgutil.get_data("transferboost", "data/data.zip")
df = pd.read_csv(io.BytesIO(file), compression="zip")
if as_frame:
return df
X, y1, y2 = (
df[[col for col in df.columns if col.startswith("f_")]],
df["y_1"],
df["y_2"],
)
if return_X_y:
return X, y1, y2
return {"data": X, "target_1": y1, "target_2": y2}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.