blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
de99e1d9b18b48be0ea4c09e9b42418efd368682 | pdst-lccs/lccs-python | /Section 7 - Dictionaries/mean result v1.py | 544 | 3.984375 | 4 | # Event: LCCS Python Fundamental Skills Workshop
# Date: Dec 2018
# Author: Joe English, PDST
# eMail: computerscience@pdst.ie
# Purpose: A program to demonstrate the use of dictionaries to calculate the mean result
#A dictionary to store results for multiple students
results = {
'Joe': 67,
'Mary' : 76,
'Alex' : 72,
'Sarah' : 82,
'Fred': 64,
'Pat' : 91,
}
# Calculate the mean v1
total = 0
for v in results.values():
total = total + v
mean_result = total/len(results)
print("Mean result: %d " %mean_result)
|
62386c074957d2fab9a85ea17e967e3b27cdb759 | gxsoft/SkillShare---Python-3--Programming-in-Py-for-Beginners | /Jucu 01.py | 247 | 3.5 | 4 | print('-Jucu-'*50)
a = 10
print(a)
b = 'Hola 123456789-z'
print(a,b[0:2])
a = [1,2,3,4,5,6,7]
b = [8,9]
c = a + b
print(b+a,sum(c))
# a = 'Hola como te va'
if a>b:
print('a es mayor que b')
|
32bb910e9e8a0e047e4c01e823e6e1dbf0e11af6 | Naxthephantom/Python_Learning | /Binary Search Algorithm.py | 902 | 4.25 | 4 |
#Binary search algorithm
def binary_search(number, item):
left = 0
right = len(number) - 1
while left <= right:
middle = int((left + right) / 2) # middle tile
if item < number[middle]:
right = middle - 1
elif item > number [middle]:
left = middle + 1
else:
return middle
#I'm going to set down the basic parameters the algorithm is going to be using
size = 100000000 #The total numbers the code is searching through (the hay stack)
ordered_list = range(0, size)
search_item = 5426998 #the number we are looking for (the needle)
#now im setting the parameters in line with my biniary search formula under the name found_index
found_index = binary_search(ordered_list, search_item)
if found_index != -1:
print("found: ", found_index)
else:
print("Not found")
|
c25a4216a7e75366a77fb5f8090d81dd75f8446c | basvasilich/leet-code | /264.py | 563 | 3.546875 | 4 | # https://leetcode.com/problems/ugly-number-ii/
from heapq import heappop, heappush
class Solution:
def nthUglyNumber(self, n: int) -> int:
h = []
d = set()
heappush(h, 1)
count = 0
next_num = 1
while count < n:
next_num = heappop(h)
heappush(h, next_num * 2)
heappush(h, next_num * 3)
heappush(h, next_num * 5)
d.add(next_num)
while h[0] in d and len(h) > 0:
heappop(h)
count += 1
return next_num
|
3a70d48b3b3687f2a1cc64a54f21f1738bfb5b26 | meenapandey500/Python_program | /program/ex1.py | 539 | 3.890625 | 4 | #WAP to find the sum of 2 nos.
while(True):
try:
a=float(input("Enter Number a : "))
break #exit from loop
except ValueError:
print("Data Type Mismatch Error, Please Re-Enter numeric value of variable a : ")
print("Value of a : ",a)
while(True):
try:
b=int(input("Enter Number b : "))
break #exit from loop
except ValueError:
print("Data Type Mismatch Error, Please Re-Enter Integer value of variable b : ")
print("Value of b : ",b)
c=a+b
print("Sum=",c)
|
f51c2f594ac165224c40496383dbe8f6e0fbbc71 | CardinisCode/learning-python | /extra-course-practice-problems/delete_from_list.py | 3,231 | 4.25 | 4 | #Write a function called delete_from_list. delete_from_list
#should have two parameters: a list of strings and a list of
#integers.
#
#The list of integers represents the indices of the items to
#delete from the list of strings. Delete the items from the
#list of strings, and return the resulting list.
#
#For example:
#
# delete_from_list(["a", "b", "c", "d", "e", "f"], [0, 1, 4, 5])
#
#...would return the list ["c", "d"]. "a" is at index 0, "b" at 1,
#"e" at 4, and "f" at 5, so they would all be removed.
#
#Remember, though, as you delete items from the list, the
#indices of the remaining items will change. For example, once
#you delete "a" at index 0, the list will be ["b", "c", "d",
#"e", "f"], and now "c" will be at index 1 instead of "b". The
#list of indices to delete gives those values' _original_
#positions.
#
#You may assume that there are no duplicate items in the list
#of strings.
#
#There is more than one way to do this, so if you find yourself
#struggling with one way, try a different one!
import unittest
#Write your function here!
def delete_from_list(current_list, indices):
updated_list = []
if len(indices) == 0:
return current_list
for index in range(0, len(current_list)):
current_element = current_list[index]
if not index in indices:
updated_list.append(current_element)
return updated_list
#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print:
#['c', 'd']
#['a', 'b', 'e', 'f']
# print(delete_from_list(["a", "b", "c", "d", "e", "f"], [0, 1, 4, 5])) ----> ['c', 'd']
# print(delete_from_list(["a", "b", "c", "d", "e", "f"], [2, 3])) ---> ['a', 'b', 'e', 'f']
class TestDeletingItems(unittest.TestCase):
# current_list = ["a", "b", "c", "d", "e", "f"]
current_list = ["insight", "dispensate", "Layton", "airdrop", "dogtrot", "councilmen"]
def test_no_items_to_delete_returns_original_list(self):
print("----------------------------------------")
expected = ["insight", "dispensate", "Layton", "airdrop", "dogtrot", "councilmen"]
actual = delete_from_list(self.current_list, [])
self.assertEqual(expected, actual)
def test_deletes_1_item_from_original_list(self):
print("----------------------------------------")
expected = ["insight", "Layton", "airdrop", "dogtrot", "councilmen"]
actual = delete_from_list(self.current_list, [1])
self.assertEqual(expected, actual)
def test_deletes_2_items_from_original_list(self):
print("----------------------------------------")
expected = ["insight", "dispensate", "dogtrot", "councilmen"]
actual = delete_from_list(self.current_list, [2, 3])
self.assertEqual(expected, actual)
def test_deletes_4_items_from_original_list(self):
print("----------------------------------------")
expected = ["Layton", "airdrop"]
actual = delete_from_list(self.current_list, [0, 1, 4, 5])
self.assertEqual(expected, actual)
if __name__ == "__main__":
unittest.main() |
65b62cb43ae3445dade943da03cc789f0dd83a5f | sideroff/Softuni | /00_Other_Courses/01_Python/05_Exam_Preparation/15_Unique_Sales_By_City.py | 1,754 | 3.625 | 4 | import sys
import os
import iso8601
def file_check(file_path):
if (not os.path.isfile(file_path) or not os.access(file_path, os.R_OK)):
raise FileExistsError('Path is either a dir or cannot be accessed for reading')
def file_to_dict_of_cities(file_path):
dict_of_items = dict()
with open(file_path, encoding='utf-8') as f:
for line in f:
if not line.isspace():
line = line.strip().replace('"', "")
splitted = line.split(',')
item_id = splitted[0]
country = splitted[1]
city = splitted[2]
# date = iso8601.parse_date(splitted[3])
price = float(splitted[4].strip('"'))
if(item_id not in dict_of_items):
dict_of_items[city] = list()
if city not in dict_of_items[item_id]:
dict_of_items[item_id].append(city)
return dict_of_items
def main():
try:
file_path = input()
file_check(file_path)
items = file_to_dict_of_cities(file_path)
cities = {}
has_any = False
for id in items.keys():
if len(items[id]) == 1:
has_any = True
city = items[id][0]
if city not in cities:
cities[city] = []
cities[city].append(id)
else:
cities[city].append(id)
if(has_any):
for city in cities:
cities[city].sort()
print(city + "," + ",".join(cities[city]))
else:
print('NO UNIQUE SALES')
except(Exception):
print('INVALID INPUT')
if __name__ == '__main__':
sys.exit(main()) |
7fd3e9736f90af6cfe287b70cecfed99c8b15c36 | PaulWendt96/Markov_Visualize | /tempdir.py | 1,193 | 3.90625 | 4 | from contextlib import contextmanager
import os
import shutil
@contextmanager
def make_temporary_directory(path, dir_name, remove_if_already_exists=False):
''' create a temporary directory, do stuff with it, and remove it '''
assert os.path.isdir(path), "Error -- '{}' is not a directory".format(path)
dir_path = os.path.join(path, dir_name)
if not remove_if_already_exists:
assert dir_name not in os.listdir(path), "Error -- a directory named '{}' already exists. " \
"Cannot create a temporary directory over a " \
"permanent directory".format(dir_name)
else:
if os.path.isdir(dir_path):
shutil.rmtree(dir_path)
os.mkdir(dir_path)
yield dir_path
shutil.rmtree(dir_name)
def sample_save(text):
def call(path):
with open(path, 'w+') as f:
f.write(text)
return call
def save(objects, path, file_name, extension):
# objects is a method that can save an object given a path argument
for object in objects:
object(os.path.join(path, file_name, extension))
|
5ee303b8cd9171b7e5ea594af8628a54ad876377 | SmartCityLabs/Licence-Plate-Detection | /Licenceplate_identification/Logistic_regression/a_HOG_computation.py | 1,464 | 3.578125 | 4 | #-------------------------------------------------------------------------------
# Name: module2
# Purpose:
#
# Author: Sardhendu_Mishra
#
# Created: 04/03/2015
# Copyright: (c) Sardhendu_Mishra 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
'''
About: The below code is the HOG class that instantiates HOG. HOG is used to create the features that is sent into a logistic regression machine.
With the use of HOG feature we develop a model or find the optimal theta value which is again used for a new instance to predict the output.
If the image is a number plate or not number plate
'''
from skimage.feature import hog
class HOG:
def __init__(self, orientations = 9, pixelsPerCell = (8, 8),cellsPerBlock = (3, 3), visualise=False, normalize = False):
self.orienations = orientations
self.pixelsPerCell = pixelsPerCell
self.cellsPerBlock = cellsPerBlock
self.visualise = visualise
self.normalize = normalize
def describe(self, image):
hist , hog_image= hog(image,
orientations = self.orienations,
pixels_per_cell = self.pixelsPerCell,
cells_per_block = self.cellsPerBlock,
visualise= self.visualise,
normalise = self.normalize)
return hist, hog_image |
5a245698a46e3046f617c30fc4150707de41c22e | avik94/The-Whether | /run.py | 1,046 | 3.78125 | 4 | def x():
file = open("temp.txt",'w+')
file.write('city,country,month ave: highest high,month ave: lowest low\n\
Beijing,China,30.9,-8.4\nCairo,Egypt,34.7,1.2\nLondon,UK,23.5,2.1\
\nNairobi,Kenya,26.3,10.5\nNew York City,USA,28.9,-2.8\nSydney,Australia,26.5,8.7\nTokyo,Japan,30.8,0.9\n')
file.close()
file=open("temp.txt",'a+')
file.write("Rio de Janeiro,Brazil,30.0,18.0\n")
file.seek(0)
headings=file.readline()
headingsList=headings.split(',')
headingsList[0]="City"
listForAppend=headingsList[0:1]
listForAppend.append("of")
listForAppend.extend(headingsList[1:])
listForAppend[4]="is"
listForAppend.append("temp")
listForAppend.append("Celsius")
cityTemp=file.readline()
while cityTemp:
city_temp=cityTemp
cityTemp=file.readline()
listCityTemp=city_temp.split(',')
listForAppend[2]=listCityTemp[0]
listForAppend[5]=listCityTemp[2]
result=" ".join(listForAppend)
print(result)
if __name__ == '__main__':
x()
|
42fc258d24a33048771307150459357e29d03d14 | shellygr/Zookathon | /dbconnection.py | 1,426 | 3.515625 | 4 | import sqlite3
def initDB():
try:
conn = sqlite3.connect('photos.db')
c = conn.cursor()
c.execute('''CREATE TABLE photo
(photopath text,latitude number, longitude number, lables text, dateTaken text,endangeredStatus number)''')
conn.commit()
conn.close()
except Exception as e:
print e.message
def insertLine(path,lat,long,lables,dateTaken,endangeredStatus):
try:
conn = sqlite3.connect('photos.db')
c = conn.cursor()
args = [path,str(lat),str(long),lables,dateTaken,endangeredStatus]
c.execute("INSERT INTO photo VALUES (?,?,?,?,?,?)",args)
conn.commit()
conn.close()
except Exception as e:
print e.message
def selectByLable(lable):
try:
conn = sqlite3.connect('photos.db')
c = conn.cursor()
c.execute("SELECT * FROM photo WHERE lables like ?", ["%"+lable+"%"])
#rows = c.fetchall()
r = [dict((c.description[i][0], value) \
for i, value in enumerate(row)) for row in c.fetchall()]
#print c.fetchone()
conn.commit()
conn.close()
return r
except Exception as e:
print e.message
def clearTable():
try:
conn = sqlite3.connect('photos.db')
c = conn.cursor()
c.execute("DELETE FROM photo")
conn.commit()
conn.close()
except Exception as e:
print e.message
|
401ebe39c1a84852792cd56972ad59b9529b69d2 | renlei-great/git_window- | /python数据结构/和刘亮讨论/快速排序.py | 759 | 3.546875 | 4 | lista = [12, 4, 5, 6, 22, 3, 43, 654, 765, 7, 234]
# lista = [78, 45, 984, 42, 5, 6, 22, 3 , 2]
def quick_sort(alist, start=None, end=None):
"""快速排序"""
if start is None and end is None:
start = 0
end= len(alist) - 1
if end - start <= 0:
return
l_cur = start
r_cur = end
mid = alist[start]
while l_cur < r_cur:
while l_cur < r_cur and alist[r_cur] > mid:
r_cur -= 1
alist[l_cur] = alist[r_cur]
while l_cur < r_cur and alist[l_cur] < mid:
l_cur += 1
alist[r_cur] = alist[l_cur]
alist[l_cur] = mid
quick_sort(alist, start, l_cur-1)
quick_sort(alist, l_cur+1, end)
# start = 0
# end= len(lista) - 1
quick_sort(lista)
print(lista) |
5f3b32d1809318284e670fa004f9870061cec906 | dukeofducttape/code-combat | /cloudrip-volcano-fighters.py | 1,072 | 3.59375 | 4 | # Complete the paladin rectangle to protect the village.
# This function finds the left-most unit.
def findMostLeft(units):
if len(units) == 0:
return None
mostLeft = units[0]
for unit in units:
if unit.pos.x < mostLeft.pos.x:
mostLeft = unit
return mostLeft
# This function finds the bottom-most unit:
def findMostBottom(units):
if len(units) == 0:
return None
mostBottom = units[0]
for unit in units:
if unit.pos.y < mostBottom.pos.y:
mostBottom = unit
return mostBottom
paladins = hero.findByType("paladin")
# Find the top left paladin with findMostLeft function:
pallyTL = findMostLeft(paladins)
# Find the bottom right paladin with findMostBottom function:
pallyBR = findMostBottom(paladins)
# Use X coordinate from the top left paladin:
# and Y coordinate from the bottom right paladin:
x = pallyTL.pos.x
y = pallyBR.pos.y
# Move to the {X, Y} point from the previous step:
hero.moveXY(x, y)
# Continue to shield while the volcano is erupting:
while True:
hero.shield()
|
d725d2b54e95b43ee68ca08974caefdd72f2bc61 | bidahor13/Python_projects | /P3/Q1.py | 1,195 | 4.3125 | 4 | #AUTHOR: BABATUNDE IDAHOR
#COURSE: CS133
#TERM : FALL 2015
#DATE : 11/3/2015
#This program checks if two user input strings are anagrams of each other.
print('Project_3: Q1')
print('----------------------------------------------')
print('----------------------------------------------')
#Input values
word1 = str(input('Please enter first word: '))
word2 = str(input('Please enter secord word: '))
# Go through the list and check if word1 matches word2.
word1a = word1.lower() # converts the string to a lower case
word2b = word2.lower()
#convert to a list
word1_list = list(word1a)
word2_list = list(word2b)
#Sorts the existing list
word1_list.sort()
word2_list.sort()
#Loop removes the white spaces from the sorted list.
while ' ' in word1_list:
word1_list.remove(' ')
while ' ' in word2_list:
word2_list.remove(' ')
# checks for anagrams
if word1_list == word2_list:
print( '\n'+ "Yes it's an Anagram!")
print('\n' + '------------------------PROOF------------------')
print(word1_list)
print(word2_list)
else:
print( 'hmm!! - No, they are not Anagrams' )
print(word1_list)
print(word2_list)
print('------------------------All Done!----------------')
|
16d74f0baf29cc997770b5dbb18314793161f3bb | patovala/ecuador-django-jquery | /validator.py | 1,713 | 3.828125 | 4 | #-*- coding: utf8 -*-
#------------------------------------------------------------------------------#
#---- ----#
#---- Validator testing functions ----#
#---- ----#
#---- Para dos algoritmos de cálculo de cédula ecuatoriana ----#
#---- ----#
#---- Autor: Pato Valarezo (c) patovala@pupilabox.net.ec @patovala ----#
#------------------------------------------------------------------------------#
def cedula1(cedula):
"""La primera function del google+ discussion python"""
r = 0
verificador = 0
c = 1
for i in cedula[0:9]:
if c % 2 != 0:
r = int(i) * 2
if r > 9:
for x in str(r):
verificador += int(x)
else:
verificador += r
else:
verificador += int(i)
c += 1
if verificador % 10 == 0 and int(cedula[9]) == 0:
return (verificador, True)
elif (10 - (verificador % 10)) == int(cedula[9]):
return (verificador, True)
else:
return (verificador, False)
def cedula2(cedula):
"""mi implementación del algoritmo anterior """
cint = [int(d) for d in cedula]
tester = cint[-1]
cint = cint[:-1]
impar = map(lambda a: sum(map(int, list(str(a * 2)))), cint[0::2])
pares = cint[1::2]
verificador = sum(pares + impar)
if verificador % 10 == 0 and tester == 0:
return (verificador, True)
return (verificador, (10 - (verificador % 10)) == tester)
|
3b5bb7113c3a848ebdf2b90c1245789cf530a9ac | jakipatryk/aoc-2020 | /12/solution.py | 2,221 | 3.5625 | 4 | import fileinput
instructions = list(
map(lambda x: (x[0], int(x.rstrip()[1:])), fileinput.input()))
def manhattan_distance(x, y):
return abs(x) + abs(y)
def process_instructions_1(instructions):
facing = 0
x = 0
y = 0
move_forward = {
0: lambda v: (x + value, y),
1: lambda v: (x, y + value),
2: lambda v: (x - value, y),
3: lambda v: (x, y - value)
}
for d, value in instructions:
if d == 'L':
facing = (facing + (value // 90)) % 4
elif d == 'R':
facing = (facing - (value // 90)) % 4
elif d == 'F':
x, y = move_forward[facing](value)
else:
x, y = move_forward[['E', 'N', 'W', 'S'].index(d)](value)
return manhattan_distance(x, y)
def process_instructions_2(instructions):
x = 0
y = 0
waypoint_x = 10
waypoint_y = 1
move_forward = {
0: lambda v: (waypoint_x + value, waypoint_y),
1: lambda v: (waypoint_x, waypoint_y + value),
2: lambda v: (waypoint_x - value, waypoint_y),
3: lambda v: (waypoint_x, waypoint_y - value)
}
for d, value in instructions:
if d == 'L':
direction = (value // 90)
if direction == 1:
waypoint_x, waypoint_y = -waypoint_y, waypoint_x
elif direction == 2:
waypoint_x, waypoint_y = -waypoint_x, -waypoint_y
elif direction == 3:
waypoint_x, waypoint_y = waypoint_y, -waypoint_x
elif d == 'R':
direction = (value // 90)
if direction == 1:
waypoint_x, waypoint_y = waypoint_y, -waypoint_x
elif direction == 2:
waypoint_x, waypoint_y = -waypoint_x, -waypoint_y
elif direction == 3:
waypoint_x, waypoint_y = -waypoint_y, waypoint_x
elif d == 'F':
x = x + value * waypoint_x
y = y + value * waypoint_y
else:
waypoint_x, waypoint_y = move_forward[[
'E', 'N', 'W', 'S'].index(d)](value)
return manhattan_distance(x, y)
print(process_instructions_1(instructions))
print(process_instructions_2(instructions))
|
3ffbe91af56fcd941a0bfaa243d64eeb44e5f1d3 | YingXie24/Python | /Fundamental-Python/2-DNA-Processing/DnaProcessing.py | 3,133 | 4.28125 | 4 | def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequence
dna2.
>>> is_longer('ATCG', 'AT')
True
>>> is_longer('ATCG', 'ATCGGA')
False
"""
return len(dna1)>len(dna2)
def count_nucleotides(dna, nucleotide):
""" (str, str) -> int
Return the number of occurrences of nucleotide in the DNA sequence dna.
>>> count_nucleotides('ATCGGC', 'G')
2
>>> count_nucleotides('ATCTA', 'G')
0
"""
num_nucleotides = 0
for char in dna:
if char in nucleotide:
num_nucleotides = num_nucleotides + 1
return num_nucleotides
def contains_sequence(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna2 occurs in the DNA sequence
dna1.
>>> contains_sequence('ATCGGC', 'GG')
True
>>> contains_sequence('ATCGGC', 'GT')
False
"""
return dna2 in dna1
def is_valid_sequence(dna):
""" (str)-> bool
Return True if and only if the dna sequence is valid. That is, it contains no other characters
other than 'A', 'T', 'G', 'C'.
>>>is_valid_sequence('ATCGTCA')
True
>>>is_valid_sequence('ABTGT')
False
"""
## for char in dna:
## if char in "ATCG":
## a = 1
## else:
## return False
##
## return True
num_invalid_nucleotide = 0
for char in dna:
if char not in "ATCG":
num_invalid_nucleotide = num_invalid_nucleotide + 1
return num_invalid_nucleotide == 0
def insert_sequence(dna1,dna2,index):
"""(str,str,int)-> str
Return the dna sequence obtained by inserting dna2 into dna1 at the given index.
>>>insert_sequence('CCGG','AT',2)
'CCATGG'
>>>insert_sequence('CCGG','AT',0)
'ATCCGG'
>>>insert_sequence('CCGG','AT',len('CCGG'))
'CCGGAT'
"""
new_dna = dna1[:index] + dna2 + dna1[index:]
return new_dna
def get_complement(nucleotide):
""" (str)-> str
Return the nucleotide's complement.
>>>get_complement('A')
'T'
>>>get_complement('C')
'G'
"""
if nucleotide == 'A':
return 'T'
if nucleotide == 'T':
return 'A'
if nucleotide == 'C':
return 'G'
if nucleotide == 'G':
return 'C'
def get_complementary_sequence(dna):
""" (str) -> str
>>>get_complementary_sequence('AT')
'TA'
>>>get_complementary_sequence('TCAG')
'AGTC'
"""
complementary_sequence = ''
for char in dna:
if char in 'ATCG':
get_complement(char)
complementary_sequence = complementary_sequence + get_complement(char)
return complementary_sequence
|
797dea886c57ac0febaaade4e8f63162223a2496 | ZU3AIR/DCU | /Year1/prog2_python3/w10l2/maximum_102.py | 146 | 3.578125 | 4 | def maximum(x):
if len(x) == 1:
return x[0]
m = maximum(x[:-1])
if x[-1] > m:
return x[-1]
else:
return m
|
9c15acec8f598fcaeaa6f953399ff4e408ce12f7 | sandeepkumar8713/pythonapps | /03_linkedList/26_delete_greater_value_on_right.py | 2,006 | 4.0625 | 4 | # https://www.geeksforgeeks.org/delete-nodes-which-have-a-greater-value-on-right-side/
# Question : Given a singly linked list, remove all the nodes which have a greater value on right side.
#
# Question Type : Generic
# Used : removeNextGreater(self):
# temp = self.head, prev = None
# while temp.next:
# if temp.data < temp.next.data:
# if self.head == temp:
# self.head = temp.next
# del temp
# temp = self.head
# prev = None
# else:
# prev.next = temp.next
# del temp
# temp = prev.next
# else:
# prev = temp
# temp = temp.next
# Complexity : O(n)
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def printList(self):
temp = self.head
while temp:
print(temp.data, end=" ")
temp = temp.next
print("")
def removeNextGreater(self):
temp = self.head
prev = None
while temp.next:
if temp.data < temp.next.data:
if self.head == temp:
self.head = temp.next
del temp
temp = self.head
prev = None
else:
prev.next = temp.next
del temp
temp = prev.next
else:
prev = temp
temp = temp.next
if __name__ == "__main__":
inpArr = [12, 15, 10, 11, 5, 6, 2, 3]
lList = LinkedList()
for i in range(len(inpArr) - 1, -1, -1):
lList.push(inpArr[i])
lList.printList()
lList.removeNextGreater()
lList.printList()
|
0fe2afb514cc7e595e1dc3c4362c05e48ad99d50 | choiking/LeetCode | /tree/EricD/235. Lowest Common Ancestor of a Binary Search Tree - EricD.py | 294 | 3.53125 | 4 | # Binary Search Tree!
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
while (root.val-p.val)*(root.val-q.val)>0:
root = root.left if root.val>q.val else root.right
return root |
576499034a57a30a45fed2769bc801cc7a32aded | izlatkin/euler-project | /interview/sorting/13_h_citation.py | 856 | 3.578125 | 4 | import collections
import heapq
def h_citation(citations: list[int]):
citations.sort() # O(n*log(n))
n = len(citations)
for i, c in enumerate(citations): # O(n)
if c >= n - i:
return n - i
return 0
def h_citation_heap(citations: list[int]):
n = len(citations)
count_citations = collections.Counter(citations) # O(n)
hc = []
for c in count_citations.items(): # O(n)
heapq.heappush(hc, c)
sum = 0
while len(hc) > 0: # O(n*log(k)) where k is numebr of distinct elemnts
element, count = heapq.heappop(hc) # O(log(n))
sum += count
if n - sum <= element:
return element
return 0
def main():
print(h_citation([2, 3, 3, 5, 5, 6, 7, 7, 8, 12]))
print(h_citation_heap([2, 3, 3, 5, 5, 6, 7, 7, 8, 12]))
if __name__ == '__main__':
main() |
3f9fb68543fbcb81d5bb4ba4b951266690561e81 | thmbob/TIPE-MPSI | /denombrement.py | 2,164 | 3.53125 | 4 | ### Objectif : mettre au point une formule qui calcule la proba théorique qu'un graphe soit connexe on procède par dénombrement via une formule récursive
### Pour limiter le nombre d'appel on a recours à la programmation dynamique. Les nombres en jeu sont rapidement très gros
### On dénombre le nombre de graphe à n sommet et k arêtes (noté C(n, k)) qui sont connexes en utilisant la formule suivante
### C(n, k) = \sum_{i=1}^{n} \sum_{a=0}^{k} C(i, a) * \binom{n-1}{i-1} * \binom{\binom{n-i}{2}}{k-a}
import numpy as np
import matplotlib.pyplot as plt
def creerTableau(l, c) :
tab = []
for i in range(l) :
tab.append([])
for j in range(c) :
tab[i].append(0)
return tab
def pascal(n) :
tab = creerTableau(n+1, n+1)
for i in range(n+1) :
tab[i][0] = 1
for i in range(1, n+1) :
print(i)
for j in range(1, i+1) :
tab[i][j] = tab[i-1][j-1] + tab[i-1][j]
return tab
triangle = pascal(1300)
def binom(k, n) :
return triangle[n][k]
def denombr(n) :
tab = creerTableau(n+1, binom(2, n)+1)
tab[1][0]
for i in range(1, n+1) :
print(i)
for j in range(i-1, binom(2,n)+1) :
s = 0
for k in range(1, i) :
for a in range(j+1) :
s += tab[k][a] * binom(k-1, i-1) * binom(j-a, binom(2,i-k))
tab[i][j] = binom(j, binom(2, i)) - s
return tab
tab = denombr(30)
def C(n, k) :
return tab[n][k]
def dicho(f, a, b, eps) :
t = 0
while b-a > eps :
t = (a+b)/2
if f(t)*f(a) <= 0 :
b = t
else :
a = t
return (a+b)/2
def probaConnexeTheo(x, n) :
e = binom(2, n)
s=0
for a in range(0, e) :
s += float(C(n, a)) * x**a * (1-x)**(e-a)
return s
def calculProbaLien(p, n) :
return dicho(lambda x: p-probaConnexeTheo(x, n), 0, 1, 0.01)
x = np.linspace(-0.001, 1., 10000)
for i in range(2, 31) :
y = probaConnexeTheo(x, i)
plt.plot(x, y, label='Ordre ' + str(i))
print(i)
plt.legend()
plt.show()
|
d88456f5ef26533b2d29c2c5d7d118cf45b8e95d | kimtaehyeong/Algorithm | /solution/beakjoon_2750.py | 215 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 22:26:30 2020
@author: Taehyung
"""
N = int(input())
a = []
for i in range(N):
b = int(input())
a.append(b)
a.sort()
for i in a:
print(i) |
f8ab57d4b8e6f28cb9956278e8d200bba736ffd0 | jingyiZhang123/leetcode_practice | /searching_problem/four_sum_18.py | 2,126 | 3.6875 | 4 | """
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
"""
class Solution(object):
def fourSum(self, nums, target):
nums.sort()
self.results = []
self.findNsum(nums, target, 4, [])
return self.results
def findNsum(self, nums, target, N, result):
if len(nums) < N or N < 2: return
# solve 2-sum
if N == 2:
l,r = 0,len(nums)-1
while l < r:
if nums[l] + nums[r] == target:
self.results.append(result + [nums[l], nums[r]])
l += 1
r -= 1
while l < r and nums[l] == nums[l - 1]:
l += 1
while r > l and nums[r] == nums[r + 1]:
r -= 1
elif nums[l] + nums[r] < target:
l += 1
else:
r -= 1
else:
for i in range(0, len(nums)-N+1): # careful about range
if target < nums[i]*N or target > nums[-1]*N: # take advantages of sorted list
break
if i == 0 or i > 0 and nums[i-1] != nums[i]: # recursively reduce N
self.findNsum(nums[i+1:], target-nums[i], N-1, result+[nums[i]])
return
print(Solution().fourSum([-500,-481,-480,-469,-437,-423,-408,-403,-397,-381,-379,-377,-353,-347,-337,-327,-313,-307,-299,-278,-265,-258,-235,-227,-225,-193,-192,-177,-176,-173,-170,-164,-162,-157,-147,-118,-115,-83,-64,-46,-36,-35,-11,0,0,33,40,51,54,74,93,101,104,105,112,112,116,129,133,146,152,157,158,166,177,183,186,220,263,273,320,328,332,356,357,363,372,397,399,420,422,429,433,451,464,484,485,498,499], 2139))
|
a64feae59f170151834409fc9a84fc0ee84d9865 | ReethP/Kattis-Solutions | /anothercandies.py | 387 | 3.671875 | 4 | iterations = int(input())
candies = []
for i in range(0,iterations):
input()
children = int(input())
candies.clear()
for j in range(0,children):
userinp = int(input())
candies.append(userinp)
kids = len(candies)
totalcandies = 0
for candy in candies:
totalcandies = totalcandies + candy
possible = totalcandies%kids
if(possible == 0):
print("YES")
else:
print("NO") |
b690b0dc696a95aa8a6ffcb7f8a77cdb613cd8be | gkdmssidhd/Python | /Python_day03/Day03Ex02.py | 714 | 3.71875 | 4 |
# 함수를 사용하는 이유
# 함수를 선언 해 두면 여러지점에서 재활용(반복호출) 가능
# input(), print() 도 역시 함수
def my_func(size) :
print(">>> 함수 호출")
print(">>> 이것은 함수 입니다")
print("-"* size)
print(">>> 1 함수를 외부에서 호출 하였다.")
my_func(5)
print(">>> 2 함수를 외부에서 호출 하였다.")
my_func(30)
print(">>> 3 함수를 외부에서 호출 하였다.")
my_func(5)
print(">>> 4 함수를 외부에서 호출 하였다.")
my_func(10)
def fn(cnt) :
print(">" * cnt)
if cnt <= 0 :
return
# 재귀 호출 - 반복문 대신 사용 가능
fn(cnt - 1)
# 매개변수 이용한 호출
fn(10) |
1e041001d8847572413077b2ca8303b4bb7c10d5 | darian200205/FP-python | /lab7/Domain/Subject.py | 328 | 3.53125 | 4 | class Subject:
def __init__(self, subject_id, subject_name, teacher):
self.subject_id = subject_id.upper()
self.subject_name = subject_name.upper()
self.teacher = teacher.upper()
def show_subjects(self):
print('ID:' + str(self.subject_id) + ':' + self.subject_name + '-' + self.teacher)
|
9d718c1457da85bb8d871b2024a6902c6888132e | vnpavlukov/Study | /Coursera/1_Specializations/2_Programming_on_Python/1_Dive_into_Python/Week_3/2_Inheritance/Lect_1_1.py | 417 | 3.53125 | 4 | class Pet:
def __init__(self, name=None):
self.name = name
class Dog(Pet):
def __init__(self, name, breed=None):
super().__init__(name)
self.breed = breed
def say(self):
return '{0}: waw'.format(self.name)
Doberman_Sharik = Dog('Шарик', 'Доберман')
print(Doberman_Sharik.name)
print(Doberman_Sharik.breed)
print(Doberman_Sharik.say())
print(Dog.__mro__)
|
046d62a9e843ab3f475213273b01fa967ddcc2ba | Elena-Zhao/gf | /utils.py | 559 | 3.6875 | 4 | import datetime as dt
from re import sub
import numpy as np
def parse_currency(string):
"""Preprocess string and get currency number
>>> parse_currency('$2,000')
2000.0
"""
return float(sub(r'[^\d.]', '', string))
def parse_date(string):
"""Get datetime
>>> parse_date('08/22/2017')
datetime.datetime(2017, 8, 22, 0, 0)
"""
try:
date = dt.datetime.strptime(string, '%m/%d/%Y')
except:
date = 'NA'
return date
if __name__ == "__main__":
import doctest
doctest.testmod()
|
3518c1e2d91c271c0f8b98df5fa9a686eec251ef | OtchereDev/Python-workbook-solution-projects- | /python_workbook_3.py | 7,829 | 4.0625 | 4 | """
This is the third chapter of The Python Workbook
the solution to the exercise
'Loop Exercise'
"""
#Exercise 61
# print('Let calculate the average of your collection of values')
# print('Please enter "0" if you dont have any more input')
# input_=True
# value=0
# n=0
# while input_:
# user_=int(input('What is the value of the item:\n\t'))
# if user_==0:
# print('Thank you for your input, calculaing your average')
# input_=False
# else:
# n+=1
# value+=user_
# if value==0:
# print('Your total average is',value)
# else:
# average=value/n
# print('The total average is',average)
#Exercise 62
# prices=[4.95,9.95,14.95,19.95,24.95]
# print('Let calculate the discount')
# for price in prices:
# discount=price *0.6
# new_price=price - discount
# print('Original price: %.2f'%price)
# print('Discount: %.2f'%discount)
# print('New price: %.2f \n'%new_price)
#Exercise 63
# deg_cel= [x for x in range(0,101,10)]
# print('Degree Celsius\tDegree Fahrenit')
# for i in deg_cel:
# fah= (i*1.8)+32
# print(i,"\t\t",fah)
#Exercise 64
#to-do
#Exercise 65
# from math import sqrt
# print('let calculate the perimeter of the polygon')
# perimeter=0
# user_x=float(input('Enter the x part of the cordinate:\t'))
# user_y=float(input('Enter the y part of the cordinate:\t'))
# old_x= user_x
# old_y= user_y
# user_xx=float(input('Enter the x part of the coordinate: (blank to quit):\t'))
# try:
# while user_xx != "":
# x=user_xx
# y= float(input('Enter the y of the cordinate:\t'))
# distance=sqrt((old_x-x)**2+(old_y-y)**2)
# perimeter+=distance
# old_x=x
# old_y=y
# user_xx=float(input('Enter the x part of the coordinate: (blank to quit):\t'))
# except ValueError:
# distance=sqrt((user_x-x)**2+(user_y-y)**2)
# perimeter+=distance
# print('The perimeter of the polygon is',perimeter)
#Exercise 66
# result=0
# cont_=True
# while cont_:
# input_=input('Enter your letter grade in caps (eg. A):\n\t')
# if input_=='A+' or input_=='A':
# result+=4.0
# elif input_=='A-':
# result+=3.7
# elif input_=='B+':
# result+=3.3
# elif input_=='B':
# result+=3.0
# elif input_=='B-':
# result+=2.7
# elif input_=='C+':
# result+=2.3
# elif input_=='C':
# result+=2.0
# elif input_=='C-':
# result+=1.7
# elif input_=='D+':
# result+=1.3
# elif input_=='D':
# result+=1.0
# elif input_=='F' or input=='':
# result+=0
# else:
# print('Your letter grade is incorrect.')
# break
# input_c=input('Do you have any othe grade to enter (enter y for Yes or n for n):\n\t')
# if input_c=='':
# break
# else:
# continue
# print('your total grade point is',result)
#Exercise 67
# print('To help determine your total admission cost enter the age of each individual in your group')
# cost=0
# cont_=True
# age=int(input('What is the age of the first person:\n\t'))
# while cont_:
# if age <= 2:
# cost+=0
# elif age >=3 and age <=12:
# cost+=14
# elif age>=65:
# cost+=18
# else:
# cost+=23
# try:
# age=int(input('What is the age of the next person:\n\t'))
# except ValueError:
# break
# print('Your total cost of admission is', cost)
#Exercise 68
# bits=input('Please enter the bit:\n\t')
# while bits != '':
# if bits.count('0') + bits.count('1') != 8 or len(bits)!=8:
# print('That not correct, provide an 8 bits')
# else:
# ones=bits.count('1')
# if ones%2==0:
# print('The parity is 0')
# else:
# print('The parity is 1')
# bits=input('Please enter the bit:\n\t')
#Exercise 69
# print('Let do some approximation of pi')
# iteration = 1000000
# multiplier = 1.0
# start_deno=2.0
# pi = 3.0
# for i in range(1,iteration+1):
# pi+=((4.0/(start_deno*(start_deno+1)*(start_deno+2))*multiplier))
# start_deno+=2
# multiplier*=-1
# print(pi)
#Exercise 70
# message=input('Enter the message:\n\t')
# shift=int(input('Enter the shift value:\n\t'))
# deciphed_message=''
# for i in message:
# if i>='a' and i <='z':
# position=ord(i)-ord('a')
# position=(position+shift)%26
# new_letter= chr(position+ord('a'))
# deciphed_message+=new_letter
# elif i>='A' and i<='Z':
# position=ord(i)-ord('A')
# position=(position+shift)%26
# new_letter= chr(position+ord('A'))
# deciphed_message+=new_letter
# else:
# deciphed_message+=i
# print('The real message is',deciphed_message)
#Exercise 71
# user_=int(input('Enter the value of x:\n\t'))
# guess=1
# not_good= True
# while not_good:
# f_x=guess**2-user_
# fi_x=2*user_
# squrt= (guess-(f_x/fi_x))
# # print(squrt)
# guess=squrt
# # print(guess)
# if abs(((guess*guess)-user_))<=10e-12:
# break
# print(squrt)
#Exercise 72
# user_=input('Enter your message:\n\t')
# ispalidrome=True
# for i in range(0,len(user_)//2):
# if user_[i] != user_[len(user_)-i-1]:
# ispalidrome= False
# if ispalidrome==True:
# print(user_,'that is a palidrome')
# else:
# print(user_,'is not a palidrome')
# Exercise 73
# user_=input('Enter your message:\n\t')
# punt='.,'
# new_user_=''
# for i in user_:
# if i not in punt:
# new_user_+=i
# new_user_=new_user_.replace(" ",'')
# ispalidrome=True
# for i in range(0,len(new_user_)//2):
# if new_user_[i] != new_user_[len(new_user_)-i-1]:
# ispalidrome= False
# if ispalidrome==True:
# print(user_,'that is a palidrome')
# else:
# print(user_,'is not a palidrome')
#Exercise 74
# print(" ",end='')
# for i in range(1,11):
# print("%4d"%i,end='')
# print()
# for i in range(1,11):
# print('%4d'%i, end='')
# for j in range(1,11):
# result=i*j
# print('%4d' %result, end="")
# print()
#Exercise 75
# user_1=int(input("Please enter m:\n\t"))
# user_2=int(input("Please enter n:\n\t"))
# d=min(user_1,user_2)
# while user_1%d !=0 or user_2%d !=0:
# d=d-1
# print(d)
#Exercise 76
# user_=int(input('Enter an integer greater than or equal to two:\n\t'))
# factor=2
# while factor<=user_:
# if user_%factor==0:
# user_=user_//factor
# print(factor)
# else:
# factor+=1
#Exercise 77
# user_=int(input('Enter the number in base 2:\n\t'))
# count=-1
# for i in str(user_):
# count+=1
# base_ten=0
# for j in str(user_):
# result=int(j)*(2**count)
# count-=1
# base_ten+=result
# if count<0:
# break
# print('the base 10 of the ',user_,' is ',base_ten)
#Exercise 78
# user_=int(input('Enter the number in base 10:\n\t'))
# result=""
# q=user_
# while True:
# r=q%2
# result=str(r)+result
# q=q//2
# if q==0:
# break
# print(result)
#Exercise 79
from random import randint
# maxi=randint(1,100)
# count=0
# print('We start with',maxi)
# for i in range(1,100):
# new=randint(1,100)
# if new>maxi:
# maxi=new
# count+=1
# print(new,"<== updated")
# else:
# print(new)
# print('The maximum number is',maxi)
# print('The number of update is',count)
#Exercise 80
# flips=''
# prob=''
# count=0
# run = True
# simu=10
# while run:
# flip=randint(1,2)
# if flip==1:
# prob+='H '
# else:
# prob+='T '
# flips+=str(flip)
# count+=1
# if flips[-3:]==str(111):
# run=False
# elif flips[-3:]==str(222):
# run=False
# else:
# continue
# print(prob,'(',count,"flips)")
|
0f1324da10e312bb9dcad0ccf1e726692fe1f20b | joeguerrero735/AlgoritmosSistemas | /ene-jun-2020/joe tareas y parciales/segundo parcial/segundo examen parcial.py | 1,931 | 3.875 | 4 | def quick_sort(arr,primero,ultimo):
pivote = arr[(primero+ultimo)//2]
min =primero
max =ultimo
while min <= max:
nom = arr[min]
while nom[0] < pivote[0]:
min +=1
nom = arr[min]
pass
nom2 = arr[max]
while nom2[0] > pivote[0]:
max -=1
nom2 = arr[max]
pass
if min <= max :
temp = arr[min]
arr[min] =arr[max]
arr[max] =temp
min +=1
max -=1
pass
pass
if primero < max:
quick_sort(arr,primero,max)
pass
if min < ultimo:
quick_sort(arr,min,ultimo)
pass
return arr
pass
#_____________________________________Busqueda binaria________________________________________
def Busqueda_binaria(arr,x):
primero = 0
ultimo = len(arr)-1
while primero <= ultimo:
centro =(primero + ultimo)//2
valor = arr[centro]
if x == valor:
return centro
pass
elif x != valor:
if x[0] < valor[0]:
ultimo = centro - 1
pass
else:
primero = centro + 1
pass
pass
return -1
pass
#________________________________main___________________________________________
import random
if __name__ == '__main__':
print("numero de canciones y peticiones a buscar:")
num = input().split()
medi = int(num[0])
peti = int(num[1])
arr=[]
cancion = []
"""for i in range(medi):
print(i+1,"° primer cancion")
lista = input()
arr.append(lista)
print("")
pass"""
print("nombre de canciones: ")
cancion = input().split()
if medi == len(cancion):
print("")
print("Buscar cancion: ")
buscar = []
for x in range(peti):
bus = input()
buscar.append(bus)
arr = quick_sort(cancion,0,len(cancion)-1)
print(" ")
for i in range(len(arr)):
print(arr[i], end=" ")
print("")
if peti == len(buscar):
for i in range(len(buscar)):
resul = Busqueda_binaria(arr,buscar[i])
print(resul,"\n")
elif peti != len(buscar):
primero("fuera de rango de peticiones")
elif medi != len(cancion):
print("fuera de rango") |
dbf5d871c992a586c4f09838f9c9b7dd1e034e5a | iSaluki/python | /testing/string_repeater.py | 194 | 3.9375 | 4 | string = input("String:")
stringSuffix = " "
string = string + stringSuffix
times = input("Amount:")
while not times.isdigit():
times= input("Amount")
times = int(times)
print (string * times)
|
cd4c8bdb642c0124fc9eb85b40812fece852fbe5 | MorisGoldshtein/2020DivHacks | /Map.py | 3,133 | 3.859375 | 4 | # Description: This program creates a map of the trains within the NYC Transit System based on data from
# NYC Open Data. Each station will have a heatmap, marker, station name, and track letter(s).
# The map is accessible through Jupyter with Map.ipynb
#Required Libraries: gmaps (includes Jupyter and other dependencies), pandas, requests
# Author: Moris Goldshtein
# Contributors: Neil Kuldip, Luna Shin
import requests
import gmaps
import pandas as pd
#Personal api key
API_KEY = "AIzaSyBLbuemf2HbOtD8JjWfS7E2q3uTTDGhIKw"
#Gain access to google's javascript api
gmaps.configure(api_key="AIzaSyBLbuemf2HbOtD8JjWfS7E2q3uTTDGhIKw")
new_york_coordinates = (40.69, -73.8073)
#Use pandas to access a csv containing info on train stations in Queens
df = pd.read_csv('Subway_Stations.csv')
stations = df['the_geom']
list_of_coordinates = stations.values
#list to contain coordinates(in tuple form) of each train station
places = []
#The coordinates for each train station are in string form -> turn them into floats for the gmaps to use
for x in range(0, len(stations.values)):
#Remove the "POINT " in every value, note each value is a string
stations.values[x] = stations.values[x][7:-1]
#Separate the two values(which are strings right now) by finding where the (space) is
index = stations.values[x].find(" ")
float1 = stations.values[x][index+1:]
float2 = stations.values[x][:index]
#Convert each value to a float and then recombine them into a tuple
float1 = float(float1)
float2 = float(float2)
stations.values[x] = (float1, float2)
#Add each value to places
places.append(stations.values[x])
#Access same csv, but the names of each train station instead of coordinates
stations = df['NAME']
list_of_names = stations.values
#list to contain names of each train station
names = []
#Add every name to the list
for x in range(0, len(stations.values)):
names.append(stations.values[x])
#Access same csv, but the lines of each train station instead of coordinates
stations = df['LINE']
list_of_lines = stations.values
#list to contain names of each train station
lines = []
#Add every name to the list
for x in range(0, len(stations.values)):
lines.append(stations.values[x])
#Create the map
fig = gmaps.figure(center=new_york_coordinates, zoom_level=11.2, layout={'height': '700px', 'width': '700px'})
#Show all train lines
transit_layer = gmaps.transit_layer()
fig.add_layer(transit_layer)
#Make a heatmap area around every coordinate based on the modified info from the csv (The circle is ~1/4 mile based on set zoom level without zooming)
heat_map_layer = gmaps.heatmap_layer(locations=places, point_radius=11)
fig.add_layer(heat_map_layer)
#Make markers for every station so they can be identified by name
name_marker_layer = gmaps.marker_layer(
places, info_box_content=names, hover_text=lines)
fig.add_layer(name_marker_layer)
#Activate the map
fig
|
337a3404f62a25506ee85ef439720c58cad435cf | himu999/Python_Basic | /F.list/#H#list_comprehension.py | 396 | 4.09375 | 4 | a = ["apple", "kiwi", "cherry", "banana", "mango"]
b = []
c = []
for x in a:
if "a" in x:
b.append(x)
else:
c.append(x)
print("Element of list a : ", a)
print("Element of list b : ", b)
print("Element of list c : ", c)
# With short hand
k = [x for x in a if "a" in x]
print("Element of list k : ", k)
l = [x for x in a if x != "apple"]
print("Element of list l : ", l)
|
da6052993b3c1119dee46966a57b3cde20a2d63a | horada1991/DerpSnake | /piton.py | 1,491 | 3.734375 | 4 | import curses
screen = curses.initscr()
dims = screen.getmaxyx()
curses.start_color()
# Moving Snake's parts' coordinates
def moving_coords(coord_list, y, x):
global dims
for element in range(len(coord_list)-1, 1, -1):
coord_list[element] = coord_list[element-2]
coord_list[0] = y
coord_list[1] = x
return(coord_list)
# If eat food, then grow in length
def eat(coord_list, food_coords, poison_food_coords, hp_food_coords):
if coord_list[:2] == food_coords:
if coord_list[-2] == coord_list[-4]:
coord_list.extend([coord_list[-2], coord_list[-1] * 2 - coord_list[-3]])
elif coord_list[-1] == coord_list[-3]:
coord_list.extend([coord_list[-2] * 2 - coord_list[-4],
coord_list[-1]])
return(coord_list)
if coord_list[:2] == poison_food_coords:
return(2)
if coord_list[:2] == hp_food_coords:
return(3)
else:
return(0)
# print snake on new coords
def print_snake(coord_list):
global screen
for i in range(0, len(coord_list)-1, 2):
screen.addch(coord_list[i], coord_list[i+1], "O", curses.color_pair(1))
screen.addch(coord_list[0], coord_list[1], "@", curses.color_pair(2))
# increase snake's speed base on the score
def speed_raise(score, speed):
if score % 5 == 0:
speed -= 0.005
return speed
|
74dd49a4d7167b79c9801ca42a0000faf14b118f | chefkasperson/Cracking_the_Interview | /chp1/python/multiples_3_and_5.py | 256 | 4.09375 | 4 | def solution(number):
total = 0
i = 0
while i < number:
if i % 3 == 0 or i % 5 == 0:
total += i
i += 1
return total
# def solution(number):
# return sum(x for x in range(number) if x % 3 == 0 or x % 5 == 0)
|
e8395bd96993d23694ef61c1475182610aa52e36 | Qing8/Assignments-for-Data-Structure | /1/Python template files/question5.py | 1,249 | 3.859375 | 4 | import math # need math.pi
class Shape:
# No need to modify this class.
def __init__(self, name):
self.name = name
def compute_area(self):
pass
def compute_perimeter(self):
pass
class Circle(Shape):
def __init__(self, name, radius):
# TO DO
# Call super first
super().__init__(name)
self.radius = radius
def compute_area(self):
# TO DO
# @return the area of this circle
return math.pi*self.radius**2
def compute_perimeter(self):
# TO DO
# @return the perimeter of this circle
return 2*math.pi*self.radius
class Rectangle(Shape):
def __init__(self, name, length, height):
# TO DO
# Call super first
super().__init__(name)
self.length = length
self.height = height
def compute_area(self):
# TO DO
# @return the area of this rectangle
return self.height*self.length
def compute_perimeter(self):
# TO DO
# @return the parimeter of this rectangle
return 2*(self.height+self.length)
c = Circle("Moon", 15)
#print(c.compute_perimeter())
r = Rectangle("Block", 20, 10)
#print(r.compute_area())
|
cf7dc2ee2073db26b2279f584171b905e1805e04 | yanoshercohen/virtual-mouse | /mouse_controller.py | 867 | 3.625 | 4 | import mouse
from pynput.keyboard import Key, Listener
#Pixels amount per any mouse step
step = 15
#configuring the mouse control keys
direction_keys = {
Key.right: (step, 0),
Key.left: (-step, 0),
Key.up: (0, -step),
Key.down: (0, step)
}
#configuring the mouse click keys
click_keys = {Key.f9: "left", Key.f10: "right"}
def main():
print("press ESC to exit.")
# Collect events until released
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
def on_press(key):
pos = direction_keys.get(key)
mouse_click = click_keys.get(key)
if pos:
mouse.move(*pos, absolute=False, duration=0)
elif mouse_click:
mouse.click(mouse_click)
def on_release(key):
if key == Key.esc:
# Stop listener
return False
if __name__ == "__main__":
main()
|
ee29c5df4e434674beae2edf8d32a800c3ac9344 | brooky56/SSD_Assignment_1 | /src_assignemnt_2/bc_printer.py | 1,733 | 3.640625 | 4 | """Opcodes printing
Takes .py files and yield opcodes (and their arguments) for ordinary python programs.
This file can also be imported as a module and contains the following
functions:
* expand_bytecode - function find and extends bytecode result
* bc_print - function print instructions names and human readable description of operation argument
* main - the main function of the script
"""
import marshal
import dis, sys
def expand_bytecode(bytecode):
"""
Function find and extends bytecode result
:param bytecode: bytecode
:return: list with instructions
"""
result = []
for instruction in bytecode:
if str(type(instruction.argval)) == "<class 'code'>":
result += expand_bytecode(dis.Bytecode(instruction.argval))
else:
result.append(instruction)
return result
def bc_print():
"""
Function print instructions names and human readable description of operation argument
:return: None
"""
for i in sys.argv[2:]:
source = None
if sys.argv[1] == "-py":
with open(i, 'r') as f:
source = f.read()
elif sys.argv[1] == "-pyc":
header_size = 12
with open(i, 'rb') as f:
f.seek(header_size)
source = marshal.load(f)
elif sys.argv[1] == "-s":
source = i
else:
print("Error")
return
bc = dis.Bytecode(source)
res = expand_bytecode(bc)
for instruction in res:
print(f'{instruction.opname}\t {instruction.argrepr}')
print()
print()
if __name__ == "__main__":
# main execution logic for Tasks 2&3
bc_print()
|
5fdc983681dcddc1d6bee594da5b455bdfd8186d | avinash516/python-problem-solving-skills-programmes | /2.Interest rates calculator.py | 218 | 3.84375 | 4 | basic = float(input('Amount :'))
rate = float(input('Rate :'))
months = float(input('No.of Months :'))
y =float( input("Enter No. of Years: "))
m=(basic*rate*months)/100
print("intrest rate for year wise",m*y)
|
68be34cee896c61ef2e1f6e2c57de42053834d0b | tlima1011/python3-curso-em-video | /ex067.py | 345 | 3.921875 | 4 | titulo = 'TABUADA VS 3.0'
print(f'{titulo:=^30}')
while True:
tab = int(input('Informe a tabuada: '))
if tab < 0:
break
print('-=' * 10)
print(f'TABUADA DE {tab}')
print('-=' * 10)
for i in range(1, 11):
print(f'{tab} x {i} = {tab * i}')
print('-=' * 10)
print('PROGRAMA ENCERRADO!!!')
|
235e66a39ed8285fe8f074d04b4e88986ed239e9 | andreagaietto/Learning-Projects | /Python/Small exercises/functions/star_args.py | 218 | 3.640625 | 4 | def sum_all_nums(*args):
print(sum(args))
#returns a tuple
sum_all_nums(1, 2, 3, 4)
sum_all_nums(1, 2)
# can also do something like (num1, *args)
# also doesn't have to be named args, can be something else |
8b9b43bb859b4a6adb5874e9f4db3c398a797bff | vasudevk/python | /lists.py | 2,366 | 4.25 | 4 | s = "Show how to index into sequences".split()
print(s)
print(s[4])
# indexing from the end
print(s[-5])
# slicing a list using index, negative indexing and including
gunga = "Though I’ve belted you and flayed you, " \
"By the livin’ Gawd that made you, " \
"You’re a better man than I am, Gunga Din!".split()
slices = gunga[0:10]
slice_din = gunga[1:-1]
slice_gunga = gunga[1:]
slice_gunga_din = gunga[:-1]
print(slices)
print(slice_din)
print(slice_gunga)
print(slice_gunga_din)
# Below snippet illustrates copying of lists
# New list full_slice[] has a distinct identity but equivalence with gunga[]
full_slice = gunga[:]
print(full_slice)
print(full_slice is gunga)
print(full_slice == gunga)
# copying lists
gunga_copy = gunga.copy()
print(gunga_copy)
gunga_me = list(gunga)
print(gunga_me)
# all these methods only make shallow copies.
# In the below example, only the object a is copied.
# If we change the value of b[0] or b[1][1],
# those changes are also made in a
a = [[10, 100], [9, 81]]
b = a[:]
print(a is b)
print(a == b)
print("Notice how only the reference to object a is copied here!", "\t", a[0] is b[0])
a[0] = [8, 9]
print(a[0])
a[1].append(5)
print("b[1] is", b[1], "a[1] is ", a[1])
# Repetition using *
c = [12, 43]
d = c * 4
print(d)
s = [[-1, 1]] * 5
print(s)
s[3].append(7)
print(s)
# Finding elements in a list
child = "The price of our loss shall be paid to our hands, not another’s hereafter. " \
"Neither the Alien nor Priest shall decide on it. That is our right. " \
"But who shall return us the children?".split()
print(child)
i = child.index("Alien")
print(i)
print(child[i])
# print(child.index("unicorn")) # ValueError is thrown if the element is not found.
count = child.count("shall")
print(count)
# Removing
road = "Somewhere ages and ages hence: " \
"Two roads diverged in a wood, and I- " \
"I took the one less traveled by, " \
"And that has made all the difference.".split()
print(road)
# del road[i] - remove by index
# road.remove("") - remove by value
print(road.remove('Somewhere'))
print(road)
# Insertion
sky = "There is another sky, " \
"Ever and fair, " \
"And there is another sunshine, " \
"Though it be darkness there;".split()
print(sky)
sky.insert(5, "serene") # insert(index, item)
print(sky)
print(' '.join(sky))
|
6d7221c46962a6ca326aceb2a33ecab084d9f5fa | sdnProjectAqsa/SDN-Simulation-with-OpenFlow | /FatTree_6.py | 2,694 | 3.875 | 4 | """Custom topology example
Two directly connected switches plus a host for each switch:
host --- switch --- switch --- host
Adding the 'topos' dict with a key/value
pair to generate our newly defined topology enables one to pass
in '--topo=mytopo' from the command line"""
from mininet.topo import Topo
class MyTopo( Topo ):
def build( self ):
"Create custom topo."
# Add hosts and switches
H1 = self.addHost( 'h1')
H2 = self.addHost( 'h2' )
H3 = self.addHost( 'h3' )
H4 = self.addHost( 'h4' )
H5 = self.addHost( 'h5' )
H6 = self.addHost( 'h6' )
H7 = self.addHost( 'h7' )
H8 = self.addHost( 'h8' )
H9 = self.addHost( 'h9' )
H10 = self.addHost( 'h10' )
H11 = self.addHost( 'h11' )
H12 = self.addHost( 'h12' )
H13 = self.addHost( 'h13' )
H14 = self.addHost( 'h14' )
H15 = self.addHost( 'h15' )
H16 = self.addHost( 'h16' )
H17 = self.addHost( 'h17' )
H18 = self.addHost( 'h18' )
s1 = self.addSwitch( 's1' )
s2 = self.addSwitch( 's2' )
s3 = self.addSwitch( 's3' )
s4 = self.addSwitch( 's4' )
s5 = self.addSwitch( 's5' )
s6 = self.addSwitch( 's6' )
s7 = self.addSwitch( 's7' )
s8 = self.addSwitch( 's8' )
s9 = self.addSwitch( 's9' )
#Add Links
self.addLink( H1, s1 )
self.addLink( H2, s1 )
self.addLink( H3, s1 )
self.addLink( H4, s2 )
self.addLink( H5, s2 )
self.addLink( H6, s2 )
self.addLink( H7, s3 )
self.addLink( H8, s3 )
self.addLink( H9, s3 )
self.addLink( H10, s4 )
self.addLink( H11, s4 )
self.addLink( H12, s4 )
self.addLink( H13, s5 )
self.addLink( H14, s5 )
self.addLink( H15, s5 )
self.addLink( H16, s6 )
self.addLink( H17, s6 )
self.addLink( H18, s6 )
self.addLink( s1, s7 )
self.addLink( s1, s8 )
self.addLink( s1, s9 )
self.addLink( s2, s7 )
self.addLink( s2, s8 )
self.addLink( s2, s9 )
self.addLink( s3, s7 )
self.addLink( s3, s8 )
self.addLink( s3, s9 )
self.addLink( s4, s7 )
self.addLink( s4, s8 )
self.addLink( s4, s9 )
self.addLink( s5, s7 )
self.addLink( s5, s8 )
self.addLink( s5, s9 )
self.addLink( s6, s7 )
self.addLink( s6, s8 )
self.addLink( s6, s9 )
topos = { 'mytopo': ( lambda: MyTopo() ) }
|
47dad38657dad04ccdf1d51ed3757139a36eb1cb | ysk1026/data_science | /chp4/vector.py | 3,216 | 3.921875 | 4 | from typing import List
import math
'''
벡터를 리스트로 표현해서 개념 정리, 원리를 설명하는데 굉장히 편리하지만 성능면에서는 최악이다.
실제 사용할 땐 NumPy를 사용함
'''
Vector = List[float]
height_weight_age = [70, # 인치,
170, # 파운드,
40 ] # 나이
grades = [95, # 시험 1 점수
80, # 시험 2 점수
75, # 시험 3 점수
62] # 시험 4 점수
def add(v: Vector, w: Vector) -> Vector:
"""각 성분끼리 더한다."""
assert len(v) == len(w), "vectors must be the same length"
return [v_i + w_i for v_i, w_i in zip(v, w)]
assert add([1, 2, 3], [4, 5, 6]) == [5, 7, 9]
def subtract(v: Vector, w: Vector) -> Vector:
"""각 성분끼리 뺀다."""
assert len(v) == len(w), "vectors must be the same length"
return [v_i - w_i for v_i, w_i in zip(v, w)]
assert subtract([5, 7, 9], [4, 5, 6]) == [1, 2, 3]
def vector_sum(vectors: List[Vector]) -> Vector:
"""모든 벡터의 각 성분들끼리 더한다."""
# vectors가 비어 있는지 확인
assert vectors, "no vectors provided!"
# 모든 벡터의 길이가 동일한지 확인
num_elements = len(vectors[0])
assert all(len(v) == num_elements for v in vectors), "diffrent size!"
# i번째 결괏값은 모든 벡터의 i번째 성분을 더한 값
return [sum(vector[i] for vector in vectors)
for i in range(num_elements)]
assert vector_sum([[1, 2], [3, 4], [5, 6], [7, 8]]) == [16, 20]
def scalar_multiply(c: float, v: Vector) -> Vector:
"""모든 성분을 c로 곱하기"""
return [c * v_i for v_i in v]
assert scalar_multiply(2, [1, 2, 3]) == [2, 4, 6]
def vector_mean(vectors: List[Vector]) -> Vector:
"""각 성분별 평균을 계산"""
n = len(vectors)
return scalar_multiply(1/n, vector_sum(vectors))
# assert vector_mean([1, 2], [3, 4], [5, 6]) == [3, 4]
# 벡터의 내적(dot product)
def dot(v: Vector, w: Vector) -> float:
"""v_1 * w_1 + ... + v_n * w_n """
assert len(v) == len(w), "vectors must be the same length"
return sum(v_i * w_i for v_i, w_i in zip(v, w))
assert dot ([1, 2, 3], [4, 5, 6]) == 32 # 1 * 4 + 2 * 5 + 3 * 6
# 내적의 개념을 사용해서 각 성분의 제곱 값의 합을 쉽게 구한다.
def sum_of_squares(v: Vector) -> float:
"""v_1 * v_1 + ... + v_n * v_n"""
return dot(v, v)
assert sum_of_squares([1, 2, 3]) == 14 # 1 * 1 + 2 * 2 + 3 * 3
# 제곱 값의 합을 이용해 백터의 크기 계산
def magnitude(v: Vector) -> float:
"""벡터 v의 크기를 반환"""
return math.sqrt(sum_of_squares(v)) # math.sqrt는 제곱근을 계산해 주는 함수
assert magnitude([3, 4]) == 5
def squared_distinct(v: Vector, w: Vector) -> float:
"""(v_1 - w_1) ** 2 + ... + (v_n - w_n) ** 2"""
return sum_of_squares(subtract(v, w))
def distance(v: Vector, w: Vector) -> float:
"""벡터 v와 w 간의 거리를 계산"""
return math.sqrt(squared_distinct(v, w))
# 다음과 같이 수정하면 더욱 깔끔해진다.
def distance(v: Vector, w: Vector) -> float:
return magnitude(subtract(v, w))
|
25b582d7ec8e282e890f000daceb7b716ef7d261 | smartinsert/CodingProblem | /equal_string_backspace.py | 1,091 | 3.765625 | 4 |
def backspace_compare(str1, str2):
if str1 == str2:
return True
left_idx, right_idx = len(str1) - 1, len(str2) - 1
while left_idx >= 0 or right_idx >= 0:
valid_left_idx = next_valid_character_index(str1, left_idx)
valid_right_idx = next_valid_character_index(str2, right_idx)
if str1[valid_left_idx] != str2[valid_right_idx]:
return False
if valid_left_idx < 0 and valid_right_idx < 0:
return True
if valid_left_idx < 0 or valid_right_idx < 0:
return False
left_idx = valid_left_idx - 1
right_idx = valid_right_idx - 1
return True
def next_valid_character_index(string: str, index: int) -> int:
backspace_count = 0
while index >= 0:
if string[index] == '#':
backspace_count += 1
elif backspace_count > 0:
backspace_count -= 1
else:
break
index -= 1
return index
# print(backspace_compare("xy#z", "xzz#"))
# print(backspace_compare("xy#z", "xyz#"))
print(backspace_compare("xp#", "xyz##"))
|
18db09159f1d5f56a84e1be119d2b0819de145ec | thenu97/mathworld | /Calculator.py | 478 | 4.125 | 4 | #!/usr/bin/env python3.8
print("Hello World")
x = float(input("What is your x: " ))
y = float(input("What is your y: "))
Ops = input("addition, subtraction, multiplication, division?: ")
def cal(x, y):
if Ops == "addition":
return x + y
if Ops == "subtraction":
return x - y
if Ops == "multiplication":
return x * y
if Ops == "division":
return x / y
else:
return "Invalid operation selected!"
print(x, y, cal(x,y)) |
4a5d2461d230e6d46b000b0c5b223d7ad1801a7e | ManuBedoya/AirBnB_clone_v2 | /web_flask/6-number_odd_or_even.py | 1,541 | 3.5 | 4 | #!/usr/bin/python3
"""Modulo to find the flask
"""
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/', strict_slashes=False)
def index():
"""The root of the page or index/default
"""
return 'Hello HBNB!'
@app.route('/c/<text>', strict_slashes=False)
def c_is(text):
"""Page to show the message C + a word in the url
"""
separate = text.split("_")
return 'C {}'.format(' '.join(separate))
@app.route('/hbnb', strict_slashes=False)
def hbnb():
"""Page to show the message HBNB
"""
return 'HBNB'
@app.route('/python/<text>', strict_slashes=False)
def python_is(text="is cool"):
"""Page to show the message Python + a word or phrase in the url
"""
separate = text.split("_")
return 'Python {}'.format(' '.join(separate))
@app.route('/number/<int:n>', strict_slashes=False)
def is_number(n):
"""Page to show the message number + is a number
"""
return '{:d} is a number'.format(n)
@app.route('/number_template/<int:n>', strict_slashes=False)
def number_template(n):
"""Change the h1 tag with the number
"""
return render_template('5-number.html', number=n)
@app.route('/number_odd_or_even/<int:n>', strict_slashes=False)
def number_odd_or_even(n):
"""Change the h1 tag with the respecting information id is odd or even
"""
odd_even = 'even' if n % 2 == 0 else 'odd'
return render_template('6-number_odd_or_even.html',
number=n, odd_even=odd_even)
app.run(debug=True, port=5000)
|
611cd300cf57e64d24ad1c3dae7502ef3db48bab | dhananjayharel/mark_trego_python_beginners | /numpy_basic/basic.py | 369 | 3.546875 | 4 | import numpy as np
x=np.random.random()
print("Random number: ", x)
x_square_root=np.sqrt(x)
print("Number square root: ", x_square_root)
print("x^sqrt(x): ", np.power(x, x_square_root))
matrix = np.random.random(3)
print("Random matrix: ", matrix)
matrix = np.append(matrix, np.random.random(2))
print("New matrix: ", matrix)
print("Sine of matrix: ", np.sin(matrix)) |
92e443de47064165bfe64761c480290e619e2589 | eno2050/python-study-note | /base/task10.py | 269 | 3.78125 | 4 | #-*- coding:utf-8 -*-
# 面向对象编程
class Person(object):
def __init__(self,name,skin = "yellow"):
self.name = name
self.__dict__.skin = skin
xiaoming = Person('xiaoming')
hahha = Person('hahha')
print xiaoming.name
print xiaoming.skin
print hahha.name |
28f731a0edd85ced317ea990fbce0302831f81a4 | m4nasi/UCL-Coding-Summer-School | /snakes.py | 2,359 | 3.515625 | 4 | ###### 1. Initialising the game ################################################
#### 1.1 Import libraries
import sys
sys.path.insert(1,'/home/pi/Go4Code/g4cSense/skeleton')
from sense_hat import SenseHat
from snake_lib import Snake
import random
from senselib import *
#### 1.2 Initialisation
sense = SenseHat() # This will be used to control the the SenseHat.
initialise(sense) # Initialises the senselib library, that provides us with some useful functions
sense.clear() # Clears all pixels on the screen.
#### 1.3 Set up the game variables
applePosition = [1, 1] # Set the starting position of the apple
snake = Snake([3,3]) # Creates the snake, and sets its starting position
snakeColour = [0, 255, 0] # Colour of the snake
appleColour = [255, 255, 255] # Colour of the apple
###### 2. Main game code #######################################################
while True:
sense.clear()
snake_body = snake.get_body() # Gets the body of the snake, containing all the positions.
for bodypart in snake_body:
sense.set_pixel(bodypart[0], bodypart[1], snakeColour[0], snakeColour[1], snakeColour[2])
# Draw the apple
sense.set_pixel(applePosition[0], applePosition[1], appleColour[0], appleColour[1], appleColour[2])
#### 2.1 Let the user control the snake
for event in sense.stick.get_events():
if event.action == 'pressed':
if event.direction == 'up':
snake.turn_up()
elif event.direction == "down":
snake.turn_down()
# Fill in with your own code
elif event.direction == "left":
snake.turn_left()
# Fill in with your own code
elif event.direction == "right":
snake.turn_right()
# Fill in with your own code
#### 2.2 Draw the snake and the apple
#### 2.3 Move the snake
snake.move_forward()
#### 2.4 Check if apple ate an apple
if snake.get_position() == applePosition:
snake.grow()
applePosition = snake.get_new_apple_position()
#### 2.5 Check if snake has collided with itself
if snake.has_collided_with_self():
count = 0
for bodypart in snake_body:
count += 1
sense.show_message("You lose, your score is " + str(count), 0.05)
snake.reset()
#### 2.6 Add some delay
wait(0.2)
|
fcfc6601c4c68b2397f8bda1982b1f7713245083 | tasotasoso/statistics | /NLP/myparse.py | 800 | 3.75 | 4 | #Copyright (c) <2017> Suzuki N. All rights reserved.
#inspired by "http://www.phontron.com/teaching.php?lang=ja"
# -*- coding: utf-8 -*-
import MeCab
from collections import Counter
def Wordcount(text):
def myparse(text):
mc = MeCab.Tagger("-Owakati")
ptext = mc.parse(text)
words = ptext.split()
return words
def count(words):
counter = Counter(words)
for word, cnt in counter.most_common():
print(word, cnt)
words = myparse(text)
count(words)
def readfile(filename):
f = open("text.txt",'r')
text = ""
for line in f:
text += line.strip()
return text
def main():
import sys
f1 = open(sys.argv[1], 'r')
text = readfile(f1)
Wordcount(text)
if __name__ == "__main__":
main()
|
cd2eb70ddd06efb445b9dffd8124dcc82fb5bfc8 | vharvey80/PythonExercises | /LightYearCalculator.py | 1,032 | 3.703125 | 4 | # Calcul la distance en année lumière
def CalculSeconde(annees):
n_j = (float(str(annees.replace(",", "."))) * 365.26)
n_h = n_j * 24
n_m = n_h * 60
n_s = n_m * 60
return n_s
n_secondes = CalculSeconde(input("Entrez un nombre d'année(s) lumière : "))
print(format(n_secondes, ".2f") + " secondes")
#b)
def CalculDistance(secondes):
n_km = (secondes * 300000)
return n_km
n_kilometres = CalculDistance(n_secondes)
print(format(n_kilometres, ".2f") + "km")
#c)
def CalculDistanceEntreEtoiles(p_distance, d_distance):
nseconde_1d = CalculSeconde(str(p_distance.replace(",", ".")))
nkm_1d = CalculDistance(nseconde_1d)
d_finale = nkm_1d
nseconde_2d = CalculSeconde(str(d_distance.replace(",", ".")))
nkm_2d = CalculDistance(nseconde_2d)
d_finale += nkm_2d
return d_finale
n_km_etoile = CalculDistanceEntreEtoiles(input("Entrez la distance de la première étoile : "), input("Entrez la distance de la deuxième étoile : "))
print(format(n_km_etoile, ".2f") + " km")
|
6d8522c061838774fcd10c28be7a1ce81c8978e1 | Ethics123/python_a | /level2-1.py | 208 | 3.828125 | 4 | # バグを修正し全ての名前を一度ずつ順番に出力できるようにしてください
name_list = ["太郎", "次郎", "三郎", "四郎", "五郎"]
for i in range(1, 5):
print(name_list)
|
94709ec80dd95d1ee3e6ca9aed83aac7f5fe0b0a | zongzake/Homework- | /work 27-09-2562.py | 8,272 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
#ข้อที่ 1 ให้นักศึกษากำหนดค่าตัวเลขมา 1 จำนวน ตั้งแต่ 15-60 เป็นตัวแปร A จากนั้นให้เลือกตัวเลขตั้งแต่ 2-15 มา 1 จำนวน เป็นตัวแปร B แล้วให้หาว่า ตัวแปร B สามารถหารจำนวนในช่วงที่ 15-A ใดแล้วมีเศษเป็น 0 บ้าง จงแสดงจำนวนทั้งหมดนั้น
A = int(input("Enter A in range 15-60 : "))
B = int(input("Enter B in range 2-15 : "))
for C in range(15,A+1):
if C%B == 0:
print(C,end=' ')
# In[5]:
#ข้อที่ 2 กำหนดข้อมูลมา 1 จำนวน และจงคำนวณหาผลรวมของจำนวนเต็มบวกทุกจำนวนที่มี 2 4 6 และ 8 เป็นตัวประกอบ และมีค่าน้อยกว่าข้อมูลที่กำหนด
nums = [2, 4, 6, 8]
max = int(input("Count: "))
result = 0
for x in range(0,max):
if x%2 == 0 or x%4 == 0 or x%6 == 0 or x%8 == 0:
result += x
print("Answer is ",result)
# In[6]:
#ข้อที่ 3 จงแปลงอุณภูมิจากองศาเซลเซียสเป็นองศาฟาเรนไฮ และจากองศาเซลเซียสเป็นองศาเคลวิน
temperature = float(input("temp ํC :" ))
temperature_convert_ํC_to_ํF = (9/5*temperature)+32
temperature_convert_ํC_to_ํK = (temperature + 273.15)
print("temp ํF = ", temperature_convert_ํC_to_ํF," " "temp ํK = " ,temperature_convert_ํC_to_ํK)
# In[7]:
#ข้อที่ 4 หนอนตัวหนึ่ง พยายามปีนต้นไม้ที่มีความสูง T เมตร หนอนพยายามจะไต่ให้ถึงยอดต้นไม้ ในเวลากลางวันหนอนไต่ขึ้นไปได้ W เมตร เวลากลางคืนหนอนนอนหลับจึงไม่ได้ไต่แต่กลับไถลลงมาเป็นระยะทาง F เมตร จงหาว่าหนอนจะใช้เวลากี่วันในการไต่ไปถึงยอดไม้ (กำหนดให้หนอนทากเริ่มไต่ในเวลากลางวัน)
T = int(input("T: "))
W = int(input("W: "))
F = int(input("F: "))
s = 0
day = 1
while True:
s = s+W
if s>=T:
break
s = s-F
day = day+1
print(day,"day(s).")
# In[8]:
#ข้อที่ 5 จงทำการตรวจสอบความถูกต้องของ ISBN จะใช้ตัวเลขหลักสุดท้ายเป็น check digit ในการตรวจสอบความถูกต้องของตัวเลขอื่น ๆ โดยวิธีที่ใช้ตรวจสอบคือ10n1+ 9n2+ 8n3+ 7n4+ 6n5+ 5n6+ 4n7+ 3n8+ 2n9+ n10 จะต้องหารด้วย 11 ลงตัวหากกำหนดตัวเลขหลักที่ 1-9 มาให้ จงคำนวณหา ISBN ทั้งสิบหลัก
n1 = int(input("n1 :"))
n2 = int(input("n2 :"))
n3 = int(input("n3 :"))
n4 = int(input("n4 :"))
n5 = int(input("n5 :"))
n6 = int(input("n6 :"))
n7 = int(input("n7 :"))
n8 = int(input("n8 :"))
n9 = int(input("n9 :"))
print(str(n1) + str(n2) + str(n3) + str(n4) + str(n5) + str(n6) + str(n7) + str(n8) + str(n9))
ISBN1to9 = ((10 * n1) + (9 * n2) + (8 * n3) + (7 * n4) + (6 * n5) + (5 * n6) + (4 * n7) + (3 * n8) + (2 * n9))
if (ISBN1to9 + 1) % 11 == 0:
print(str(n1) + str(n2) + str(n3) + str(n4) + str(n5) + str(n6) + str(n7) + str(n8) + str(n9) + "1")
elif (ISBN1to9 + 2) % 11 == 0:
print(str(n1) + str(n2) + str(n3) + str(n4) + str(n5) + str(n6) + str(n7) + str(n8) + str(n9) + "2")
elif (ISBN1to9 + 3) % 11 == 0:
print(str(n1) + str(n2) + str(n3) + str(n4) + str(n5) + str(n6) + str(n7) + str(n8) + str(n9) + "3")
elif (ISBN1to9 + 4) % 11 == 0:
print(str(n1) + str(n2) + str(n3) + str(n4) + str(n5) + str(n6) + str(n7) + str(n8) + str(n9) + "4")
elif (ISBN1to9 + 5) % 11 == 0:
print(str(n1) + str(n2) + str(n3) + str(n4) + str(n5) + str(n6) + str(n7) + str(n8) + str(n9) + "5")
elif (ISBN1to9 + 6) % 11 == 0:
print(str(n1) + str(n2) + str(n3) + str(n4) + str(n5) + str(n6) + str(n7) + str(n8) + str(n9) + "6")
elif (ISBN1to9 + 7) % 11 == 0:
print(str(n1) + str(n2) + str(n3) + str(n4) + str(n5) + str(n6) + str(n7) + str(n8) + str(n9) + "7")
elif (ISBN1to9 + 8) % 11 == 0:
print(str(n1) + str(n2) + str(n3) + str(n4) + str(n5) + str(n6) + str(n7) + str(n8) + str(n9) + "8")
elif (ISBN1to9 + 9) % 11 == 0:
print(str(n1) + str(n2) + str(n3) + str(n4) + str(n5) + str(n6) + str(n7) + str(n8) + str(n9) + "9")
else:
print("ERROR")
# In[9]:
#ข้อที่ 6 ให้กำหนดข้อมูลใดก็ได้ที่เป็นจำนวนจริงจนกว่าจะพบค่า -1 เพื่อหาค่าเฉลี่ยของจำนวนเหล่านั้นทั้งหมด (ไม่รวม -1)
sum = 0
count = 0
n = float(input("enter number"))
while n != -1:
sum += n
count = count + 1
n = float(input("enter number"))
avg = sum / count
print(avg)
# In[10]:
#ข้อที่ 7 จงเขียนคำนวณหาความยาวของด้านที่สามของสามเหลี่ยม เมื่อเราทราบความยาวด้านสองด้าน (a กับ b)และมุมระหว่างด้านสองด้านนั้น (C) ซึ่งคำนวณได้จาก Law of Cosines
import math
A=float(input("A SIDE LENGTH : "))
B=float(input("B SIDE LENGTH :"))
D=float(input("CORNER C :"))
C=D*math.pi/180
c=math.sqrt((A**2)+(B**2)-(2*A*B*math.cos(C)))
print("c = ",c, "cm.")
# In[12]:
#ข้อที่ 8 ให้ทำการกำหนดคะแนนเพื่อตัดเกรดตามเกณฑ์ที่ระบุ โดย 100-80=A 79-75=B+ 74-70=B 69-65=C+ 64-60=C 59-55=D+ 54-50=D >50=F โดยในกรณีที่คะแนนมีข้อผิดพลาด ให้แสดงผลว่า ERROR
x = int(input("score:"))
if 100>=x>=80:
print("A")
elif 80>x>=75:
print("B+")
elif 75>x>=70:
print("B")
elif 70>x>=65:
print("C+")
elif 65>x>=60:
print("C")
elif 60>x>=55:
print("D+")
elif 55>x>=50:
print("D")
elif 50>x:
print("F")
else:
print("error")
# In[11]:
#ข้อที่ 9 ร้านขายโต๊ะร้านหนึ่ง พยายามเพิ่มยอดขายโดยการเสนอโปรโมชั่นพิเศษ ถ้าคุณซื้อโต๊ะมากกว่า 5 ตัว ที่มีมูลค่ารวมเกิน 18000 บาท คุณจะได้ส่วนลด 20% ให้คำนวณจำนวนโต๊ะที่ซื้อและราคารวม จากนั้นคำนวณราคาที่ต้องจ่าย
Count = int(input("How many table: "))
money = int(input("How much: "))
if Count > 5 and money > 18000:
s = money-money*0.2
else:
s = money
print("You have to pay",int(s),"bath.")
# In[13]:
#ข้อที่ 10 จงคำนวณหาค่าโอห์มรวมของวงจรแบบขนาน ตามสูตร RT = (R1 x R2)/(R1 + R2) โดยกำหนดให้ R1 = 250 Ohm. และ R2 = 870 Ohm.
print("R1 = 250 Ohm.")
print("")
print("R2 = 870 Ohm.")
print("")
print("RT = (R1 x R2)/(R1 + R2)")
print("")
print("RT = " ,(250*870)/(250+870),"Ohm.")
# In[ ]:
|
921a62fee651c6cc5ce3bf0e08928d0b725c03b8 | dubugun/big_data_web | /python/0131/두수비트연산.py | 792 | 3.578125 | 4 | sel = int(input("진수(2/8/10/16)를 선택하시오"))
num1 = input("첫 번째 수를 입력하시오. ")
num2 = input("두 번째 수를 입력하시오. ")
num11 = int(num1, sel)
num22 = int(num2, sel)
print("두 수의 & 연산 결과")
print("16진수 ==> ",hex(num11&num22))
print("8진수 ==> ",oct(num11&num22))
print("10진수 ==> ",num11&num22)
print("2진수 ==> ",bin(num11&num22),'\n')
print("두 수의 | 연산 결과")
print("16진수 ==> ",hex(num11|num22))
print("8진수 ==> ",oct(num11|num22))
print("10진수 ==> ",num11|num22)
print("2진수 ==> ",bin(num11|num22),'\n')
print("두 수의 ^ 연산 결과")
print("16진수 ==> ",hex(num11^num22))
print("8진수 ==> ",oct(num11^num22))
print("10진수 ==> ",num11^num22)
print("2진수 ==> ",bin(num11^num22))
|
188ebc1523e59cface7df486908fddfe1237c58d | gisselleroldan/Digital-Crafts | /Python/Homework/phonebook.py | 1,530 | 4.125 | 4 | # CRUD - create, read, update, delete
phonebook = {}
import pickle
with open('phonebook.pickle', 'rb') as fh:
phonebook = pickle.load(fh)
keep_going = True
def lookup():
name = input("Enter whose number would you like to look up: ")
if name in phonebook:
print(f'Number for {name} is: {phonebook[name]}')
else:
print("Name not found. Please try again.")
def add():
name = input('Name: ')
number = input('Phone number: ')
phonebook[name] = number
with open('phonebook.pickle', 'wb') as fh:
pickle.dump(phonebook, fh)
print(f'Entry stored for {name}.')
def display():
for index, item in enumerate(phonebook):
print(f"{index + 1} {item} {phonebook[item]}")
def delete():
name = input('Enter a name to delete: ')
if name in phonebook.keys():
del phonebook[name]
with open('phonebook.pickle', 'wb') as fh:
pickle.dump(phonebook, fh)
print(f'{name} was deleted')
else:
print('No entry found under that name')
print('''
Electronic Phone Book
=====================
1. Look up an entry
2. Add an entry
3. Delete an entry
4. List all entries
5. Quit
''')
while keep_going == True:
choice = int(input('What do you want to do (1-5)? '))
if choice == 1:
lookup()
elif choice == 2:
add()
elif choice == 3:
delete()
elif choice == 4:
display()
elif choice == 5:
print('Quit Program')
keep_going == False
break
|
505f712290f0db9911709fd231891cced65d3921 | WampiFlampi/Temporary-Python | /Tutorial2.py | 229 | 4.25 | 4 | number = input("Place your number here!")
check = int(number) % 2
number = int(number)
if number == 0:
print("neither even nor odd")
else:
if check == 1:
print("the number is odd")
else:
print("the number is even")
|
4e3225e0cf2f649d1562b67173a3745f723ef1ac | NavneetChoudry/DataScience-Python | /Matplotlib/LINE GRAPH.py | 234 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 8 09:44:33 2018
@author: Navneet Choudry
LINE GRAPH
"""
from matplotlib import pyplot as plt
x = [5,8,10]
y = [12,16,6]
plt.plot(x,y)
plt.title("info")
plt.ylable("Yaxis")
plt.xlabel("Xaxis")
|
b4f09f3550ad06c9b464bfcd70e11ad2a5c9fe10 | Ismazgz14/TIC_20-21 | /ululador.py | 347 | 3.921875 | 4 | '''Haz un programa que lea una cadena y sustituya
las vocales por la letra u. palabra de 10, For'''
def ululador():
palabra=raw_input("Introduce una palabra para ulular. ")
for cont in range (0,11):
if(palabra [cont]=='a'):
print 'u'
else:
print palabra[cont]
ululador()
|
f4405340f5885e2b0ee45ab4212a369146a5852a | DT211C-2019/programming | /Year 2/Saul Burgess/Labs/2020-10-15/Lab10(1).py | 267 | 3.90625 | 4 | def list_adder(list):
'''When passed a list, will return an intiger containing the total
of the list'''
ans=0
for i in range(len(list)):
ans+=list[i]
return ans
sample_list = [1,2,3,4,5,6]
print("The answer is", list_adder(sample_list)) |
9a3abe8fd5b06350a888ca5c9dfe9da554c5f303 | qqqlllyyyy/LintCode-Python | /09-High-Frequency/12 Maximum Subarray.py | 990 | 4.15625 | 4 | # Maximum Subarray
# Given an array of integers, find a contiguous subarray which has
# the largest sum.
#
# Example
# Given the array [-2,2,-3,4,-1,2,1,-5,3], the contiguous
# subarray [4,-1,2,1] has the largest sum = 6
#
# Challenge
# Can you do it in time complexity O(n)?
#
class Solution:
"""
@param nums: A list of integers
@return: An integer denote the sum of maximum subarray
"""
def maxSubArray(self, nums):
# write your code here
if nums == None or len(nums) == 0: return 0
result = float("-infinity")
sum, minSum = 0, 0
for i in range(len(nums)):
sum += nums[i]
# For the following two steps, we can not change the order!
# Because if we update "minSum" first, the result may be 0,
# which is sum minus itself. (nums = [-1]).
result = max(result, sum - minSum)
minSum = min(sum, minSum)
return result
|
58b2906855bd2203296f657bc39fea8eca5263ca | LXwolf123/python-2021-7 | /Ui_Joseph/user_case/reader.py | 2,090 | 3.515625 | 4 | import csv
import zipfile
import xlrd
import os #pandas 这个库好用
import pandas as pd
class Reader(object):
def __init__(self, filePath):
self.filePath = filePath
def read(self): #父类先实现该方法
pass
class CsvReader(Reader):
def __init__(self, filePath):
assert filePath.endswith('.csv')
self.filePath = filePath
def read(self) -> list:
csvFile = pd.read_csv(self.filePath)
csvDataList = csvFile.values.tolist()
return csvDataList
def saveFile(self, dataList): #保存数据
df = pd.DataFrame(dataList)
df.to_csv(self.filePath,index=False)
class XlsReader(Reader):
def __init__(self, filePath, sheetName):
assert filePath.endswith('.xls')
self.filePath = filePath
self.sheetName = sheetName
def read(self) -> list:
xlsFile = pd.read_excel(self.filePath, sheet_name=self.sheetName)
xlsDataList = xlsFile.values.tolist()
return xlsDataList
def saveFile(self, dataList):
df = pd.DataFrame(dataList)
df.to_excel(self.filePath, index=False)
class ZipReader(Reader):
def __init__(self, filePath, interFileName):
assert filePath.endswith('.zip')
assert interFileName.endswith('.csv') or interFileName.endswith('.xls')
self.filePath = filePath
self.interName = interFileName
def read(self) -> list:
with zipfile.ZipFile(self.filePath, "r") as zip:
folder,fileName = os.path.split(self.filePath)
print(folder)
zip.extract(self.interName, folder) #解压指定文件
if (".csv" in self.interName):
return CsvReader(folder+'\{0}'.format(self.interName)).read()
elif (".xls" in self.interName):
return XlsReader(folder+'\{0}'.format(self.interName), "Sheet1").read()
def saveFile(self): #压缩包里的文件不能随便改变, 为了保持程序的完整性,加上
pass
|
3f6ca19176ab49037380bb96756153c668ebd430 | asatav/Python-All-Example | /RegularExpression/Demo1.py | 220 | 3.984375 | 4 | import re
count=0
pattern=re.compile("ab")
matcher=pattern.finditer("abaababa")
for match in matcher:
count+=1
print(match.start(),"...",match.end(),"...",match.group())
print("The number of occurrences:",count) |
840060bb21bb1384384a71d5e8934cf45c0edd9b | syedshameersarwar/pandas_init | /data_handling.py | 2,203 | 3.875 | 4 | import pandas as pd
import numpy as np
string_data = pd.Series(['aardvark', 'artichoke', np.nan, 'avocado'])
print(string_data)
print(string_data.isnull())
# The built-in Python None value is also
# treated as NA in object arrays
string_data[0] = None
print(string_data.isnull())
# filtering out missing data
print('Filtering out missing data(dropna):')
d = pd.Series([1, np.nan, 3.5, np.nan, 7])
print(d.dropna())
print(d[d.notnull()]) # alternative
# for dataframes, dropna by default drops
# any row containing a missing value
print('Dropna on dataframe:')
df = pd.DataFrame([[1., 6.5, 3.], [1., np.nan, np.nan],
[np.nan, np.nan, np.nan], [np.nan, 6.5, 3.]])
print(df.dropna())
print('Dropping only rows that are all NA:')
print(df.dropna(how='all'))
# Dropping columns in the same way is only a
# matter of passing axis=1:
print('Dropping columns that are all NA')
df[4] = np.nan
print(df)
print(df.dropna(axis=1, how='all'))
# you want to keep only rows containing a certain number
# of observations. You can
# indicate this with the thresh argument:
print('Threshing data frame"')
df2 = pd.DataFrame(np.random.randn(7, 3))
df2.ix[:4, 1] = np.nan
df2.ix[:2, 2] = np.nan
print(df2)
print(df2.dropna(thresh=3))
# Filling in missing data
print("Filling in missing data: fillna")
print(df2.fillna(0))
print("Filling in missing data:fillna=> passing dict")
# Calling fillna with a dict you can use a different
# fill value for each column
print(df2.fillna({1: 0.5, 2: -1}))
# modify existing dataframe
print('Inplace fillna:')
df2.fillna(0, inplace=True)
print(df2)
# using filling methods:
# same interpolation methods available for reindexing
# can be used with fillna:
df3 = pd.DataFrame(np.random.randn(6, 3))
df3.ix[:2, 1] = np.nan
df3.ix[4:, 2] = np.nan
print('Using filling methods with fillna:')
print(df3)
print(df3.fillna(method='ffill'))
print('fillna with method & limit:')
print(df.fillna(method='ffill', limit=2))
# little creativity
print('Little creativity:')
un_cleaned = pd.Series([1., np.nan, 3.5, np.nan, 7])
print(un_cleaned.fillna(un_cleaned.mean()))
# limit For forward and backward filling,
# maximum number of consecutive periods to fill
|
384f64b575ed819dc569d6b3db4ba4ed9e20f3ba | sachinbiradar9/Autograder | /src/gradient descent/linear.py | 4,173 | 3.671875 | 4 | """
Implementation of *regularized* linear classification/regression by
plug-and-play loss functions
"""
from numpy import *
from gd import *
from binary import *
class LossFunction:
def loss(self, Y, Yhat):
"""
The true values are in the vector Y; the predicted values are
in Yhat; compute the loss associated with these predictions.
"""
util.raiseNotDefined()
def lossGradient(self, X, Y, Yhat):
"""
The inputs are in the matrix X, the true values are in the
vector Y; the predicted values are in Yhat; compute the
gradient of the loss associated with these predictions.
"""
util.raiseNotDefined()
class HingeLoss(LossFunction):
"""
Hinge loss is sum_n max{ 0, 1 - y_n * y'_n }
"""
def loss(self, Y, Yhat):
"""
The true values are in the vector Y; the predicted values are
in Yhat; compute the loss associated with these predictions.
"""
return sum(list(map(lambda x: max(0,x), 1 - Y * Yhat)))
def lossGradient(self, X, Y, Yhat):
"""
The inputs are in the matrix X, the true values are in the
vector Y; the predicted values are in Yhat; compute the
gradient of the loss associated with these predictions.
"""
return sum([-1*Y[i]*X[i] for i,x in enumerate(Y * Yhat) if x<=1], axis=0)
class LinearClassifier(BinaryClassifier):
"""
This class defines an arbitrary linear classifier parameterized by
a loss function and a ||w||^2 regularizer.
"""
def __init__(self, opts):
"""
Initialize the classifier. Like perceptron, we need to start
out with a weight vector; unlike perceptron, we'll leave off
the bias. Also, we are not online, so we implement that full
train method.
"""
# remember the options
self.opts = opts
# just call reset
self.reset()
def reset(self):
self.weights = 0
def online(self):
"""
We're not online
"""
return False
def __repr__(self):
"""
Return a string representation of the tree
"""
return "w=" + repr(self.weights)
def predict(self, X):
"""
X is a vector that we're supposed to make a prediction about.
Our return value should be the margin at this point.
Semantically, a return value <0 means class -1 and a return
value >=0 means class +1
"""
if type(self.weights) == int:
return 0
else:
return dot(self.weights, X)
def getRepresentation(self):
"""
Return the weights
"""
return self.weights
def train(self, X, Y):
"""
Train a linear model using gradient descent, based on code in
module gd.
"""
# get the relevant options
lossFn = self.opts['lossFunction'] # loss function to optimize
lambd = self.opts['lambda'] # regularizer is (lambd / 2) * ||w||^2
numIter = self.opts['numIter'] # how many iterations of gd to run
stepSize = self.opts['stepSize'] # what should be our GD step size?
# define our objective function based on loss, lambd and (X,Y)
def func(w):
# should compute obj = loss(w) + (lambd/2) * norm(w)^2
Yhat = [sum(w * x) for x in X]
obj = lossFn.loss(Y,Yhat) + lambd * linalg.norm(w) ** 2
# return the objective
return obj
# define our gradient function based on loss, lambd and (X,Y)
def grad(w):
# should compute gr = grad(w) + lambd * w
Yhat = [sum(w * x) for x in X]
gr = lossFn.lossGradient(X, Y, Yhat) + lambd * w
return gr
# run gradient descent; our initial point will just be our
# weight vector
w, trajectory = gd(func, grad, self.weights, numIter, stepSize)
# store the weights and trajectory
self.weights = w
self.trajectory = trajectory
|
e84ae46c564ee191533f7c02738d33f1be511880 | phhm/thefruitflygang | /Breakpoint_function.py | 1,714 | 3.796875 | 4 | Melanogaster = [23,1,2,11,24,22,19,6,10,7,25,20,5,8,18,12,13,14,15,16,17,21,3,4,9]
def breakpoint_search(List):
'''
Function to determine Breakpoint positions.
Breakpoints are returned in a list containing each Breakpoint.
'''
# Creating borders to check for Breakpoints before the first, and behind the last element.
start = min(List) - 1
end = max(List) + 1
# copy the List, appending start and end
List_breakpoint_check = List[:]
List_breakpoint_check.append(end)
List_breakpoint_check.insert(0,start)
# Creates an empty list of Breakpoints, This is used to append the breakpoints found in the Genome.
# Checker is the value of the previous List element, starting at the first element of our List: start.
# Count is used to keep track of the index value inside our List while looping.
Breakpoints = []
checker = start
count = 0
# For-loop used to check if an element is consecutive with the previous value (either +1 or -1).
# Previous value is determined by checker and updated using "count".
for e in List_breakpoint_check[1:]:
# if element is consecutive with the previous value, skip to next value
if e == checker + 1 or e == checker -1:
count += 1
checker = List_breakpoint_check[count]
# if value is non-consecutive with the previous value, append it to Breakpoints
else:
Breakpoints.append(List_breakpoint_check.index(e))
count += 1
checker = List_breakpoint_check[count]
return Breakpoints
Where_are_the_breakpoints = breakpoint_search(Melanogaster)
print "this is where are breakpoints are located: ", Where_are_the_breakpoints
print "This is how many breakpoints we have now: " + str(len(Where_are_the_breakpoints))
print Where_are_the_breakpoints
|
74aec538ae2308f6d5fe0322dab27630072b76e1 | quixoteji/Leetcode | /solutions/261.graph-valid-tree.py | 1,048 | 3.65625 | 4 | #
# @lc app=leetcode id=261 lang=python3
#
# [261] Graph Valid Tree
#
# @lc code=start
class Solution:
# topological sort
# 0 : unknown 1 : visiting 2 : visited
def validTree(self, n: int, edges: List[List[int]]) -> bool:
return self.sol1(n, edges)
# Solution 1 : dfs
def sol1(self, n, edges) :
graph = collections.defaultdict(list)
for edge in edges:
u,v = edge[0], edge[1]
graph[u].append(v)
graph[v].append(u)
visited = set([])
if self.dfs(0, -1, graph, visited):
return False
if len(visited) != n:
return False
return True
def dfs(self, node, parent, graph, visited):
visited.add(node)
for nbr in graph[node]:
if nbr not in visited:
if self.dfs(nbr, node, graph, visited):
return True
elif nbr in visited and nbr != parent:
return True
return False
# UnionFind
# @lc code=end
|
40fae480f5b34757c7ebd1fe8c83e47068d9adce | JT4life/PythonRevisePractice | /inheritancePractice.py | 671 | 3.734375 | 4 | class A():
def __init__(self):
self.name = 'joshua'
def view(self):
print("My name in A is ",self.name)
def sayHello(self):
print("Hello there")
class B(A):
def __init__(self):
self.name = "JayZ"
A.__init__(self) #because this is declared after 'joshua' would be used
self.lastname = "Thao"
def view(self):
print(self.name, " ", self.lastname)
def sayHi(self):
print("Hi there")
class C(B):
def function1(self):
print("Function from C")
def sayHello(self):
print("Hello from C class")
super().sayHello()
o1 = B()
#
o1.view()
o2 = C()
o2.sayHello() |
12f82c423e43a0dc2802c7b6bf7f752372f1d06d | WeilieChen/data-engineer-interview | /facebook/screening/python/highest_neighbor.py | 640 | 3.546875 | 4 | """
Find the alphabet with highest neighbors
"""
def solution(data):
count = {}
for group in data:
if len(group) == 1:
count[group[0]] = count.get(group[0], 0) + 0
else:
for node in group:
count[node] = count.get(node, 0) + 1
highest = max(count.values(), default=-1)
result = [
k for k, v in count.items()
if v == highest
]
return result
assert solution([]) == []
assert solution([[]]) == []
assert solution([['A', 'B']]) == ['A', 'B']
assert solution([['A'], ['A', 'B'], ['A', 'C'], [
'B', 'D'], ['C', 'A']]) == ['A']
|
36abab3b6da56105277743d1b5d70be728edff80 | mudit2103/courserapython | /pong.py | 5,361 | 3.5 | 4 | # Implementation of classic arcade game Pong
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 4
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
LEFT = False
RIGHT = True
ball_pos = [WIDTH/2, HEIGHT/2]
ball_vel = [0,0]
paddle1_pos = [4,0]
paddle1_posend = [4,80]
paddle2_pos = [WIDTH - PAD_WIDTH + 4, 0]
paddle2_posend = [WIDTH - PAD_WIDTH + 4,80]
paddle1_vel = [0,0]
paddle2_vel = [0,0]
redscore = 0
bluescore = 0
paddlespeed = 3
# initialize ball_pos and ball_vel for new bal in middle of table
# if direction is RIGHT, the ball's velocity is upper right, else upper left
def spawn_ball(direction):
global ball_pos, ball_vel # these are vectors stored as lists
ball_pos = [WIDTH/2, HEIGHT/2]
vert = random.randrange(60, 180) / 60
hori = random.randrange(120, 240) / 60
if direction == RIGHT:
ball_vel = [hori,-vert]
else:
ball_vel = [-hori,-vert]
# define event handlers
def new_game():
global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel
global ball_pos, ball_vel, paddle1_pos, paddle1_posend, paddle2_pos, paddle2_posend
global paddlespeed
# these are numbers
global redscore, bluescore # these are ints
redscore = 0
bluescore = 0
paddle1_vel = [0,0]
paddle2_vel = [0,0]
ball_pos = [WIDTH/2, HEIGHT/2]
ball_vel = [0,0]
paddle1_pos = [4,0]
paddle1_posend = [4,80]
paddle2_pos = [WIDTH - PAD_WIDTH + 4, 0]
paddle2_posend = [WIDTH - PAD_WIDTH + 4,80]
paddlespeed=3
spawn_ball(LEFT)
def draw(canvas):
global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel, paddle1_posend, paddle2_posend
global paddle1_vel, paddle2_vel
global redscore, bluescore, paddlespeed
# draw mid line and gutters
canvas.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White")
canvas.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White")
canvas.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White")
# update ball
if (ball_pos[1]<=BALL_RADIUS):
ball_vel[1] = - ball_vel[1]
elif (ball_pos[1]>=(HEIGHT-1-BALL_RADIUS)):
ball_vel[1] = -ball_vel[1]
ball_pos[0] += ball_vel[0]
ball_pos[1] += ball_vel[1]
# draw ball
canvas.draw_circle(ball_pos, BALL_RADIUS, 10, 'Yellow', 'Orange')
# determine whether ball collides with gutter
if (ball_pos[0]<=(PAD_WIDTH + BALL_RADIUS)):
if(ball_pos[1]>(paddle1_pos[1]) and ball_pos[1]<(paddle1_posend[1])):
ball_vel[0] = -(ball_vel[0]+0.1*ball_vel[0])
ball_vel[1] = -(ball_vel[1]+0.1*ball_vel[1])
paddlespeed += 0.1*paddlespeed
else:
bluescore +=1
spawn_ball(RIGHT)
elif (ball_pos[0] >= (WIDTH - PAD_WIDTH - BALL_RADIUS - 1)):
if(ball_pos[1]>(paddle2_pos[1]) and ball_pos[1]<(paddle2_posend[1])):
ball_vel[0] = -(ball_vel[0] + 0.1*ball_vel[0])
ball_vel[1] = (ball_vel[1] + 0.1*ball_vel[1])
paddlespeed += 0.1*paddlespeed
else:
redscore +=1
spawn_ball(LEFT)
# update paddle's vertical position, keep paddle on the screen
if(paddle1_pos[1]+paddle1_vel[1]>=0):
if(paddle1_pos[1] + paddle1_vel[1]<=HEIGHT-PAD_HEIGHT+1):
paddle1_pos[1] += paddle1_vel[1]
if(paddle2_pos[1]+paddle2_vel[1]>=0):
if(paddle2_pos[1] + paddle2_vel[1]<=HEIGHT-PAD_HEIGHT+1):
paddle2_pos[1] += paddle2_vel[1]
# draw paddles
paddle1_posend[1] = paddle1_pos[1] + PAD_HEIGHT
paddle2_posend[1] = paddle2_pos[1] + PAD_HEIGHT
canvas.draw_line(paddle1_pos, paddle1_posend, PAD_WIDTH, 'Red')
canvas.draw_line(paddle2_pos, paddle2_posend, PAD_WIDTH, 'Blue')
canvas.draw_text(str(redscore), (100, 40), 25, 'Red')
canvas.draw_text(str(bluescore), (500, 40), 25, 'Blue')
# determine whether paddle and ball collide
# draw scores
def keydown(key):
global paddle1_vel, paddle2_vel, paddlespeed
if(key == simplegui.KEY_MAP['w']):
paddle1_vel = [0,-paddlespeed]
if(key == simplegui.KEY_MAP['s']):
paddle1_vel = [0,paddlespeed]
if(key == simplegui.KEY_MAP['up']):
paddle2_vel = [0,-paddlespeed]
if(key == simplegui.KEY_MAP['down']):
paddle2_vel = [0,paddlespeed]
def keyup(key):
global paddle1_vel, paddle2_vel
if(key == simplegui.KEY_MAP['w']):
paddle1_vel = [0,0]
if(key == simplegui.KEY_MAP['s']):
paddle1_vel = [0,0]
if(key == simplegui.KEY_MAP['up']):
paddle2_vel = [0,0]
if(key == simplegui.KEY_MAP['down']):
paddle2_vel = [0,0]
def button_handler():
new_game()
# create frame
frame = simplegui.create_frame("Pong", WIDTH, HEIGHT)
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
button1 = frame.add_button('Restart', button_handler)
# start frame
new_game()
frame.start()
|
5b23f87d82b4596860ca67e2d6232e4207f053a9 | kanosaki/picbot | /picbot/utils/__init__.py | 824 | 3.5 | 4 |
import itertools
def uniq(*iters):
"""Make unique iterator with preserving orders. """
return UniqueIterator(itertools.chain(*iters))
class UniqueIterator(object):
def __init__(self, source):
self.source = source
self._history = set()
def __iter__(self):
return self
def __next__(self):
next_candidate = next(self.source)
while next_candidate in self._history:
next_candidate = next(self.source)
self._history.add(next_candidate)
return next_candidate
class AttrAccess(dict):
def __getattr__(self, key):
try:
v = self[key]
if isinstance(v, dict):
return AttrAccess(**v)
else:
return v
except KeyError:
raise AttributeError(key)
|
8af333cb4512847777511f653fce1921a1085846 | r25ta/USP_python_2 | /semana4/exercicio_busca_binaria_recursiva.py | 1,368 | 4.1875 | 4 | """ ALGORITIMO DE BUSCA BINARIA RECURSIVA
O SISTEMA RECEBE UMA LISTA ORDENADA E O ELEMENTO A SER PROCURADO
"""
def search_binary_recursive(list,element):
'''CONSISTE SE A LISTA ESTÁ VAZIA GERALMENTE PARA CASOS ONDE A LISTA FOI TOTALMENTE
EXPLORADA E O ELEMENTO NÃO ENCONTRADO'''
if(len(list)==0):
return False
else:
'''DIVIDE A LISTA NO MEIO'''
midpoint = len(list)//2
#VERIFICA SE O ELEMENTO É IGUAL AO INDICE CENTRAL DA LISTA
if(element==list[midpoint]):
return True
else:
#SE ELEMENTO FOR MENOR QUE ITEM CENTRAL DA LISTA
if(element<list[midpoint]):
#CHAMA A FUNÇÃO NOVAMENTE (RECURSIVIDADE) PASSANDO COMO PARAMETRO
# A LISTA COM TODOS ITENS ATÉ A METADE A ESQUERDA (SLICE :)
return search_binary_recursive(list[:midpoint],element)
else:
#SE ELEMENTO FORM MAIOR QUE ITEM CENTRAL DA LISTA
# CHAMA A FUNÇÃO NOVAMENTE PASSANDO COMO PARAMETRO MIDPOINT + 1 E TODA
#METADE A DIREITA DA LISTA
return search_binary_recursive(list[midpoint + 1:],element)
if __name__ == "__main__":
list = [1,2,3,5,7,9,12,34,56,78,90]
print(search_binary_recursive(list,34))
print(search_binary_recursive(list,15)) |
6990fd4b69f9f5235c85f720ae1fea76b2625bf4 | knysna/POTD | /potd.py | 2,521 | 3.734375 | 4 | __author__ = 'admin'
""" potd (Password of The Day)
Calculates the passwords for today based on the well known formula. The purpose is to save a few minutes work each day.
Writes the passwords into html and sets up a little http daemon for access. The listening port can be specified.
Browse to <IP>:PORT
The html page is rewritten constantly so that the information is always up to date.
"""
import datetime
import time
import http.server
import socketserver
# Obtain today's date and breakdown into components
todayp = datetime.datetime.now()
pwyear = int(todayp.year)
pwmonth = int(todayp.month)
pwday = int(todayp.day)
# Determine the passwords for today
def exitpw1gen():
return pwyear + pwmonth + pwday
def exitpw2gen():
return pwyear + pwmonth - pwday
def potdhtml():
'''
Put today's passwords into html format with some headings. Set the browser to auto refresh at an interval.
'''
potdContent ="<html>"
potdContent += "<head><meta http-equiv='refresh' content='60'><h2>Password Of The Day</h2></head><body><h4>Today's Date Is: "
potdContent += str(datetime.datetime.today().strftime("%d/%m/%Y"))
potdContent += "</h4><p>Exit Password #1 is: "
potdContent += str(exitpw1gen())
potdContent += "</p><p>Exit Password #2 is: "
potdContent += str(exitpw2gen())
potdContent += "</p><br>"
potdContent += "<p>Page was generated at "
potdContent += str(datetime.datetime.now())
potdContent +="</p></body></html>"
return potdContent
def makefile( myfilename, mycontent ):
'''
Create a file with the specified name, write the content to the file then close the file.
myfilename is the name of the file to be created including single quotes e.g. 'index.html'
mycontent is the content to be written into the file including single quotes e.g. 'this is some content'
'''
f = open(myfilename,'w')
f.write(mycontent)
f.close()
# Make a webserver
def mini_web_server( myport=8080 ):
'''
A very light web server listening on the specified port number. Default port is 8080.
Also constantly rewrite the index.html file so that the information is always up to date
'''
PORT = myport
handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), handler)
print("serving at port", PORT)
while keepgoing():
httpd.handle_request()
makefile('index.html', potdhtml())
time.sleep(1)
def keepgoing():
return True
mini_web_server(8088)
|
64b6cdc27b4fff2bf7f587b48a37bd9b8ce15062 | w40141/atcoder | /abc_247/c.py | 143 | 3.5 | 4 | n = int(input())
def s(n):
if n == 1:
return "1 "
else:
return s(n - 1) + str(n) + " " + s(n - 1)
print(s(n)[:-1])
|
45b08d586d1f072a685d4fb7f09b7c8fa8645074 | Elly-bang/python | /chap06_Class_Module_lecture/step01_class_basic.py | 2,761 | 3.796875 | 4 | '''
클래스(class)
-함수의 모임
-역할: 다수의 함수와 공유 자료를 묶어서 객체(object) 생성
-유형 : 사용자 정의 클래스, 라이브러리 클래스 (python)
-구성 요소: 멤버(member)+생성자
-멤버(member): 변수(자료 저장) + 메서드(자료 처리)
-생성자 : 객체 생성
#####################
형식)
class 클래스명 :
멤버변수 = 자료
def 멤버메서드() :
자료 처리
생성자 : 객체 생성
#####################
'''
#1.중첩함수
def calc_func(a,b): #outer : 자료 저장
#자료 저장
x = a
y = b
#inner :자료 처리(조작)
def plus():
return x+y
def minus():
return x-y
return plus, minus
p, m = calc_func(10, 20) #일급함수 : +는 p로, -는 m으로 저장
print('plus=',p()) #plus= 30
print('minus=',m()) #minus= -10
#2. 클래스 정의
class calc_class:
#member변수(전역 변수): 자료 저장
x = y = 0
#생성자 : 객체 생성 + 멤버 변수 값 초기화
def __init__(self, a, b):
#멤버 변수 초기화
#self.멤버변수=지역변수
self.x = a
self.y = b #비활성화 y회색은 지역변수 뜻함/ self 사용해야 전역 변수
#멤버 메서드 : 클래스에서 정의한 함수 x = y = 0에서 +,-메서드 2가지 만듦(self이용)
def plus(self): #바깥 함수로 접근시 self가 작용
return self.x + self.y
def minus(self):
return self.x - self.y
#클래스(1) vs 객체(n)
#생성자 -> 객체 (object)
obj1 = calc_class(10, 20) #클래스명(): 생성자 -> 객체 생성
#object.member() :멤버 메서드 호출
#obj1.plus()
#obj1.minus()
print('plus=', obj1.plus()) #plus=30
print('minus=', obj1.minus()) #minus=-10
# object.member() :멤버 변수 호출
print('x=', obj1.x) #x=10
print('y=', obj1.y) #y=20
#생성자-> 객체2
obj2= calc_class(100, 200)
print('plus=', obj2.plus()) # plus = 300
print('minus=', obj2.minus()) # minus = -100
print('x=', obj2.x) # x= 100
print('y=', obj2.y) # y= 200
#객체 주소 확인 => class는 하나이며, n개의 객체를 만들기 위한 지도 역할 . 각각 저장됨을 확인.
print(id(obj1),id(obj2)) # 2393244617544 2393244621960
#3. 라이브러리 클래스
from datetime import date #from 모듈 import 클래스
today = date(2020, 4, 13) #생성자 -> 객체
#object.member
print('year :',today.year)
print('month :',today.month)
print('day :',today.day)
#object.member():method
week = today.weekday()
print('week :', week) #week : 0 -> 월요일 : 0~6까지
|
bea1fd4f88652d01c59f6cf56b7888f3ee30a9cd | hks73/project | /weather.py | 2,152 | 3.640625 | 4 | # import pyowm
# import requests
# from datetime import date
# from dateutil.rrule import rrule, DAILY
# API_KEY="68897584b12c57a6f018081baac462c2"
# ################### GET CUURENT WEATHER DETAILS ############################
# x=raw_input("Enter any place to get current weather :")
# owm = pyowm.OWM(API_KEY)
# observation = owm.weather_at_place(x)
# w = observation.get_weather()
# humidity=w.get_humidity()
# temperature=w.get_temperature('celsius')
# print str(temperature['temp'])+ " degree celsius"
# print humidity
# ################################################################################
#
# ######################## GET DATA ACCORDING TO DATE ############################
# location=raw_input("Enter any place to get weather according date :")
# def get_json():
# ########## WE CAN CHANGE DATE HERE #########################################
# a = date(2015, 1, 1)
# b = date(2015, 12, 31)
# for dt in rrule(DAILY, dtstart=a, until=b):
# get_weather(dt.strftime("%Y%m%d"))
# def get_weather(find_date):
# urlstart = 'http://api.wunderground.com/api/9f531938a5579c5e/history_'
# urlend = '/q/Switzerland/Zurich.json'
# url = urlstart + str(find_date) + urlend
# data = requests.get(url).json()
# for summary in data['history']['dailysummary']:
# print ','.join((gooddate,summary['date']['year'],summary['date']['mon'],summary['date']['mday'],summary['precipm'], summary['maxtempm'], summary['meantempm'],summary['mintempm']))
# ################################################################################
import openweather
from datetime import datetime
import json,ast
# create client
ow = openweather.OpenWeather()
print ow.get_weather(1273294)
# historic weather
start_date = datetime(2013, 9, 10)
end_date = datetime(2013, 9, 15)
# default: hourly interval
a= ow.get_historic_weather(4885, start_date, end_date,"day")
data= ast.literal_eval(json.dumps(a))
with open('a.txt','r') as f:
read_data=f.read()
print read_data
f.closed()
# for i,value in enumerate(data):
# print value["temp"]["mi"]
# daily aggregates
# print ow.get_historic_weather(1273294, start_date, end_date, "day")
|
bcb1da2ae519e5b94601070cd56e69aa058b37b3 | OleksandrMakeiev/python_hw | /def gen_primes.py | 370 | 3.609375 | 4 | #30
def gen_primes():
list_of_ints = []
for x in range(1, 101):
if x == 1:
pass
else:
for y in list_of_ints:
if x % y == 0:
break
else:
list_of_ints.append(x)
return list_of_ints
print("Все простые числа от 1 до 100 \n", gen_primes()) |
2a7e3c2f143789b5a09c7f1cf8d1353874639de9 | EmersonDantas/SI-UFPB-IP-P1 | /Exercícios-Lista3-Estrutura sequencial-IP-Python/Lista3-Sld-Pag28-Alg-9.py | 253 | 3.546875 | 4 | #Emerson Dantas S.I IP-P1
#02/08/2017 16:06
print('Para saber sua média, diga suas notas:')
N1= float(input('Nota 1:'))
N2= float(input('Nota 2:'))
N3= float(input('Nota 3:'))
N1F= (N1*2)
N2F= (N2*3)
N3F= (N3*5)
NF= ((N1F+N2F+N3F)/10)
print('Sua média:',NF)
|
6cc02658076f1b458e0c981741f56a10a1c3a18c | sowmiyavelu17/geet | /cancatenate.py | 132 | 4.03125 | 4 | s1=input('Please enter the first string:\n')
s2=input('Please enter the second string:\n')
print('Concatenated String =', s1 + s2)
|
3f69a86216b5ec08c7135fdd889bd5136b1a5760 | manojach87/ludo | /src/game.py | 3,044 | 3.65625 | 4 | colors = {0: "red", 1: "green", 2: "yellow", 3: "blue"}
## This class is for the gatti
class gatti:
loc = -1
MAXMOVES = 56
inSafeZone = True
SAFEZONES = [-1, 0, 8, 13, 21, 26, 34, 39, 47]
HOMEZONES = [51, 52, 53, 54, 55, 56]
def __init__ (self,color):
self.color = color
self.loc = -1
def move(self,numMoves):
# If the gatti is at its start position
if(self.loc < 0 ):
# Gatti needs a 6 to move out from start position
if(numMoves==6):
print("Its a six!")
self.loc+=1
# Do nothing if its not a six
else:
print("Its not a six! Still Stuck!")
#self.loc+=numMoves
# if it is not a six
elif (self.loc + numMoves <= gatti.MAXMOVES):
self.loc = self.loc + numMoves
else:
print("here")
#pass
#inSafeZone=self.isInSafeZone()
class startZone:
allGattis = {
"red": set(),
"blue": set(),
"green": set(),
"yellow": set()
}
def __init__(self,players):
self.players=players
for i in self.allGattis:
pass
#print(self.allGattis[i])
for color in self.players:
for i in range(4):
#print("{}".format(allGattis[colors[color]]))
self.allGattis[colors[color]].add(gatti(color))
#print("{} {}".format(i,k))
def checkOtherGattis(self,gatti):
for color in self.players:
if(color != gatti.color):
for otherGatti in self.allGattis[colors[color]]:
if(otherGatti.loc==gatti.loc):
print(otherGatti.color)
otherGatti.loc=-1
#print("{} {}".format(i,k))
#if(self.players)
import random as random
class ludoWorld:
def __init__(self,numPlayers):
self.players=random.sample(colors.keys(), numPlayers)
print(self.players)
self.startZone = startZone(self.players)
self.turn=self.players.pop()
def decideTurn(self):
self.players.append(self.turn)
self.turn=self.players.pop()
def chooseGattiToPlay(self,gatti):
gatti=gatti()
random.randint(1,4)
def moveGatti(self):
moves=random.randint(1,6)
#moves = 6
self.playerColor = colors[self.turn]
for j in self.startZone.allGattis[colors[self.turn]]:
j.move(moves)
self.startZone.checkOtherGattis(j)
def showGattiStatus(self):
for i in self.startZone.allGattis:
print(i)#len(self.startZone.allGattis[i]))
for j in self.startZone.allGattis[i]:
print(j.loc)
x=ludoWorld(2)
x.moveGatti()
x.showGattiStatus()
# for i, k in enumerate(colors):
# print(k)
# i=random.randint(1,6)
# while (i!=6):
# i=random.randint(1,6)
# print(i)
# red=gatti(0)
# print(red.loc)
# red.move(5)
# print(red.loc)
|
c197f98dffe24c60a2876d694734ffc5dc7c7b6b | kongtianyi/cabbird | /leetcode/find_bottom_left_tree_value.py | 402 | 3.75 | 4 | from structure.treenode import *
def largestValues(root):
res=[0,root.val]
dfs(root,0,res)
return res[1]
def dfs(root,level,res):
if root:
if level>res[0]:
res[0],res[1]=level,root.val
dfs(root.left,level+1,res)
dfs(root.right,level+1,res)
if __name__=="__main__":
root=listToTree([1])
printNode(root)
print largestValues(root)
|
a17970fac69726143fa1d73a8d53004336f1fdf1 | ecdegroot/replace_characters | /replace_characters.py | 669 | 4.40625 | 4 | # https://github.com/ecdegroot/replace_characters
# This python program replaces multiple characters in a word or sentence, example:
# text_input = "Intelligence is the ability to adapt to change"
# text_output = "1N73LL1G3NC3 15 7H3 4B1L17Y 70 4D4P7 70 CH4NG3"
# enter a word or sentence
input_str = input("Type someting: ")
# convert all letters to uppercase
input_str_upper = input_str.upper()
# print output with replaced letters and in uppercase.
print ( input_str_upper
.replace ( 'I', '1' )
.replace ( 'T', '7' )
.replace ( 'E', '3' )
.replace ( 'S', '5' )
.replace ( 'A', '4' )
.replace ( 'O', '0' )
)
|
166798ef28aec224c1a5e52eab49109db501e1d3 | weekenlee/pythoncode | /pra/counter_test.py | 590 | 3.578125 | 4 | import collections
print(collections.Counter(['a', 'b', 'c', 'a']))
print(collections.Counter({'a': 2, 'b': 3, 'c': 1}))
print(collections.Counter(a=2, b=3, c=1))
c = collections.Counter()
print('Initial:', c)
c.update('abcdaab')
print('Sequence:', c)
c.update({'a': 1, 'd': 5})
print('Dict :', c)
for letter in 'abcde':
print('{}: {}'.format(letter, c[letter]))
print(list(c.elements()))
c1 = collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
c2 = collections.Counter('alphabert')
print("math.....")
print(c1)
print(c2)
print(c1+c2)
print(c1-c2)
print(c1 & c2)
print(c1 | c2)
|
3d012edc643328f4aac480a022458eacdd888175 | Zahidsqldba07/HackerRank-Solutions-1 | /python/epeated-string.py | 825 | 3.78125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the repeatedString function below.
def repeatedString(s, n):
acounter = 0
for c in range(len(s)):
if s[c] == 'a':
acounter += 1
acounter = math.floor(n/len(s))*acounter
g = math.floor(n/len(s)) * len(s)
for c in range(len(s)):
if g < n and s[c] == 'a':
acounter += 1
g += 1
# g = 0
# while g <= n:
# for c in range(len(s)):
# if g+c <= n and s[c] == 'a':
# acounter += 1
# g += 1
return acounter
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
n = int(input())
result = repeatedString(s, n)
fptr.write(str(result) + '\n')
fptr.close()
|
b6d502bb47035a59b9ca9ab79f7c571b404b4fe7 | mattheww22/COOP2018 | /Chapter06/U06_Ex_03_Sphere.py | 1,098 | 4.375 | 4 | # U06_Ex_03_MacDonald.py
#
# Author: Matthew Wiggans
# Course: Coding for OOP
# Section: A3
# Date: 14 Dec 2019
# IDE: PyCharm
#
# Assignment Info
# Exercise: 03
# Source: Python Programming
# Chapter: 06
#
# Program Description
#
# This program prints the surface area and volume of a sphere using a given radius
#
# Algorith (pseudocode)
#
# Print introduction
# Get radius from user
# Send radius to getSurface
# Calculate surface area using 4 * 3.14 * r ** 2
# Send radius to getVol
# Calculate volume using 4 / 3 * 3.14 * r ** 2
# Print both using .format
#
from math import *
def main():
print("This program prints the surface area of a sphere")
r = float(input("What is the radius of your sphere? "))
surf = getSurface(r)
print("{0} is the surface area of your sphere.".format(surf))
volume = getVol(r)
print("{0} is the volume of your sphere.".format(volume))
def getSurface(r):
surf = 4 * pi * r ** 2
return surf
def getVol(r):
volume = 4 / 3 * pi * r ** 3
return volume
if __name__ == '__main__':
main()
|
3e46559534cc40ed2a0e86f442517d07eb7efe60 | khromov-heaven/pyBursaGit | /L2/dz2_5.py | 298 | 3.71875 | 4 | def separator(l):
even = []
uneven = []
res = []
for i in l:
if i%2 != 0:
uneven.append(i)
else: even.append(i)
uneven.sort()
even.sort()
even.reverse()
res = uneven + even
print res
print l is res
s = list(input())
separator(s)
|
77603e4a09bf35d2c1354c7d299ef9e3a59a74b5 | yordanovagabriela/HackBulgaria | /week7/website-crawler/histogram.py | 318 | 3.5 | 4 | class Histogram:
def __init__(self):
self.items = {}
def add(self, word):
if word not in self.items:
self.items[word] = 1
else:
self.items[word] += 1
def count(self, word):
return self.items[word]
def get_dict(self):
return self.items
|
3daf851111dd097c7a0d967e5e7b8d4206eb57be | usako1124/teach-yourself-python | /chap11/reserve_call.py | 354 | 3.8125 | 4 | import math
class Coordinate:
def __init__(self, x, y):
self.x = x
self.y = y
# c(x, y)形式で呼び出せ、距離を求める
def __call__(self, o_x, o_y):
return math.sqrt(
(o_x - self.x) ** 2 + (o_y - self.y) ** 2
)
if __name__ == '__main__':
c = Coordinate(10, 20)
print(c(5, 15)) |
9002befb024258a18d693bcf477d404963b02594 | DanielPramatarov/Python-Data-Structures-Implementation | /Stack/Stack.py | 555 | 3.796875 | 4 | class Stack:
def __init__(self):
self.stack = []
def is_empty(self):
return self.stack == []
def push(self, data):
self.stack.append(data)
def pop(self):
if self.size_stack() < 1:
return None
data = self.stack[-1]
del self.stack[-1]
return data
def peek(self):
return self.stack[-1]
def size_stack(self):
return len(self.stack)
st = Stack()
st.push(3212)
st.push(32313)
st.push(1342425654)
st.push(78686)
st.push(99878)
print(st.pop())
|
428e353b8584dc61b1d78eb29be138ebc6d75cc0 | xc21/Leetcode-Practice | /Python/283. Move Zeroes.py | 1,212 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 12 23:18:44 2018
@author: Xun Cao
"""
"""
283. Move Zeroes
Given an array nums, write a function to move all 0's to the end of it
while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
"""
#method 1 -double pointer
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
slow = fast = 0
while fast < len(nums):
if nums[fast] != 0:
if slow != fast:
nums[slow] = nums[fast]
nums[fast] = 0
slow += 1
fast += 1
#method 2
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
nums.sort(key = lambda x: 1 if x == 0 else 0) |
408ba40227c45debbffc114b3c9cf04ebfc61376 | ietuday/python-notes | /variable-ex.py | 721 | 3.78125 | 4 | a = 2
print(a)
b = 9223372036854775807
print(b)
pi = 3.14
print(pi)
c = 'A'
print(c)
name = 'John Doe'
print(name)
q = True
print(q)
x = None
print(x)
print(type(a))
# a, b, c = 1, 2
# print(a, b, c)
# dummy variable can have any name, but it is conventional to use the underscore ( _ ) for assigning unwanted
# values
a,b,_ = 1, 2, 3
print(a,b)
a, b, _ = 1, 2, 3
print(a, b)
# Note that the number of _ and number of remaining values must be equal. Otherwise 'too many values to unpack
# error' is thrown
a = b = c = 1
print(a, b, c)
b = 2
print(a, b,c)
x = y = [7,8,9]
x = [13,8,22]
print(x)
print(y)
x = y = [7, 8, 9]
8, 9]
x[0] = 13
print(y)
x = [1, 2, [3, 4, 5], 6, 7]
print(x[2])
print(x[2][1]) |
b3857a281b98c9fc779661174a034d14f7ed32e1 | xodhx4/webcam_image_recognizer | /train.py | 6,097 | 3.78125 | 4 | """Make CNN model with your dataset
Make your CNN model with your dataset.
This automatically load dataset from directory './train/'.
This model is multi class classification and each folder would be onde class with dir name.
And this automatically augument the dataset with shift, flip, etc.
*Pretrained model is recommended
USAGE :
python train.py train [--pretrained y|n] [--path DATASET_PATH] [--block NUM_BLOCK]
[--BN True|False] [--epoch NUM_EPOCH]
TODO :
[] Load pretrained model
[] Finetune pretrained model
"""
import os
import fire
from datetime import datetime
from util import makepath
class Trainer(object):
def __init__(self, pretrained="y", path=os.path.join(os.getcwd(), "train"), block=3, BN=True):
"""Init option - pretrained, path, block
Args:
pretrained (str): Defaults to "n". Whether use pretrained model or not.
path (string): Defaults to os.path.join(os.getcwd(), "train"). Path of dataset.
block (int): Defaults to 3. Block of CNN, Block is made in 2 CNN layer.
BN (Boolean) : Defaults to True. Whether use batchnormalization or not.
"""
if pretrained == "y" or pretrained == "Y":
self.pretrained = True
elif pretrained == "n" or pretrained == "N":
self.pretrained = False
else:
raise Exception
self.path = path
self._get_datalabel()
self.block = block
self.BN = BN
def _get_datalabel(self):
"""Make label list from dataset
"""
self.labellist = list()
for folder in os.listdir(self.path):
fullpath = os.path.join(self.path, folder)
if os.path.isdir(fullpath):
self.labellist.append(folder)
def _save_label(self, model_name):
"""Save Label data for inference
Args:
model_name (string): Name of model. label data will be saved as "{model_name}.txt"
"""
label = ",".join(self.labellist)
with open(f"{model_name}.txt", "w") as f:
f.write(label)
def new_model(self):
"""Generate CNN model
"""
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dropout
from keras.layers import Dense
from keras.layers import BatchNormalization
model = Sequential()
start_chan = 16
model.add(Conv2D(8, kernel_size=(3, 3),
activation='relu',
input_shape=(64, 64, 3),
padding="same"))
for i in range(self.block):
chan = start_chan*(i+1)
model.add(Conv2D(chan, (3, 3), activation='relu', padding="same"))
model.add(Conv2D(chan, (3, 3), activation='relu', padding="same"))
if self.BN:
model.add(BatchNormalization())
# model.add(MaxPooling2D(pool_size=(2,2)))
# model.add(Dropout(0.2))
model.add(Conv2D(1, (1, 1), activation='relu', padding="same"))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(len(self.labellist), activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.summary()
return model
def pretrained_model(self):
from keras.applications.mobilenet_v2 import MobileNetV2
from keras.layers import Dense
from keras.models import Model
trained_model = MobileNetV2()
trained_model.layers.pop()
added = trained_model.layers[-1].output
added = Dense(128, activation='relu')(added)
pred = Dense(len(self.labellist), activation='softmax')(added)
model = Model(input=trained_model.input, output=pred)
for layer in trained_model.layers:
layer.trainable = False
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.summary()
return model
def _data_generator(self, size=64):
"""Load image from dir, and make augemented dataset
"""
from keras.preprocessing.image import ImageDataGenerator
train_data = ImageDataGenerator(rotation_range=30,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
vertical_flip=True,
validation_split=0.2)
train_generator = train_data.flow_from_directory(
directory=self.path,
target_size=(size, size)
)
return train_generator
def train(self, epoch=10):
"""Train model with early stop
epoch (int, optional): Defaults to 10. Number of epochs
"""
from keras.callbacks import ModelCheckpoint, EarlyStopping
model_name = f"./model/{datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}.h5"
checkpoint = ModelCheckpoint(filepath=model_name,
monitor="loss", verbose=1, save_best_only=True)
early_stop = EarlyStopping(monitor="loss")
makepath('./model')
self._save_label(model_name)
if not self.pretrained:
dataset = self._data_generator()
model = self.new_model()
else :
dataset = self._data_generator(224)
model = self.pretrained_model()
result = model.fit_generator(
dataset,
epochs=epoch,
callbacks=[checkpoint, early_stop]
)
# model.save(model_name)
if __name__ == '__main__':
fire.Fire(Trainer)
|
474bb9e8defc88c9b1888a1fcd93e4e203702314 | max644/advent_of_code | /2018/2.py | 396 | 3.53125 | 4 | from collections import Counter
if __name__ == "__main__":
with open("2.txt", "r") as file:
lines = file.readlines()
lines = [line[:-1] for line in lines]
count2 = 0
count3 = 0
for line in lines:
if len(filter(lambda x: x[1] == 2, Counter(line).items())) > 0:
count2 += 1
if len(filter(lambda x: x[1] == 3, Counter(line).items())) > 0:
count3 += 1
print count2 * count3 |
3e075402bc0190ee5664d2b3e4d19b889b6409ff | kaiwolff/Eng88-cybercourse | /Week_3/Python_OOP/functional_calculator.py | 1,150 | 3.578125 | 4 | from oop_calculator import SimpleCalculator
class FunctionalCalculator(SimpleCalculator):
#add mroe functionality compared to the simple calculator
def __init__(self):
super().__init__()
def inchtocm(self, value1):
return value1 * 2.54
def triangle_area(self, height, width):
return height*width/2
def divisible(self, value1, value2):
if value2 == 0:
return False
elif value1 % value2 == 0:
return True
else:
return False
class SimpleCalculator:
def add(self, value1, value2):
return value1 + value2
def subtract(self, value1, value2):
return value1 - value2
def multiply(self, value1, value2):
return value1 * value2
def divide(self, value1, value2):
return value1 / value2
# my_calc = FunctionalCalculator()
# print(my_calc.add(1,1))
# print(my_calc.subtract(1,1))
# print(my_calc.multiply(1,2))
# print(my_calc.divisible(4,2))
# print(my_calc.divisible(3,2))
# print(my_calc.divisible(3,0))
# print(my_calc.divide(4,2))
# print(my_calc.inchtocm(2))
# print(my_calc.triangle_area(2,2)) |
a3dcbf1cfbe44f9a2d6930d13f83de124a020da4 | huimeizhex/leetcode | /BestTimetoBuyandSellStock.py | 425 | 3.796875 | 4 | #!/usr/bin/env python
# coding=utf-8
class Solution(object):
def max_profit(self, prices):
if len(prices) == 0:
return 0
min_price = prices[0]
res = 0
for price in prices:
res = max(res, price-min_price)
min_price = min(min_price, price)
return res
if __name__ == "__main__":
so = Solution()
num = [2,1]
print so.max_profit(num)
|
78177a2068792738a8f2969f63ccf71ecea694d2 | vivekiitm/IC272-MiniProject | /Batch06/main.py | 204 | 3.859375 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
data = pd.read_csv("group6.csv")
#Checking whether there is any missing value in any column.
print(data.isna().sum())
'''No Missing Values Found'''
|
d57888085c0faae2778b9d3c586dd764946f3156 | kho903/Flask_Oracle | /oracleTest.py | 887 | 3.609375 | 4 | import cx_Oracle as o
def insertTest(name, age, birth):
try:
# sql = "insert into student values('이순신',30,'1999/02/11')"
sql = "insert into student values(:name,:age,:birth)"
dsn = o.makedsn('localhost', '1521', 'xe')
conn = o.connect(user='scott', password='tiger', dsn=dsn)
cur = conn.cursor()
cur.execute(sql, ('임꺽정', 40, '1979/03/01'))
conn.commit()
conn.close()
print("oracle insert")
except Exception as err:
print('err:', err)
try:
sql = "select * from student"
dsn = o.makedsn('localhost', '1521', 'xe')
conn = o.connect(user='scott', password='tiger', dsn=dsn)
cur = conn.cursor()
cur.execute(sql)
data = cur.fetchall()
for n, a, b in data:
print(n, a, b.year, b.month, b.day)
except Exception as err:
print('err:', err)
|
6d1bd469108801a6ab43f34ebd5f2084b636ffdb | brianpattie/byz-generals | /byzgen.py | 6,340 | 3.609375 | 4 | import sys
import threading
import queue
# Nodes of the OrderTree. Implemented as recursive dictionaries.
class OrderNode():
def __init__(self):
self.value = None
self.dict = {}
# Returns the order (a string)
def majority(self):
# Perform majority on all child nodes
for k in self.dict.keys():
self.dict[k].majority()
orders = [self.value]
counts = [1]
for k in self.dict.keys():
o = self.dict[k]
if o.value not in orders:
orders.append(o.value)
counts.append(1)
else:
counts[orders.index(o.value)] += 1
# Return the majority winner, or 'RETREAT' if there's a tie
m = max(counts)
if counts.count(m) == 1:
self.value = orders[counts.index(m)]
else:
self.value = 'RETREAT'
# Must be rewritten as a method of OrderNode
def insert(self, order, order_path):
if len(order_path) == 0:
self.value = order
return
if order_path[0] not in self.dict.keys():
self.dict[order_path[0]] = OrderNode()
self.dict[order_path[0]].insert(order, order_path[1:])
# A tree of OrderNodes. Implemented using recursive dictionaries.
class OrderTree():
def __init__(self):
self.root = OrderNode()
self.num_nodes = 0
# Inserts a node. Invokes the OrderNode's recursive insert() method.
def insert(self, order, order_path):
self.root.insert(order, order_path[1:])
self.num_nodes += 1
# Evaluates the order tree to make a decision. Invokes the OrderNode's recursive majority() method.
def majority(self):
self.root.majority()
return self.root.value
# Message objects are passed between generals on queues.
class Message():
def __init__(self, order, order_path, r_level):
self.order = order
self.order_path = order_path
self.r_level = r_level
def copy(self):
return Message(self.order, self.order_path[:], self.r_level)
def print(self):
print(self.order + " " + str(self.order_path) + " " + str(self.r_level))
# General threads. Thread with id = 0 is the commander and all others are lieutenants.
class General(threading.Thread):
def __init__(self, id, loyal, queues, expected):
threading.Thread.__init__(self)
self.id = id
self.loyal = loyal
self.queues = queues
self.expected = expected
self.ordertree = OrderTree()
def run(self):
# The commander (id = 0) doesn't receive any messages beyond the initial message from the main thread
if self.id == 0:
msg = self.queues[self.id].get()
self.ordertree.insert(msg.order, msg.order_path)
if self.loyal:
self.loyal_relay(msg)
else:
self.traitor_relay(msg)
self.print_action(self.ordertree.majority())
# Lieutenants (id > 0) receive messages from other lieutenants until they have completed their
# recursive order tree. Then they make a decision.
else:
while self.ordertree.num_nodes < self.expected:
msg = self.queues[self.id].get()
self.ordertree.insert(msg.order, msg.order_path)
if msg.r_level > 0:
if self.loyal:
self.loyal_relay(msg)
else:
self.traitor_relay(msg)
self.print_action(self.ordertree.majority())
# Relays the message correctly to the other generals
def loyal_relay(self, msg):
# Copy the message, add yourself to the order's history, decrement the recursion level
new_msg = msg.copy()
new_msg.order_path.append(self.id)
new_msg.r_level -= 1
# Send a copy to every general not in the message's history
for i in range(0, len(queues)):
if i not in new_msg.order_path:
self.queues[i].put(new_msg.copy())
# Relays the message correctly to odd numbered generals and relays the
# opposite to even numbered generals
def traitor_relay(self, msg):
# Copy the message, add yourself to the order's history, decrement the recursion level
loyal_msg = msg.copy()
loyal_msg.order_path.append(self.id)
loyal_msg.r_level -= 1
# Same as above, but also lie about the order
traitor_msg = msg.copy()
traitor_msg.order_path.append(self.id)
traitor_msg.r_level -= 1
traitor_msg.order = self.flip(msg.order)
# Send a copy to every general not in the message's history
for i in range(0, len(queues)):
if i not in loyal_msg.order_path:
if i % 2 == 1:
self.queues[i].put(loyal_msg.copy())
else:
self.queues[i].put(traitor_msg.copy())
def flip(self, order):
if order == 'ATTACK':
return 'RETREAT'
else:
return 'ATTACK'
def print_action(self, action):
if self.loyal:
print("Loyal General " + str(self.id) + " took action " + action)
else:
print("Traitor General " + str(self.id) + " took action " + action)
# Math to determine how many messages each general expects to get total
def expected(n, m):
sum = 0
for i in range(1,m+1):
sum += partial_factorial(n-2, i)
return sum + 1
def partial_factorial(n, m):
product = 1
for i in range(0, m):
product *= n - i
return product
# Main
if len(sys.argv) < 4:
print("Not enough arguments")
exit()
# Parse arguments
gen_str = sys.argv[1]
gen_num = len(sys.argv[1])
order = sys.argv[2]
m = int(sys.argv[3])
expected = expected(gen_num, m)
# Create queues
queues = []
for i in range(0, gen_num):
queues.append(queue.Queue())
# Create generals
generals = []
for i in range(0, len(gen_str)):
generals.append(General(i, gen_str[i] == 'L', queues, expected))
# Start general threads
for g in generals:
g.start()
# Send initial message to commander to get the ball rolling
queues[0].put(Message(order, [], m+1))
# Wait for child threads to finish
for g in generals:
g.join()
|
1436e0e3899ba21b67be2f00be2024c6b9f437ac | rabinshrestha2055/python-training | /week2/factorial.py | 118 | 3.96875 | 4 | def factorial(n):
i = 1
f = 1
while i<=n:
f *= i
i += 1
return f
print(factorial(3))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.