blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
2818ebb1632099c87d7e41850042aafb210caa35 | maleficus1234/School | /COMP452TME1/COMP452TME1/Entities/MouseTarget.py | 478 | 3.65625 | 4 | from pygame import mouse
from Vector import Vector
# Acts a steering behavior target that positions itself using the mouse cursor position
class MouseTarget(object):
# Constructor
def __init__(self):
# Just set an initial value for the target position
self.position = Vector()
# Update the target using current mouse cursor coordinates
def update(self, center):
self.position = center + Vector(mouse.get_pos()[0], mouse.get_pos()[1]) |
03143053a8aa572cec1c1caaf52a1f6d8d1b970f | MarvelousLim/MarvelousHomework | /Lection1/Lection1.py | 509 | 3.578125 | 4 | # for i in range(1, 100):
# if i % 15 == 0:
# print("fizzbuzz")
# elif i % 5 == 0:
# print("buzz")
# elif i % 3 == 0:
# print("fizz")
# else:
# print(i)
#
#
#steps = [(1,0),(-1,0),(0,1),(0,-1)]
#
#def generate_walk(path, L):
# if L == 0:
# print(path)
# else:
# for dx, dy in steps:
# x, y = path[-1]
# pp = path.copy()
# pp.append((x+dx,y+dy))
# generate_walk(pp, L-1)
#
#generate_walk([(0,0)], 1)
|
8ce5a5f4bcc65251ccc4ac8c3603e83af89cab35 | AlehDarashenka/Coursera-Python | /HomeWork/Week1/solution.py | 138 | 3.703125 | 4 | import sys
digit_string = sys.argv[1]
def digit_sum(text):
return sum([int(digit)for digit in text])
print(digit_sum(digit_string)) |
45fd96830ca0719e54c00675aa5b68b84f91873a | brianchiang-tw/leetcode | /No_0171_Excel Sheet Column Number/excel_sheet_column_number_by_recursion.py | 1,085 | 3.78125 | 4 | '''
Description:
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: "A"
Output: 1
Example 2:
Input: "AB"
Output: 28
Example 3:
Input: "ZY"
Output: 701
'''
class Solution:
def titleToNumber(self, s: str) -> int:
if len(s) == 1:
# base case
return ord(s)-64
else:
# general case
return 26*self.titleToNumber( s[:-1] ) + self.titleToNumber( s[-1] )
# n : the length of input string s
## Time Complexity: O( n )
#
# The major overhead in time is the call depth of recursion, which is of O( n ).
## Space Complexity: O( n )
#
# The major overhead in space is to maintain call stack for recursion, which is of O( n ).
def test_bench():
test_data = ['A', 'AB', 'AZ', 'BA','ZY', 'ZZ','AAA']
for s in test_data:
n = Solution().titleToNumber(s)
print(n)
return
if __name__ == '__main__':
test_bench() |
c163d392f676d764e7cb605151d32fff1d463d81 | vitoriabf/FC-Python | /Lista 1/Ex1.py | 816 | 3.953125 | 4 | somaf = 0
somam = 0
contF = 0
contM = 0
maiorSalario = 0
idade = int(input('Digite sua idade: '))
while idade >= 0:
sexo = str(input('Digite seu sexo: '))
salario = int(input('Digite seu salario: '))
if sexo == 'f':
somaf += salario
contF += 1
elif sexo == 'm':
somam += salario
contM += 1
if idade < 30 and salario > maiorSalario:
maiorSalario = salario
idade = int(input('Digite sua idade: '))
if maiorSalario != 0:
print(f'Maior salario de pessoas com menos de 30 anos é {maiorSalario}')
else:
print('Maior salario de pessoas com menos de 30 anos é 0')
if contF != 0:
print(f'A media salarial das mulheres é {somaf/contF}')
if contM != 0:
print(f'A media salarial dos homens é {somam/contM}')
print('Saiu do programa') |
f13ceb4386cb896cb9b812d005e78af16916ff16 | jamespolley/linear-data-structures | /doubly-linked-list/MusicPlayer.py | 5,316 | 3.53125 | 4 | # MusicPlayer Song (Node)
class Song:
def __init__(self, title, artist, duration, next=None, prev=None):
self.title = title
self.artist = artist
self.duration = duration
self.next = next
self.prev = prev
def get_next(self):
return self.next
def set_next(self, song):
self.next = song
def get_prev(self):
return self.prev
def set_prev(self, song):
self.prev = song
def get_title(self):
return self.title
def set_title(self, title):
self.title = title
def get_artist(self):
return self.artist
def set_artit(self, artist):
self.artist = artist
def get_duration(self):
return self.duration
def set_duration(self, duration):
self.duration = duration
def get_all_info(self):
return self.title, self.artist, self.duration
def set_all_info(self, title, artist='Unknown', duration='0:00'):
self.title = title
self.artist = artist
self.duration = duration
def has_next(self):
return self.next != None
# Main MusicPlayer to Hold Songs (Doubly Linked List)
class MusicPlayer:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
self.current_song = None
def play(self):
# Play current song. If None, play head.
if not self.current_song:
self.current_song = self.head
if self.current_song:
print('Playing > {}'.format(
self.current_song.get_title()))
else:
print('No songs in library.')
def next(self):
# Play next song. If at end, play head.
if self.current_song:
next = self.current_song.get_next()
if not next:
self.current_song = self.head
else:
self.current_song = next
self.play()
def prev(self):
# Play previous song. If at beginning, play tail.
if self.current_song:
prev = self.current_song.get_prev()
if not prev:
self.current_song = self.tail
else:
self.current_song = prev
self.play()
def get_current_song(self):
return self.current_song
def get_size(self):
return self.size
def add(self, title, artist='Unknown', duration='0:00'):
# Create new song with next pointer set to MusicPlayer head,
# and previous pointer set to None. Set new song as head.
new_song = Song(title, artist, duration, self.head)
if self.head:
self.head.set_prev(new_song)
else:
self.tail = new_song
self.head = new_song
self.size += 1
def remove(self, title, partial_match=True):
# Set variable for iteration.
this_song = self.head
#
# Iterate until end of MusicPlayer, or target song is found
while this_song is not None:
#
# Check if target title matches this song's title.
is_match = self._is_match(
title, this_song.get_title(), partial_match)
#
# If target has been found, set next pointer of previous
# song to next song, and set previous pointer of next song
# to previous song (which deletes this song). Decrement
# library size.
if is_match:
next = this_song.get_next()
prev = this_song.get_prev()
#
if next:
next.set_prev(prev)
else:
self.tail = prev
#
if prev:
prev.set_next(next)
else:
self.head = next
#
self.size -= 1
#
# Set current song if necessary.
if self.current_song == this_song:
self.current_song = None
# Song successfully removed.
return True
#
# If not found, set variable for next iteration.
else:
this_song = this_song.get_next()
#
# Song not found.
return False
def _is_match(self, target_title, item_title,
partial_match=True):
# Check if target title is part of the item title
# (partial_match=True, default).
if partial_match:
return target_title in item_title
#
# OR, check if target title completely matches item
# title (partial_match=False)
return target_title == item_title
def __repr__(self):
# Combine MusicPlayer song titles, artists, and durations into
# string for display.
this_song = self.head
list_string = 'SONG LIBRARY:\n'
while this_song != None:
title, artist, duration = this_song.get_all_info()
song_string = '{0} | {1} | {2}\n'.format(
title, artist, duration)
list_string += song_string
this_song = this_song.get_next()
return list_string
|
fc60c6adfda960f26b5eea2c9b8c5131e618b61c | JHorlamide/Python-tutorial | /logical operator.py | 410 | 3.71875 | 4 | # has_height_income = False
has_good_credit = True
has_criminal_records = True
# AND: both condition must be true
# if has_good_credit and has_height_income:
# print("AND: Eligible for loan")
# # OR: At least one condition must be true
# if has_good_credit or has_height_income:
# print("OR: Eligible for loan")
# NOT:
if has_good_credit and not has_criminal_records:
print("NOT: Eligible for loan")
|
5b73027472a9931869841bb84232a7bc94b7bbf6 | wmaxlloyd/CodingQuestions | /Dynamic Programming/minimumSum.py | 1,067 | 3.640625 | 4 | # Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
# Note: You can only move either down or right at any point in time.
grid = [
[1,3,1],
[1,5,1],
[4,2,1],
[1,12,3]
]
gridWidth = len(grid[0])
gridHeight = len(grid)
minSumToPoint = [ [0] * gridWidth for i in range(gridHeight) ]
for heightIndex in range(gridHeight):
for colIndex in range(gridWidth):
value = grid[heightIndex][colIndex]
if heightIndex == 0 and colIndex == 0:
minSumToPoint[heightIndex][colIndex] = value
elif heightIndex == 0:
minSumToPoint[heightIndex][colIndex] = value + minSumToPoint[heightIndex][colIndex - 1]
elif colIndex == 0:
minSumToPoint[heightIndex][colIndex] = value + minSumToPoint[heightIndex - 1][colIndex]
else:
minSumToPoint[heightIndex][colIndex] = value + min(minSumToPoint[heightIndex - 1][colIndex], minSumToPoint[heightIndex][colIndex - 1])
print(minSumToPoint[-1][-1]) |
24ab1984e459445711cadf1ecef4c68d464c5568 | alejaksoto/JavaScript | /Poo/python/excersice/2.py | 152 | 3.71875 | 4 | millas = float(1.609344)
kilometros = 1
kilometros = int(input("ingrese cantidad de kilometros"))
print("kilometros en millas"+ str(millas*kilometros))
|
546fa0446e8881e00f854a6628e7a80b3bf80a30 | lackmannicholas/data-structures-and-algorithms | /bfs.py | 1,319 | 3.71875 | 4 | #Uses python3
import sys
import queue
class Graph:
def __init__(self, adj):
self.discovered = queue.Queue()
self.adj = adj
self.visited = [0 for x in range(len(adj))]
self.depth = [-1 for x in range(len(adj))]
self.isBipartite = False
def bfs(self, s):
self.visited[s] = 1
self.depth[s] = 0
self.discovered.put(s)
# while our queue is not empty, keep pulling out nodes
while not self.discovered.empty():
u = self.discovered.get()
for i in self.adj[u]:
if self.depth[i] == -1:
self.depth[i] = self.depth[u] + 1
self.discovered.put(i)
elif self.depth[i] == self.depth[u]:
self.isBipartite = True
def distance(adj, s, t):
graph = Graph(adj)
graph.bfs(s)
return graph.depth[t]
# Coursera scaffolding
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
n, m = data[0:2]
data = data[2:]
edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))
adj = [[] for _ in range(n)]
for (a, b) in edges:
adj[a - 1].append(b - 1)
adj[b - 1].append(a - 1)
s, t = data[2 * m] - 1, data[2 * m + 1] - 1
print(distance(adj, s, t))
|
48ca12657ba2d3752de7225cf6d41165153370d9 | mdujava/PB016 | /2.7_15.py | 3,085 | 3.875 | 4 | class Node:
def __init__(self, val):
self.l = None
self.r = None
self.v = val
def delete(self):
if self.l == self.r == None:
return None
if self.l == None:
return self.r
if self.r == None:
return self.l
child = self.l
grandchild = child.r
if grandchild:
while grandchild.r:
child = grandchild
grandchild = child.r
self.v = grandchild.v
child.r = grandchild.l
else:
self.l = child.l
self.v = child.v
return self
class Tree:
def __init__(self):
self.root = None
def getRoot(self):
return self.root
def add(self, val):
if(self.root == None):
self.root = Node(val)
else:
self._add(val, self.root)
def _add(self, val, node):
if(val < node.v):
if(node.l != None):
self._add(val, node.l)
else:
node.l = Node(val)
else:
if(node.r != None):
self._add(val, node.r)
else:
node.r = Node(val)
def find(self, val):
if(self.root != None):
return self._find(val, self.root)
else:
return None
def _find(self, val, node):
if(val == node.v):
return node
elif(val < node.v and node.l != None):
return self._find(val, node.l)
elif(val > node.v and node.r != None):
return self._find(val, node.r)
def deleteTree(self):
self.root = None
def printTree(self):
if(self.root != None):
self._printTree(self.root, 0)
def _printTree(self, node, rekurzia):
if(node != None):
self._printTree(node.r, rekurzia + 1)
print((" " * rekurzia) + str(node.v) + ' ')
self._printTree(node.l, rekurzia + 1)
def delete(self, value):
if self.root and self.root.v == value:
self.root = self.root.delete()
return
else:
parent = self.root
while parent:
if value < parent.v:
child = parent.l
if child and child.v == value:
parent.l = child.delete()
return
parent = child
else:
child = parent.r
if child and child.v == value:
parent.r = child.delete()
return
parent = child
def main():
print("Príklad na odoberanie uzlu z binárneho stroma:")
tree = Tree()
tree.add(8)
tree.add(3)
tree.add(7)
tree.add(5)
tree.add(2)
tree.add(4)
tree.add(1)
tree.add(6)
tree.add(9)
print("original:")
tree.printTree()
print()
tree.delete(7)
print("odoberieme 7:")
tree.printTree()
print()
if __name__ == '__main__':
main() |
898fa94da6428e44cfb6316ff18a0c3f88ffa7ed | syl0224/algorithm | /sort/quick_sort.py | 861 | 4 | 4 | class QuickSort(object):
@classmethod
def quick_sort(cls, arr, left, right):
if left < right:
index = cls.ajust_arr(arr, left, right)
cls.quick_sort(arr, left, index - 1)
cls.quick_sort(arr, index + 1, right)
return arr
@classmethod
def ajust_arr(cls, arr, left, right):
i = left
j = right
x = arr[i]
while i < j:
while i < j and arr[j] >= x:
j -= 1
if i < j:
arr[i] = arr[j]
i += 1
while i < j and arr[i] <= x:
i += 1
if i < j:
arr[j] = arr[i]
j -= 1
arr[i] = x
return i
if __name__ == "__main__":
arr = [3, 2, 5, 3, 8, 9, 6, 12, 14, 11]
print(QuickSort.quick_sort(arr, 0, len(arr) - 1))
|
0c3f5a072232aaacbdfd0f6dc2076b273f15e82c | Ender-90/python_discrete_math | /python_discrete_math/prime_factoring.py | 1,690 | 4.1875 | 4 | def input_positive_integer():
while True:
try:
int_input = int(input("Input a number: "))
if int_input > 0:
return int_input
break
else:
print("Please input a positive integer!")
except ValueError:
print("Please input a positive integer!")
def display_prime_factors(int_to_factors):
width = 1
while int_to_factors % (10 ** width) != int_to_factors:
width += 1
factor_rest = int_to_factors
while factor_rest != 1:
divisor = 2
for i in range(2, factor_rest + 1):
if factor_rest % i == 0:
divisor = i
break
print("{0:{1}} | {2}".format(factor_rest, width, divisor))
factor_rest //= divisor
print("{0:{1}} |". format(1, width))
def prime_factors_to_list(int_to_factors):
factor_rest = int_to_factors
prime_factor_list = [[0, 0]]
while factor_rest != 1:
divisor = 2
for i in range(2, factor_rest + 1):
if factor_rest % i == 0:
divisor = i
break
factor_rest //= divisor
is_in_list = False
for i in range(0, len(prime_factor_list)):
if prime_factor_list[i][0] == divisor:
is_in_list = True
prime_factor_list[i][1] += 1
break
if not is_in_list:
prime_factor_list.append([divisor, 1])
return prime_factor_list
if __name__ == "__main__":
user_input = input_positive_integer()
print("")
display_prime_factors(user_input)
ls = prime_factors_to_list(user_input)
print(ls)
|
f9f823ffc07dbe9f807a2b26cb094693e3e36d45 | yshshadow/Leetcode | /300-/392.py | 1,663 | 3.90625 | 4 | # Given a string s and a string t, check if s is subsequence of t.
#
# You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).
#
# A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace" is a subsequence of "abcde" while "aec" is not).
#
# Example 1:
# s = "abc", t = "ahbgdc"
#
# Return true.
#
# Example 2:
# s = "axc", t = "ahbgdc"
#
# Return false.
#
# Follow up:
# If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?
import bisect
class Solution(object):
def isSubsequence(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dic = {}
for i, c in enumerate(t):
if c not in dic:
dic[c] = [i]
else:
dic[c].append(i)
pos = 0
for idx, char in enumerate(s):
if char not in dic:
return False
if idx == 0:
pos = dic[char][0]
else:
new = pos
for i in dic[char]:
if i > pos:
new = i
break
if pos == new:
return False
pos = new
return True
s = Solution()
print(s.isSubsequence("acb", "ahbgdc"))
|
b448e065b37232f749099efd2766908d4f3cc7e5 | markjluo/MITOCW6.00.1x | /Week 2/W2_Lecture_Tower of Hanoi Algorithms.py | 606 | 3.765625 | 4 | def printmove(fr, to):
print('Move from', str(fr), 'to', str(to))
# Move stack of discs from one tower (fr) to another tower (to):
# n = the number of towers.
# spare = the spare tower
def Towers(n, fr, to, spare):
if n == 1:
return printmove(fr, to)
else:
# Move all the discs except the largest one to the spare tower
Towers(n-1, fr, spare, to)
# Move the largest disc to the destination
Towers(1, fr, to, spare)
# Move the rest of the discs back on top of the largest one
Towers(n-1, spare, to, fr)
print(Towers(4, 'P1', 'P2', 'P3')) |
634cd85cd75e98d77562544e253fc17ae4c51ccb | Leticiacouti/Python | /tp2/ex25.py | 782 | 4.0625 | 4 | '''
Exercício Fix25
Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu peso (p) ideal,
utilizando as seguintes fórmulas:
Para homens: (72.7*h) - 58
Para mulheres: (62.1*h) - 44.7
'''
#Exercicio 5
print("Letícia Coutinho da Silva - N5752E4 - CC2A41")
print("--------------------------------------------")
print("Calculo do peso ideial de homem e mulher")
print("")
h = float(input("Digite a sua altura: "))
opcao = input("Digite M se você for mulher ou H se você for homem: ").upper()
print("")
if(opcao == 'M'):
resultado = (62.1*h) - 44.7
print("Seu peso ideal é: %2.f"%(resultado))
elif(opcao == "H"):
resultado = (72.7*h) - 58
print("Seu peso ideal é: %2.f"%(resultado))
else:
print("Opção inválida, tente novamente!") |
808dafce1c85fe6dd6ee780c94dc9575873fcea6 | DaveZima/PycharmProjects | /Concurrency/non_locked_threads.py | 1,719 | 3.703125 | 4 | import time
import random
import queue
from threading import Thread
#from concurrent.futures import ThreadPoolExecutor
#from concurrent.futures import ProcessPoolExecutor
COUNTER = 0
# Create the JOB and COUNTER queues
JOB_QUEUE = queue.Queue()
COUNTER_QUEUE = queue.Queue()
""" Runs forever processing counter items in the COUNTER_QUEUE
incremented counter item is put in the PRINT_QUEUE """
def increment_manager():
global COUNTER
while True:
increment = COUNTER_QUEUE.get() # waits for an item
old_counter = COUNTER
COUNTER = old_counter + 1
JOB_QUEUE.put((f"New counter value is {COUNTER}","-------------"))
COUNTER_QUEUE.task_done() # unlocks the queue
""" Runs forever processing print items in the PRINT_QUEUE """
def printer_manager():
while True:
for line in JOB_QUEUE.get():
print(line)
JOB_QUEUE.task_done()
""" Seed the COUNTER_QUEUE """
def increment_counter():
COUNTER_QUEUE.put(1)
def main():
print("*************************************")
print("* Threads Queues with Shared States *")
print("*************************************")
""" Place one in the COUNTER_QUEUE and then use a function to
update the global counter. Use another queue to control the
printing
"""
# Start the COUNTER_QUEUE
Thread(target=increment_manager, daemon=True).start()
# Start the PRINT_QUEUE
Thread(target=printer_manager,daemon=True).start()
# Create 10 threads each containing 1
worker_threads = [Thread(target=increment_counter) for thread in range(10)]
for thread in worker_threads:
thread.start()
for thread in worker_threads:
thread.join()
COUNTER_QUEUE.join()
JOB_QUEUE.join()
##########
# Module #
##########
if __name__ == "__main__":
main()
|
2d16baae9f084d9b0e325361ea801e71b2228149 | sindhumantri/common_algorithms | /kway_merge.py | 695 | 3.515625 | 4 | import heapq
def kway_merge(*iterables):
input_buffer = []
iterators = [iter(iterable) for iterable in iterables]
for index, iterator in enumerate(iterators):
heapq.heappush(input_buffer, (iterator.next(), index))
while input_buffer:
value, index = heapq.heappop(input_buffer)
yield value
next_value = iterators[index].next()
if next_value is not None:
heapq.heappush(input_buffer, (next_value, index))
def main():
a = [1, 5, 9, 13]
b = [2, 6, 10, 14]
c = [1, 1, 2, 3, 5, 8, 13]
args = [a, b, c]
print a
print b
print c
print list(kway_merge(*args))
if __name__ == "__main__":
main()
|
de5d6271d81c95b1f134326fc0a568e9db2e701c | vikashkshatra/morse_code | /morse.py | 1,174 | 3.734375 | 4 |
from playsound import playsound
import time
codes = {
"A": ".-",
"B": "-...",
"C": "-.-.",
"D": "-..",
"E": ".",
"F": "..-.",
"G": "--.",
"H": "....",
"I": "..",
"J": ".---",
"K": "-.-",
"L": ".-..",
"M": "--",
"N": "-.",
"O": "---",
"P": ".--.",
"Q": "--.-",
"R": ".-.",
"S": "...",
"T": "-",
"U": "..-",
"V": "...-",
"W": ".--",
"X": "-..-",
"Y": "-.--",
"Z": "--..",
" ": "/"
}
phrase = input("Enter your phrase: \n")
# convert a string to morse code
morse_code = ""
for word in phrase:
for i, j in zip(codes.keys(), codes.values()):
if word.upper() == i:
morse_code = morse_code + j
break
print(morse_code)
print("PLAYING SOUND")
# play sound beeep
for word in phrase:
for i, j in zip(codes.keys(), codes.values()):
dots = 0
if word.upper() == i :
for beep in j:
if beep == ".":
dots += 1
playsound("beep.wav")
else:
time.sleep(0.2)
|
e6132a41ee3324b68d6ca3e7c18592b0c8a7a4a2 | MukulKirtiVerma/Python_Excercise | /12. Python_Dictionary.py | 2,460 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 13 15:14:10 2018
@author: sky
"""
#creating dictionary
dict1={}
dict1={1:2,3:4,5:6}
dict2 = {2: [1,2,3], 'Age': 7, 'Class': 'First'}
#print value
print ( dict2['Age'])
print ("dict['Age']: ", dict2['Age'])
dict2 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict2['Name'])
#error when access wrong key
dict2 = {'Name': 'Zara', 'Age': 7, 2:'two','Class': 'First'}
print ("dict['Alice']: ", dict2['Alice'])
#Updating Dictionary
dict2 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict2['Age'] = 8; # update existing entry
dict2['School'] = "DPS School"; # Add new entry
print ("dict['Age']: ", dict2['age'])
print ("dict['School']: ", dict2['School'])
#deletion
dict2 = {'Name': 'Zara', 'Age': 7, 'Class': 'First','Name':'ABC'}
del dict2['Name']; # remove entry with key 'Name'
dict2.clear(); # remove all entries in dict
del dict2 ; # delete entire dictionary
print( "dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
#dictionary can not access by index
dict2[0]
#functionMethods
dict2 = {'Name': 'Zara', 'Age': 7};
len(dict2)
i=list(dict2.keys())
i=list(i)
i=dict2.values()
i=list(i)
seq = ('name', 'age', 'sex')
dict1 = dict.fromkeys(seq)
dict1 = dict.fromkeys(seq, 10)
seq=[(1,2),(2,3),(3,4)]
dict(seq)
#in python 2.7
dict2 = {'Name': 'Zabra', 'Age': 7}
dict2['Name']
x=dict2.get(('Name','Age'))
dict2 = {'Name': 'Zara', 'Age': 7}
print(dict2.has_key('Age'))
print("Value : %s" % dict.has_key('Sex'))
dict.setdefault
dict2 = {'Name': 'Zara', 'Age': 7}
dict2.items()
[('Name','Zara'),('Age',7)]
i=str(dict2)
dict2 = {'Name': 'Zara'}
dict2.setdefault()('Age', None)
dict2.setdefault('Sex', None)
print(dict2['Age'])
dict1 = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex' : 'female' ,1:2}
s
dict1.update(dict2)
x=dict1+dict2
dict2 = {'Name': 'Zara', 'Age': 7}
dict2.values()
dict = {'Name': 'Zara', 'Age': 7};
#datatype conversion
x=2
x=2.0
x="asd"
x="abc","asd"
x=2+3j
x=True
#only this can be converted into dict
x=[(1,2),(3,5)]
x=(1,2,3)
print(dict(x))
str(dict2)
#some methods
dict2.pop()
x=dict2.pop('Name')
x=dict1.popitem()
i=[(1,2),(3,3)]
i=dict1.sort()#not define
i=dict(i)
max(dict2)
min(dict2)
#dictionary iteration
dict2={1:2,3:5,5:6}
for i in dict2:
print(i,dict2[i])
|
f1e8462cb95a2a134f9600913cff3e9ca771de8a | leonardo111003/infosatc-lp-avaliativo-01 | /exercicio22.py | 101 | 3.5625 | 4 | jardas = float ( input ( "Insira o valor em jardas:" ))
metros = jardas * 0,91
print ( metros ) |
ac2a04f3490af8bf8c8c56107232a53c59fa49a7 | ppmorgoun/dspt11_3.1.1 | /mymodule/reddit.py | 1,775 | 3.671875 | 4 | admin = "petr"
class Post:
def __init__(self, up_votes, down_votes, user, body):
self.up_votes = up_votes
self.down_votes = down_votes
self.user = user
self.body = body
class User:
def __init__(self, name, karma, is_moderator=False):
"""
Create a User object
------------
name : str
Returns
"""
self.name = name
self.karma = karma
self.is_moderator = is_moderator
self.topics = []
self.comments = []
print(f'New user created:\nName = {self.name}\nKarma = {self.karma}')
def post_topic(self, title, body):
"""
Post a topic with the user as the author and the given title and body
------------
title : str
Returns
--------
Topic
"""
topic = Topic(title=title, user=self, body=body)
self.topics.append(topic)
return topic
def post_comment(self, topic, body):
comment = Comment(topic=topic, body=body, user=self)
self.comments.append(comment)
return comment
"""
Argument post is expected to be either a mymodule.reddit.Topic object or mymodule.reddit.Comment
"""
def up_vote(self, post: Post):
post.up_votes += 1
class Topic(Post):
def __init__(self, title, user, body, up_votes=1, down_votes=0):
self.title = title
super(Topic, self).__init__(up_votes=up_votes, down_votes=down_votes, user=user, body=body)
class Comment(Post):
def __init__(self, topic, body, user, up_votes=1, down_votes=0):
self.topic = topic
super(Comment, self).__init__(up_votes=up_votes, down_votes=down_votes, user=user, body=body)
|
b9303d5c4dbb81760e70563ed9572ef880e463f4 | ccmiller214/python_api_class | /tryExcept.py | 363 | 3.859375 | 4 | #!/usr/bin/python3
## Loop until works
while True:
try:
## Pull info from the local user
name = input('Enter a file name: ')
with open(name,'w') as myfile:
myfile.write('Well done\n')
except:
print('Error in creating that file...try again!')
else:
print('File created successfully!')
break
|
b54896e1374239a7f6ac66c3987ab4475a3262b2 | alistairpott/intaka | /docbuilder.py | 3,346 | 3.78125 | 4 | class DocBuilder:
"""A class for construcing documents ready to be converted to ebooks."""
def __init__(self, title, filename='output'):
"""Setup the document builder using input parameters
title = The title out the output document
filename = Optional filename of the output document. Defaults to output
"""
self.title = title
self.filename = filename
self.has_toc = False
self.has_cover = False
#list to hold all the articles in the document
self.articles = []
def output_all_files(self):
"""Goes through the steps to create the output files."""
self.buildTableOfContents()
self.buildOPF()
self.buildOutput()
def set_cover(self, cover_filename):
"""Sets the cover of the output document"""
self.cover_filename = cover_filename
self.has_cover = True
def add_article(self, html, toc_label):
"""Adds an article to the DocBuilder.
html = the HTML content of the article
toc_label = the label of this article in the Table of Contents
"""
#create an anchor automatically
toc_anchor = 'anchor%i' % len(self.articles)
self.articles.append({'toc_label':toc_label, 'toc_anchor':toc_anchor, 'html':html})
def buildTableOfContents(self, title='Table of Contents'):
"""Outputs the Table of Contents to a file"""
fout = open('toc.html','w')
fout.write('<html><head><title>%s</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body>' % title)
fout.write('<h1>%s</h1>' % title)
#actually write the output file
for item in self.articles:
fout.write(u'<p><a href="%s.html#%s">%s</a></p>' % (self.filename, item['toc_anchor'], item['toc_label']))
self.has_toc = True
fout.write('</body></html>')
fout.close()
def buildOPF(self):
"""Builds the output OPF file."""
#get the template for the OPF
fin = open('template.opf','r')
opf_output = fin.read()
fin.close()
#update the placeholders in the template
opf_output = opf_output.replace('{TITLE}', self.title)
opf_output = opf_output.replace('{FILENAME}', self.filename)
if self.has_cover:
opf_output = opf_output.replace('{COVER}', '<EmbeddedCover>%s</EmbeddedCover>' % self.cover_filename)
else:
opf_output = opf_output.replace('{COVER}', '')
#write the output file
fout = open('%s.opf' % self.filename, 'w')
fout.write(opf_output)
fout.close()
def buildOutput(self):
"""Builds the output HTML file with the document contents."""
fout = open('%s.html' % self.filename, 'w')
fout.write('<html><head><title>%s</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body>' % self.title)
for item in self.articles:
fout.write('<a name="%s"></a>' % item['toc_anchor'])
fout.write(item['html'])
fout.write('<mbp:pagebreak/>')
fout.write('</body></html>')
fout.close()
|
4faed6f5261879ded97652d712bb6863ddfe73f9 | TianyaoHua/LeetCodeSolutions | /Unique Binary Search Trees.py | 753 | 3.78125 | 4 | # Definition for a binary tree node.
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n < 1:
return []
table = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
table[i][i] = 1
for l in range(1, n):
for i in range(n-l):
j = i + l
c = 0
for k in range(i+1, j):
c += table[i][k-1]*table[k+1][j]
c += table[i+1][j]
c += table[i][j-1]
table[i][j] = c
return table[0][n-1]
if __name__ == "__main__":
solution = Solution()
print(solution.generateTrees(10))
|
8b9e4443eb0106157f79d42c0c45be2a3f7d03a7 | lusifer65/algorithms | /Python3/TowerOfHanoi.py | 541 | 3.765625 | 4 | i=0
def towerOfHanoi(disks, source, auxiliary, target):
global i
if disks == 1:
print("Move disk 1 from tower {} to tower {}.".format(source, target))
i+=1
return
towerOfHanoi(disks - 1, source, target, auxiliary)
print("Move disk {} from tower {} to tower {}.".format(disks, source, target))
i+=1
towerOfHanoi(disks - 1, auxiliary, source, target)
disks = int(input('Enter number of disks: \n'))
towerOfHanoi(disks, 'A', 'B', 'C')
print("Total number of steps required are {}".format(i)) |
dace2c927744f4c001540a8a42f56caba8829748 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/hrrbha001/question1.py | 261 | 4.1875 | 4 | def palindrome (s):
if len(s) < 2:
return True
elif s[0] == s[-1]:
return palindrome (s[1:-1])
else:
return False
str = input ("Enter a string:\n")
if (palindrome (str)):
print ("Palindrome!")
else:
print ("Not a palindrome!") |
2d1f3698a1a6520972dd29420e3ae41638cd406a | rrnewton/MandelMicrobench | /mandel_test.py | 262 | 3.5625 | 4 |
def mandel(depth, c):
count = 0
z = complex(0,0)
while (True):
if (count == depth): break
if (abs(z) >= 2.0): break
z = z*z + c;
count += 1
return count
print(mandel(5 * 1000 * 1000, complex(0.1,0.1)));
|
39e4a5e2921dc91327c123da6266655b52b73476 | lixingyangok/learn-python-01 | /00-li-note/01-data-type.py | 430 | 4 | 4 | """
数据类型检测方法
● type(18) # <class 'int'>
● isinstance(18, int) # True
"""
name = 'Tom'
number = 18
print('name的数据类型:', type(name))
print('number的数据类型:', type(number))
typeStr = type(1)
print('type()返回的值,类型是:', type(typeStr))
print('■'*20)
print('查看18是不是整型:', isinstance(18, int))
print('查看18是不是浮点型:', isinstance(18, float))
|
98d11ec72760ae2f6e8b790c1ede327480847f71 | LorenzoChavez/CodingBat-Exercises | /List-1/rotate_left3.py | 302 | 4.25 | 4 | # Given an array of ints length 3, return an array with the elements "rotated left" so {1, 2, 3} yields {2, 3, 1}.
def rotate_left3(nums):
rotated = []
iternums = iter(nums)
next(iternums)
for num in iternums:
rotated.append(num)
rotated.append(nums[0])
return rotated
|
041c74b7c351d8939c717001e933c32d1eaf9f20 | bapata/PYTHON | /sigma_and_pi.py | 820 | 3.9375 | 4 | #!/usr/bin/python
#
## Script to calculate summation and factorial of N
# ./sigma_and_pi.py 10
# Summation of 10 is 55
# Factorial of 10 is 3628800
#
import sys,os
def sum_upto_n(n):
return 0 if (n<0) else n + sum_upto_n(n-1)
def product_upto_n(n):
return 1 if (n<=0) else n * product_upto_n(n - 1)
#
## main starts here
#
def usage():
# program name
myscriptname=os.path.basename(__file__)
print "USAGE: " + myscriptname + " <integer>"
exit(1)
def main(argv):
argc=len(argv)
# ARGV[1] = program name
# ARGV[2] = N
if(argc!=2):
usage()
number=int(argv[1])
print "Summation of " + str(number) + " is " + str(sum_upto_n(number))
print "Factorial of " + str(number) + " is " + str(product_upto_n(number))
if __name__ == "__main__":
main(sys.argv)
|
63d6c812471c0bbab60850089ce64e53041e33c6 | decodingjourney/BeginnerToExpertInPython | /ForLoopInPython/ForLoops.py | 1,751 | 3.828125 | 4 | # for i in range(1, 12):
# print("Value of i now is {0} " .format(i))
#
#
# number = "9,123,234,345,456,567,678,789"
# for i in range(0, len(number)):
# print(number[i], end='')
#
# number = "9,123,234,345,456,567,678,789"
# print()
# cleanedNumber = ''
# for i in range(0, len(number)):
# if number[i] in '0123456':
# cleanedNumber = cleanedNumber + number[i]
#
# newNumber = int(cleanedNumber)
# print("The new number is {} " .format(newNumber))
# number = "9,123,234,345,456,567,678,789"
# cleanedNumber = ''
#
# for char in number:
# if char in '123456789':
# cleanedNumber = cleanedNumber + char
# newNumber = int(cleanedNumber)
# print("The new number is {}" .format(newNumber))
# for state in ["Rajasthan", "Madhya Pradesh", "Chhattishgadh"]:
# print("BJP lost in " +state)
# for i in range(2, 21):
# for j in range(1, 11):
# print("{0} * {1} = {2} " .format(i, j, i*j))
# print("#############")
# quote = """
# Alright, but apart from the Sanitation, the Medicine, Education, Wine,
# Public Order, Irrigation, Roads, the Fresh-Water System,
# and Public Health, what have the Romans ever done for us?
# """
#
# # Use a for loop and an if statement to print just the capitals in the quote above.
# # for i in range(len(quote)):
# # if quote[i] in "ASMEWPOIRFH":
# # print(quote[i], end='')
#
# sentence = ''
# for char in quote:
# if char in 'ASMEWPOIRFH':
# sentence = sentence + char
#
# print("the sentence is " +sentence)
# for i in range(0,101):
# if (i % 7) == 0:
# print(i, end='')
number = 5
multiplier = 8
answer = 0
# add your loop after this comment
for i in range(multiplier):
answer += number;
print(answer)
|
8c8a46f26b65ca5eaa9b20567d4b731d42591e7f | chanyoonzhu/leetcode-python | /529-Minesweeper.py | 1,982 | 3.578125 | 4 | class Solution:
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
"""
time exceeded, not know why
r, c = click
if board[r][c] == 'M':
board[r][c] == 'X'
return board
elif board[r][c] == 'E':
revealed = set([])
q = [(r, c)]
while q:
rThis, cThis = q.pop()
revealed.add((r, c))
adjacentMines = 0
temp = []
for i, j in [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]:
if 0 <= rThis+i < len(board) and 0 <= cThis+j < len(board[0]):
if board[rThis+i][cThis+j] == 'M':
adjacentMines += 1
if (rThis+i,cThis+j) not in revealed:
temp.append((rThis+i,cThis+j))
if not adjacentMines:
board[rThis][cThis] = 'B'
q.extend(temp)
else:
board[rThis][cThis] = str(adjacentMines)
return board
"""
stack = [(click[0],click[1])]
visited = set([])
while stack != []:
x,y = stack.pop()
visited.add((x,y))
if board[x][y] == 'M':
board[x][y] = 'X'
else:
temp = []
count = 0
for i,j in [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]:
if 0<=x+i<len(board) and 0<=y+j<len(board[0]):
if board[x+i][y+j]=='M':
count += 1
if (x+i,y+j) not in visited:
temp.append((x+i,y+j))
if count == 0:
board[x][y] = 'B'
stack += temp
else:
board[x][y] = str(count)
return board |
e57b4bd468b823b0171c84b3afd783138e6deb93 | sankleta/glowing-funicular | /counting_letters.py | 415 | 3.84375 | 4 | from math import floor
snippet = input()
string_length = int(input())
def count_as(snippet):
a_in_snippet = 0
for letter in snippet:
if letter == "a":
a_in_snippet += 1
return a_in_snippet
a_in_snippet = count_as(snippet)
snippet_len = len(snippet)
answer = floor(string_length / snippet_len) * a_in_snippet + count_as(snippet[:(string_length % snippet_len)])
print(answer)
|
e3ae4778793da0c685767852ac434fd0060aad2a | talhaHavadar/daily-scripts-4-fat-lazy | /programming_questions/honeycomb.py | 1,743 | 3.78125 | 4 | """
Problem B
A bee larva living in a hexagonal cell of a large honeycomb decides to creep for a walk.
In each “step” the larva may move into any of the six adjacent cells and after n steps,
it is to end up in its original cell. Your program has to compute,
for a given n, the number of different such larva walks.
"""
hive = []
def create_hive():
return [[[-1 for z in range(15)] for x in range(40)] for y in range(40)]
def is_already_known_path(pos_x, pos_y, remaining_steps):
if hive[pos_x][pos_y][remaining_steps] is not -1:
return True
return False
def get_successful_walk_count(pos_x, pos_y, remaining_steps):
return hive[pos_x][pos_y][remaining_steps]
def travel(pos_x, pos_y, remaining_steps):
if is_already_known_path(pos_x, pos_y, remaining_steps):
return get_successful_walk_count(pos_x, pos_y, remaining_steps)
if remaining_steps == 0:
return 1 if pos_x == 20 and pos_y == 20 else 0
walk_count = 0
walk_count += travel(pos_x, pos_y - 1, remaining_steps - 1)
walk_count += travel(pos_x, pos_y + 1, remaining_steps - 1)
walk_count += travel(pos_x + 1, pos_y - 1, remaining_steps - 1)
walk_count += travel(pos_x - 1, pos_y + 1, remaining_steps - 1)
walk_count += travel(pos_x - 1, pos_y, remaining_steps - 1)
walk_count += travel(pos_x + 1, pos_y, remaining_steps - 1)
hive[pos_x][pos_y][remaining_steps] = walk_count
return walk_count
def main(test_case):
global hive
hive = create_hive()
steps = []
for i in range(test_case):
steps.append(int(input()))
for n in steps:
print(travel(20, 20, n))
if __name__ == '__main__':
test_case = int(input())
main(test_case)
|
ae27fbdbb628c9a53757a92df386e965c06515d8 | inshelligent/5023-OOP-scenarios | /shapes/shapes.py | 553 | 3.8125 | 4 | import math
class Rectangle:
def __init__(self, length: float, width: float):
self.length = length
self.width = width
def calculate_area(self):
return self.length * self.width
def calculate_perimeter(self):
return (self.length * 2) + (self.width * 2)
class Circle:
def __init__(self, radius: float):
self.radius = radius
def calculate_area(self):
return (self.radius * self.radius) * math.pi
def calculate_circumference(self):
return 2 * self.radius * math.pi |
729445df3f10dc2041a663e296c7163fd500fade | angelahe/python | /mail.py | 690 | 3.875 | 4 | #make a function called email
#received 2 parameters: first name and last name
#e.g. Larry Shumlich => [email protected]
#e.g. Heiko Peters => [email protected]
#write an automated test that will check the results are what you expect
#email the test to Larry before you write the code
def make_email(first="", last=""):
#[email protected]
email = None
lastname = last.lower()
firstname = first.lower()
#if first.len() == 0 and last.len() == 0
if len(first) > 0:
if len(last) > 0:
email = firstname+'.'+lastname+'@evolveu.ca'
else:
email = firstname+'@evolveu.ca'
else:
if len(last) > 0:
email = lastname+'@evolveu.ca'
return email
|
72dadbc72fcd14a0d5e6dc24ba9d19d9478804d8 | rawfighter/List | /Untitled-2.py | 226 | 3.890625 | 4 | # Conceptos condicionales y loops
print("Dame una palabra")
palabra = input()
print("Dame un numero")
numero = int(input())
if numero == 1:
print(len(palabra))
else:
for index in range(numero):
print(palabra) |
677926014c172190bafdbe242dd0c3de7cd54370 | pratham-singh-data/Python-Examples | /letter_counter.py | 1,367 | 4.03125 | 4 | def seperator():
for i in range(100):
print("*", end = '')
print()
def count_instances(string, letter):
step = len(letter)
choice = input("Enter \'y\' if cases are to be considered: ")
if choice == 'y':
pass
else:
string = string.lower()
letter = letter.lower()
curr = 0
count = 0
while curr + step <= len(string):
op_string = string[curr: curr + step]
curr += step
if op_string == letter:
count += 1
return count
def letter_counter():
string = input("Please enter the string that is to be operated on=>\n")
letter = input("Please enter letter whose total instances are to be found: ")
if letter in string:
count = count_instances(string, letter)
print(f"There are {count} instances of \'{letter}\' in given string")
else:
print(f"Sorry \'{letter}\' is not in the given string")
seperator()
def greet():
name = input('What is your name:')
print(f'Hello {name.title()}')
seperator()
print("This is a letter counter; here we will tell you how many instances of a certain charachter there is in a string")
print()
if __name__ == '__main__':
greet()
letter_counter() |
99d028d3bd9a9f0eead2449d1c565ec582a2effa | durgadevi68/guvi | /digit.py | 110 | 3.828125 | 4 | n=int(input())
if((n%2)==0):
while((n%2)==0):
n=n/2
print(int(n))
else:
print(n)
|
602108b433ca3a7d5772f0341272f5b385ab87d5 | takisforgit/Projects-2017-2018 | /binary-tree-ex1.py | 3,668 | 4.28125 | 4 | """
https://medium.freecodecamp.org/all-you-need-to-know-about-tree-data-structures-bceacb85490c
"""
from queue import Queue
class BinaryTree:
def __init__(self, value):
self.value = value
self.left_child = None
self.right_child = None
def insert_left(self, value):
if self.left_child == None:
self.left_child = BinaryTree(value)
else:
new_node = BinaryTree(value)
self.left_child = new_node
new_node.left_child = self.left_child
def insert_right(self, value):
if self.right_child == None:
self.right_child = BinaryTree(value)
else:
new_node = BinaryTree(value)
self.right_child = new_node
new_node.right_child = self.right_child
### When we go deep to the leaf and backtrack, this is called DFS algorithm.
### types of DFS: pre-order, in-order, and post-order
### in_order & pre_oreder are opposite in the linked article !!! ###
def in_order(self):
print(self.value, end=" ")
if self.left_child:
self.left_child.in_order()
if self.right_child:
self.right_child.in_order()
def pre_order(self):
if self.left_child:
self.left_child.pre_order()
print(self.value, end=" ")
if self.right_child:
self.right_child.pre_order()
def post_order(self):
if self.left_child:
self.left_child.post_order()
if self.right_child:
self.right_child.post_order()
print(self.value, end=" ")
def bfs(self):
queue = Queue()
queue.put(self)
while not queue.empty():
current_node = queue.get()
print(current_node.value, end=" ")
if current_node.left_child:
queue.put(current_node.left_child)
if current_node.right_child:
queue.put(current_node.right_child)
############################################################################
## 1st example
# tree = BinaryTree('a')
# print(tree.value) # a
# print(tree.left_child) # None
# print(tree.right_child) # None
#####
## 2nd example - Add nodes
# a_node = BinaryTree('a')
# a_node.insert_left('b')
# b_node = a_node.left_child
# print(b_node, a_node.left_child )
# a_node.insert_right('c')
# c_node = a_node.right_child
# print("Node {}: Left is {}, Right is {}.".format(a_node.value, a_node.left_child.value, a_node.right_child.value))
# b_node.insert_right('d')
# d_node = b_node.right_child
# print("Node {}: Right is {}".format(b_node.value,b_node.right_child.value))
# b_node.insert_right('g')
# g_node = b_node.right_child
# print("Node {}: Right is {}".format(g_node.value,g_node.right_child.value))
# c_node.insert_left('e')
# e_node = c_node.left_child
# c_node.insert_right('f')
# f_node = c_node.right_child
# print("Node {}: Left is {}, Right is {}.".format(c_node.value, c_node.left_child.value, c_node.right_child.value))
# print("Node values:",a_node.value,b_node.value,c_node.value, d_node.value,e_node.value,f_node.value)
### New Binary tree
node1 = BinaryTree('1')
node1.insert_left('2')
node1.insert_right('5')
node2 = node1.left_child
node5 = node1.right_child
node2.insert_left('3')
node2.insert_right('4')
node3 = node2.left_child
node3 = node2.right_child
node5.insert_left('6')
node5.insert_right('7')
node6 = node5.left_child
node7 = node5.right_child
print("\n3 types of DFS traversal\n")
print("In order:" , end=" ")
node1.in_order()
print()
print("Pre order", end=" ")
node1.pre_order()
print()
print("Post order", end=" ")
node1.post_order()
print()
print("\nBFS traversal:", end=" ")
node1.bfs()
print("\n") |
ec4fa4a4fc87c44ead62cae94878e5715256dac2 | beOk91/code_up | /code_up1073.py | 133 | 3.5625 | 4 | value_list = input().split()
i=0
while True:
if value_list[i]!="0":
print(value_list[i])
else:
break
i+=1 |
b85118c72bdb579fb446115e828c8fe3ddb2313e | havenshi/leetcode | /465. Optimal Account Balancing.py | 3,301 | 3.609375 | 4 | # A group of friends went on holiday and sometimes lent each other money. For example, Alice paid for Bill's lunch for 10.ThenlaterChrisgaveAlice10.ThenlaterChrisgaveAlice5 for a taxi ride. We can model each transaction as a tuple (x, y, z) which means person x gave person y $z. Assuming Alice, Bill, and Chris are person 0, 1, and 2 respectively (0, 1, 2 are the person's ID), the transactions can be represented as [[0, 1, 10], [2, 0, 5]].
#
# Given a list of transactions between a group of people, return the minimum number of transactions required to settle the debt.
#
# Note:
# A transaction will be given as a tuple (x, y, z). Note that x ≠ y and z > 0.
# Person's IDs may not be linear, e.g. we could have the persons 0, 1, 2 or we could also have the persons 0, 2, 6.
#
# Example 1:
#
# Input:
# [[0,1,10], [2,0,5]]
#
# Output:
# 2
#
# Explanation:
# Person #0 gave person #1 $10.
# Person #2 gave person #0 $5.
#
# Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each.
#
# Example 2:
#
# Input:
# [[0,1,10], [1,0,1], [1,2,5], [2,0,5]]
#
# Output:
# 1
#
# Explanation:
# Person #0 gave person #1 $10.
# Person #1 gave person #0 $1.
# Person #1 gave person #2 $5.
# Person #2 gave person #0 $5.
#
# Therefore, person #1 only need to give person #0 $4, and all debt is settled.
#
# 这道题给了一堆某人欠某人多少钱这样的账单,问我们经过优化后最少还剩几个。其实就相当于一堆人出去玩,
# 某些人可能帮另一些人垫付过花费,最后结算总花费的时候可能你欠着别人的钱,其他人可能也欠你的欠。
# 我们需要找出简单的方法把所有欠账都还清就行了。这道题的思路跟之前那道Evaluate Division有些像,
# 都需要对一组数据颠倒顺序处理。我们使用一个哈希表来建立每个人和其账户的映射,其中账户若为正数,说明其他人欠你钱;
# 如果账户为负数,说明你欠别人钱。我们对于每份账单,前面的人就在哈希表中减去钱数,后面的人在哈希表中加上钱数。
# 这样我们每个人就都有一个账户了,然后我们接下来要做的就是合并账户,看最少需要多少次汇款。我们先统计出账户值不为0的人数,
# 因为如果为0了,表明你既不欠别人钱,别人也不欠你钱,如果不为0,我们把钱数放入一个数组accnt中,然后调用递归函数。
# 在递归函数中,我们初始化结果res为整型最大值,然后我们跳过为0的账户,然后我们开始遍历之后的账户,
# 如果当前账户和之前账户的钱数正负不同的话,我们将前一个账户的钱数加到当前账户上,这很好理解,比如前一个账户钱数是-5,
# 表示张三欠了别人五块钱,当前账户钱数是5,表示某人欠了李四五块钱,那么张三给李四五块,这两人的账户就都清零了。
# 然后我们调用递归函数,此时从当前改变过的账户开始找,num表示当前的转账数,需要加1,
# 然后我们用这个递归函数返回的结果来更新res,后面别忘了复原当前账户的值。遍历结束后,我们看res的值如果还是整型的最大值,
# 说明没有改变过,我们返回num,否则返回res即可 |
4d825ad1dc634a990587db1bed9bbec9d8bc26fa | Avani1992/python | /chapter19_TypesofInheritance/Multiple.py | 1,016 | 4.28125 | 4 | # class Parent:
# def m1(self):
# print("Parent class")
#
# class Child:
# def m2(self):
# print("Child class")
#
# class Child1(Parent,Child):
# def m3(self):
# print("Child1 class")
#
# c=Child1()
# c.m1()
# c.m2()
# c.m3()
#2. Both class same method. First come First Serve
#
# class Parent:
# def m1(self):
# print("Parent class")
#
# class Child:
# def m1(self):
# print("Child class")
#
# class Child1(Parent,Child):
# def m3(self):
# print("Child1 class")
#
# c=Child1()
# c.m1()
# c.m1()
# c.m3()
# o/p:
# Parent class
# Parent class
# Child1 class
#3.
#
# class Parent:
# def m1(self):
# print("Parent class")
#
# class Child:
# def m1(self):
# print("Child class")
#
# class Child1(Child,Parent):
# def m3(self):
# print("Child1 class")
#
# c=Child1()
# c.m1()
# c.m1()
# c.m3()
#
# o/p:
# Child class
# Child class
# Child1 class |
a5468337ee495a87432bb468d2e9285ae32d9895 | sinhars/Data-Structures-And-Algorithms | /Course1/Week3/5_covering_segments.py | 792 | 3.625 | 4 | # Uses python3
import sys
from collections import namedtuple
from numpy.core.fromnumeric import sort
Segment = namedtuple('Segment', 'start end')
def optimal_points(segments):
points = []
sorted_segments = sorted(segments , key=lambda x: x.start, reverse=False)
while len(sorted_segments) > 0:
min_end = min([x.end for x in sorted_segments])
while (len(sorted_segments) > 0) and (sorted_segments[0].start <= min_end):
sorted_segments.pop(0)
points.append(min_end)
return points
if __name__ == '__main__':
input = sys.stdin.read()
n, *data = map(int, input.split())
segments = list(map(lambda x: Segment(x[0], x[1]), zip(data[::2], data[1::2])))
points = optimal_points(segments)
print(len(points))
print(*points)
|
971d2c8a7f57b4787f65fbd01acc7fbaef0eca0e | valerii2020/valerii2020 | /starter/lesson 2/Mariia Horb/task 3.py | 214 | 3.84375 | 4 | a=input("целое число a")
a = int(a)
b=input("целое число b")
b = int(b)
c=input("целое число c")
c = int(c)
sqrt=(b**2-4*a*c)**0.5
x1=(-b+sqrt)/2*a
x2=(-b-sqrt)/2*a
print(x1)
print(x2) |
9167320a70295970059c9001e352d41c596812a3 | leksiam/PythonCourse | /Practice/S.Mikheev/return_maximum.py | 472 | 4.15625 | 4 | def maximum(a, b):
return a if a > b else b
# если a == b, то в любом случае будет выведено максимальное число
a = int(input('enter the first integer: '))
b = int(input('enter the second integer: '))
print('The maximum number is {}'.format(maximum(a, b)))
# можно использовать float вместо int для того,
# чтобы сравнивать числа с плавающей точкой |
24cd789f6ed4252264f86c06b103eda5fe69280c | Bawya1098/python-Beginner | /Day 2/Functions.py | 284 | 3.78125 | 4 | def sum_num(number1, number2):
print(number1 + number2)
return number1 + number2
print(sum_num((2, 2)))
print((print("hi")))
# print(input("enter the number"))
print("1,2,3,4,5,6")
print(1, "a,b")
print(type(1.0))
print(type('hi'))
print(type('print'))
print(type(print()))
|
2d4d64a610c994f914248468f90d50f121c9630a | zantelope/code_Signal_42_BishopAndPawn | /bishopAndPawn.py | 682 | 3.921875 | 4 | def bishopAndPawn(b, p):
## change input values into integers that corerspond to their position on a chessboard
## ord() function changes input to a string representing it's ascii value
## change both values to ints
b = [int(ord(b[0]) - 96), int(b[1])]
p = [int(ord(p[0]) - 96), int(p[1])]
## if x values are equal to zero, return False (cannot divide by 0)
if p[0] - b[0] == 0:
return False
## absolute value of the slope (y2 - y1 / x2 - x1) will be equal to 1 if pawn is on bishop's potential paths
if abs((p[1] - b[1]) / (p[0] - b[0])) == 1:
return True
## if slope is not 1, return false
else:
return False
|
4d97ce5458e1087470ae9ce052f143b5b47e8da3 | abjordan/mazes-for-programmers | /cell.py | 1,885 | 3.640625 | 4 | #!/usr/bin/env python
from distances import Distances
class Cell:
row = None
column = None
my_links = None
(north, south, east, west) = (None, None, None, None)
def __init__(self, r, c):
self.row = r
self.column = c
self.my_links = {}
def link(self, cell, bidi=True):
self.my_links[cell] = True
if bidi:
cell.link(self, False)
return self
def unlink(self, cell, bidi=True):
self.my_links.remove(cell)
if bidi:
cell.unlink(self, false)
return self
def links(self):
return self.my_links.keys()
def is_linked(self, cell):
return self.my_links.get(cell, False)
def neighbors(self):
ret = []
if self.north: ret += self.north
if self.south: ret += self.south
if self.east: ret += self.east
if self.west: ret += self.west
return ret
def distances(self):
distances = Distances(self)
frontier = [ self ]
while len(frontier) is not 0:
new_frontier = []
for cell in frontier:
for linked in cell.links():
if linked in distances.keys():
continue
distances[linked] = distances[cell] + 1
new_frontier.append(linked)
frontier = new_frontier
return distances
def __str__(self):
ret = "Cell at ({}, {}), linked to {} neighbors".format(
self.row, self.column, len(self.my_links))
return ret
if __name__=="__main__":
c = Cell(0, 0)
d = Cell(0, 1)
e = Cell(0, 2)
c.link(d)
d.link(e)
print("C: " + str(c))
print("D: " + str(d))
print("E: " + str(e))
c_dist = c.distances()
for key in c_dist.keys():
print(key, c_dist[key])
|
7da5f00f0c3da1c42e4a3afcf7127ed5ca902e98 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2339/60760/271002.py | 363 | 3.546875 | 4 | def func(arr:list):
cou=0
for i in range(len(arr)):
for j in range(len(arr)):
if j>i and arr[j]<arr[i]:
cou=cou+1
return cou
tests=int(input())
lists=[]
for i in range(tests):
l=input()
lists.append(list(map(int,input().split(" "))))
res=[]
for i in lists:
res.append(func(i))
for i in res:
print(i) |
76728ef97952517799bb36df97b7f7239bdbcb3f | CreativeBusyBee/Hadoop | /MongoDB/for_loop.py | 143 | 4.03125 | 4 |
fruit =['apple','pears','mango','kiwi']
new_fruit =[]
for item in fruit:
print item
new_fruit.append(item)
print new_fruit
|
2f8bdab3b4235bed31cceed640737785766ba103 | arbansal/16Puzzle-and-DrivingDirectionsSearch | /part1/solver16.py | 6,807 | 3.59375 | 4 | #!/usr/bin/env python
# solver16.py : Circular 16 Puzzle solver
# Based on skeleton code by D. Crandall, September 2018
# This code has been constructed based on the structure given by Dr. David Crandall
# We have constructed two heuristic fnctions:
# a) Number of misplaced tiles
# b) Circular manhattan distance
# Based on the observations obtained by running the code on the Indiana Burrow server,
# the code solves board 2 to board6 within 2 seoonds and board 8 in 10-15 seconds while board 12 takes around 25+ minutes.
from Queue import PriorityQueue
from random import randrange, sample
import sys
import string
# shift a specified row left (1) or right (-1)
def shift_row(state, row, dir):
change_row = state[(row * 4):(row * 4 + 4)]
return (state[:(row * 4)] + change_row[-dir:] + change_row[:-dir] + state[(row * 4 + 4):],
("L" if dir == -1 else "R") + str(row + 1))
# shift a specified col up (1) or down (-1)
def shift_col(state, col, dir):
change_col = state[col::4]
s = list(state)
s[col::4] = change_col[-dir:] + change_col[:-dir]
return (tuple(s), ("U" if dir == -1 else "D") + str(col + 1))
# print board state
def print_board(row):
for j in range(0, 16, 4):
print '%3d %3d %3d %3d' % (row[j:(j + 4)])
#Using number of misplaced tiles as heuristic.
#Here in this method we are comparing our board with the goal board (which is obtained by sorting in ascending order)
# Each element in our state is compared with the corresponding element in the goal state. If there is a match then
# we increment count by 1. The total number of misplaced elements are obtained by subtracting count from 16.
# This heuristic does not seem to work beyond board 4.
def heuristic1(state):
goal = sorted(state)
arr = []
count = 0
for i in state:
arr.append(i)
for i in range(0, 16):
if arr[i] == goal[i]:
count += 1
misplaced = 16 - count
return misplaced
# Using Manhattan Distance
#Here in this method we are calculating the circular manhattan distance. So for our reference and ease we
# have visualized a single list as two-dimensional matrix with both x-value and y-value. The goal state is otained
# sorting the intial state in ascending order. The x-value and y-value of both the goal state and the successor state is
#obtained by mapping the single list to the dictionary of coordinates. The key of the dictionary denotes the index position of
#single list while its value denotes the x and y positions.
def heuristic2(state):
goal = sorted(state)
#https://stackoverflow.com/questions/16318757/calculating-manhattan-distance-in-python-in-an-8-puzzle-game
coordinates = {0: (0, 0), 1: (0, 1), 2: (0, 2), 3: (0, 3),
4: (1, 0), 5: (1, 1), 6: (1, 2), 7: (1, 3),
8: (2, 0), 9: (2, 1), 10: (2, 2), 11: (2, 3),
12: (3, 0), 13: (3, 1), 14: (3, 2), 15: (3, 3)}
# We will be calculating the circular manhattan distance using the below function and use it for our heuristic calculation
# Comparing the position of the current element against its location in the desired goal state
# x and y value of both the goal state and current successor state is obtained by
#mapping the values from the list of dictionary.
manhattanDist = 0
for i in range(0, 16):
element = state[i]
pos = goal.index(element)
xvalue, yvalue = coordinates[i]
xgoal, ygoal = coordinates[pos]
#following if and else conditions takes care of the borderline cases
#The first if loop compares first row elements and last row elements to the corresponding elements in the goal state.
#If the difference of x coordinates in goal state and intial state is 3 then we are comparing first and last row elements
#and in addition, if x coordinate is equal to y coordinate of goal state and vice versa then we are comparing the top right most and bottom
#left most elements of board, thereby increasing the distance by +2. Else we are calculating the simple manhattan distance.
if ((xvalue == 0 and xgoal == 3) or (xvalue == 3 and xgoal == 0)):
if (xvalue == ygoal) and (yvalue == xgoal):
manhattanDist += 2
elif ((xvalue == 0 and xgoal == 3) and (yvalue == 0 and ygoal == 3)):
manhattanDist += 2
else:
manhattanDist += (1 + abs(yvalue - ygoal))
elif ((yvalue == 0 and ygoal == 3) or (yvalue == 3 and ygoal == 0)):
manhattanDist += (1 + abs(xvalue - xgoal))
else:
manhattanDist += (abs(xvalue - xgoal) + abs(yvalue - ygoal))
return float(manhattanDist) / 4
# return a list of possible successor states
been_state = []
def successors1(state):
successor = []
for i in range(0, 4):
for d in (-1, 1):
successor.append(shift_row(state, i, d))
for i in range(0, 4):
for d in (-1, 1):
successor.append(shift_col(state, i, d))
# Here we attempted to eliminate duplicate states from entering the fringe so as to optiimize and reduce the time taken by board 12,
# however we have commented this part because our board 8 did not seem to work.
# for success in been_state:
# for success1 in successor:
# if (success == success1[0]):
# successor.remove(success1)
#
# for success in successor:
# been_state.append(success)
return successor
# just reverse the direction of a move name, i.e. U3 -> D3
def reverse_move(state):
return state.translate(string.maketrans("UDLR", "DURL"))
# check if we've reached the goal
def is_goal(state):
return sorted(state) == list(state)
# Here we have taken a priority queue so that the state with the minimum manhattan ditance + distance
# from the initial state is always popped from the list first.
def solve(initial_board):
a = PriorityQueue()
a.put((0, (initial_board, "")))
while not (a.empty()):
(p, (state, route_so_far)) = a.get()
for (succ, move) in successors1(state):
if is_goal(succ):
return (route_so_far + " " + move)
l = len(route_so_far.split())
a.put((heuristic2(state) + l, (succ, route_so_far + " " + move)))
return False
# inputting the board from the command line.
filename=(sys.argv[1])
start_state = []
with open(filename, 'r') as file:
for line in file:
start_state += [int(i) for i in line.split()]
if len(start_state) != 16:
print "Error: couldn't parse start state file"
print "Start state: "
print_board(tuple(start_state))
print "Solving..."
route = solve(tuple(start_state))
print "Solution found in " + str(len(route) / 3) + " moves:" + "\n" + route |
3a0bbb07d325f3d66d116bfe5398ca25d6465325 | syurskyi/Python_Topics | /079_high_performance/exercises/template/Writing High Performance Python/item_25.py | 2,534 | 3.828125 | 4 | import logging
from pprint import pprint
from sys import stdout as STDOUT
# Example 1
class MyBaseClass(object):
def __init__(self, value):
self.value = value
class MyChildClass(MyBaseClass):
def __init__(self):
MyBaseClass.__init__(self, 5)
def times_two(self):
return self.value * 2
foo = MyChildClass()
print(foo.times_two())
# Example 2
class TimesTwo(object):
def __init__(self):
self.value *= 2
class PlusFive(object):
def __init__(self):
self.value += 5
# Example 3
class OneWay(MyBaseClass, TimesTwo, PlusFive):
def __init__(self, value):
MyBaseClass.__init__(self, value)
TimesTwo.__init__(self)
PlusFive.__init__(self)
# Example 4
foo = OneWay(5)
print('First ordering is (5 * 2) + 5 =', foo.value)
# Example 5
class AnotherWay(MyBaseClass, PlusFive, TimesTwo):
def __init__(self, value):
MyBaseClass.__init__(self, value)
TimesTwo.__init__(self)
PlusFive.__init__(self)
# Example 6
bar = AnotherWay(5)
print('Second ordering still is', bar.value)
# Example 7
class TimesFive(MyBaseClass):
def __init__(self, value):
MyBaseClass.__init__(self, value)
self.value *= 5
class PlusTwo(MyBaseClass):
def __init__(self, value):
MyBaseClass.__init__(self, value)
self.value += 2
# Example 8
class ThisWay(TimesFive, PlusTwo):
def __init__(self, value):
TimesFive.__init__(self, value)
PlusTwo.__init__(self, value)
foo = ThisWay(5)
print('Should be (5 * 5) + 2 = 27 but is', foo.value)
# Example 11
# This is pretending to be Python 2 but it's not
class MyBaseClass(object):
def __init__(self, value):
self.value = value
class TimesFiveCorrect(MyBaseClass):
def __init__(self, value):
super(TimesFiveCorrect, self).__init__(value)
self.value *= 5
class PlusTwoCorrect(MyBaseClass):
def __init__(self, value):
super(PlusTwoCorrect, self).__init__(value)
self.value += 2
class GoodWay(TimesFiveCorrect, PlusTwoCorrect):
def __init__(self, value):
super(GoodWay, self).__init__(value)
before_pprint = pprint
pprint(GoodWay.mro())
from pprint import pprint
pprint(GoodWay.mro())
pprint = pprint
# Example 12
class Explicit(MyBaseClass):
def __init__(self, value):
super(__class__, self).__init__(value * 2)
class Implicit(MyBaseClass):
def __init__(self, value):
super().__init__(value * 2)
assert Explicit(10).value == Implicit(10).value
|
60429d2e22d1e78c958fa563a6e79b0b270fc6ba | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 1 - Fizzbuzz NUKE.py | 594 | 4.375 | 4 | # Question: Write a program that prints the integers from 1 to 100.
# But for multiples of three print "Fizz" instead of the number, and for the multiples of five print "Buzz".
# For numbers which are multiples of both three and five print "FizzBuzz".
# Solution:
c_ Solution:
___ Fizzbuzz(x,z):
___ i __ r..(x,z):
__ i % 3 __ 0 a.. i % 5 __ 0:
print ("FizzBuzz")
____ i % 3 __ 0:
print ("Fizz")
____ i % 5 __ 0:
print ("Buzz")
____:
print (i)
Solution.Fizzbuzz(1,100) |
8d7034d80b93bad52eb970ca538ccbdcfa687631 | KimhabCoding/python-w3school | /exercise/0.basic.py | 238 | 3.609375 | 4 | print('Hello My Crush')
print('---*** I Love Programming do much ***---')
# This a comment line in python
print("I am so happy today")
print('Error with Semi colon'); # Error when you end with semi colon
print("Do you love your crush")
|
579da09835d8da0a67e21fffceb677f95addc605 | a-angeliev/Python-Fundamentals-SoftUni | /Text Processing - Exercise/01. Valid Usernames.py | 465 | 3.734375 | 4 | data = input().split(", ")
flag = True
for i in range(len(data)):
current_username = data[i]
if 3<= len(current_username)<= 16:
for i in current_username:
if not i.isdigit():
if not i.isalpha():
if not i == '-':
if not i =="_":
flag = False
break
if flag:
print(current_username)
flag = True
|
226b0cf4e30c4d4ba425dddf1b405ad70c3a5552 | EstebanMongui/challenge-python-02 | /src/main.py | 1,953 | 3.8125 | 4 | # Resolve the problem!!
import string
import random
SYMBOLS = list('!"#$%&\'()*+,-./:;?@[]^_`{|}~')
def generate_password():
# Start coding here
letters_min = 'azxjclptuopwkfr'
letters_may = letters_min.upper()
symbols = SYMBOLS
password_list = []
len_password = random.randint(2,4)
for num in range(len_password):
number = random.randint(0,9)
password_list.append(str(number))
for letter in range(len_password):
password_list.append(random.choice(letters_min))
for letter in range(len_password):
password_list.append(random.choice(letters_may))
for symbol in range(len_password):
password_list.append(random.choice(symbols))
random.shuffle(password_list,random.random)
password = ''.join(password_list)
print (password)
print ('# chars = ',len(password))
return password
def validate(password):
if len(password) >= 8 and len(password) <= 16:
has_lowercase_letters = False
has_numbers = False
has_uppercase_letters = False
has_symbols = False
for char in password:
if char in string.ascii_lowercase:
has_lowercase_letters = True
break
for char in password:
if char in string.ascii_uppercase:
has_uppercase_letters = True
break
for char in password:
if char in string.digits:
has_numbers = True
break
for char in password:
if char in SYMBOLS:
has_symbols = True
break
if has_symbols and has_numbers and has_lowercase_letters and has_uppercase_letters:
return True
return False
def run():
password = generate_password()
if validate(password):
print('Secure Password')
else:
print('Insecure Password')
if __name__ == '__main__':
run()
|
ddff13866d5787128ededa6b2d2b238e2eae8f58 | songszw/python | /python小栗子/t50.py | 314 | 3.71875 | 4 | def fab(n):
n1=1
n2=1
n3=1
if n<1:
print('wrong number')
return -1
while (n-2)>0:
n3=n1+n2
n1=n2
n2=n3
n-=1
return n3
result = fab(20)
if result != -1:
print('总共有%d对小兔崽子诞生'% result)
|
6e85eb241306588efac5cf453ae848c71795668b | montlebalm/euler | /python/problems/problem15.py | 711 | 3.609375 | 4 | """
Question:
Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?
Answer:
137846528820
"""
from helpers.timer import print_timing
from math import factorial
@print_timing
def problem15(sides):
"""
Finding the number of combinations can be expressed as the factorial of the
number of sides times two divided by the factorial of sides then squared
For sides = 20
40!
-------
20! ^ 2
"""
divisor = factorial(sides * 2)
dividend = factorial(sides) ** 2
return int(divisor / dividend)
if __name__ == "__main__":
print(problem15(20))
|
7ef2218f6a47a3f89c2e551afe6c432e317aac6c | joonluvschipotle/baekjoon | /9498.py | 133 | 3.796875 | 4 | a = int(input())
if a > 89: print ("A")
elif a > 79: print ("B")
elif a > 69: print ("C")
elif a > 59: print ("D")
else: print ("F")
|
8309c119891bf3afee64eb8ad5243895e04f8df5 | brycejh/Py-practice | /myfile.py | 249 | 3.875 | 4 | anymal = input("Please type your favorite animal: ")
if anymal != "Dogs":
print("Wrong, your favorite animal is Dogs")
else:
doggo = input("What kind of dog? ")
if doggo != "Husky":
print("Dummy")
else:
print("Good")
|
297a90e0b2703f5d25f3e3624d3d55f6883a2f53 | Tritium13/Bioinformatik | /Python etc/counting_nucleotides.py | 578 | 3.71875 | 4 | # counting nucleotides in DNA sequence
seq = str(input("DNA-sequence: "))
n = len(seq) - 1
count_A = 0
count_T = 0
count_C = 0
count_G = 0
while n >= 0:
if seq[n] == 'A':
count_A += 1
n = n - 1
elif seq[n] == 'T':
count_T += 1
n = n - 1
elif seq[n] == 'C':
count_C += 1
n = n - 1
elif seq[n] == 'G':
count_G += 1
n = n - 1
else:
print("Abbruch! Fehlerhafte Eingabe")
break
print(count_A, count_C, count_G, count_T) |
de8fac63e0fde33298699a964c23a55e9660daf7 | EricOuma/IEEEXtremePractice | /AeneasCryptoDisc/aeneas.py | 990 | 3.78125 | 4 | #!usr/bin/python3
import re
import math
def work(filename):
angles = {}
with open(filename) as f:
radius = float(f.readline())
for _ in range(26):
# k is letter, v is angle
k, v = f.readline().split(' ')
angles[k.lower()] = float(v)
message = f.readline()
cleaned_message = re.sub(r'[^a-zA-Z]', '', message.lower())
string_length = 0
previous = cleaned_message[0]
for count, letter in enumerate(cleaned_message[1:]):
if letter == previous:
continue
diff_one = abs(angles[letter] - angles[previous])
diff_two = 360 - diff_one
temp = min(diff_one, diff_two)
string_length += (2 * radius * math.sin(math.radians(temp)/2.0))
print(letter, temp, string_length)
previous = letter
result = int(math.ceil(string_length + radius))
with open("output.txt", 'a') as output:
output.write(str(result))
work("input.txt") |
01d58a97bfd3cac742b4dd50bedcc2a7b04712f5 | ThaliaVillalobos/code2040 | /Step3.py | 878 | 3.5625 | 4 | import urllib2
import requests
import json
def main():
#requsting information from API
payload = {'token':'', 'needle':'', 'haystack': ''}
data= requests.post("http://challenge.code2040.org/api/haystack", params = payload)
#To view the information
#print(data.text)
#Coverting JSON string into Python dictionary
dictionary = json.loads(data.text)
#Split the dictionay into needle(target) and haystack(list of value)
needle = dictionary["needle"]
haystack = dictionary["haystack"]
#Getting the index where the needle is located
index = haystack.index(needle)
#Checking needle, haystack, and index
#print(needle)
#print(haystack)
#print(index)
#Posting my results
load = {'token':'', 'needle':index}
requests.post("http://challenge.code2040.org/api/haystack/validate", params =load)
main()
|
85d94d9b888b8266ce62aae31c9c7b3d8c49695c | Success2014/Leetcode | /numberOf1Bits.py | 1,479 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 14 15:36:12 2015
Write a function that takes an unsigned integer and returns the number of
’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation
00000000000000000000000000001011, so the function should return 3.
Tags: Bit Manipulation
Similar Problems (E) Reverse Bits (E) Power of Two
Brute force solution:
Iterate 32 times, each time determining if the ith bit is a ‘1’ or not.
This is probably the easiest solution, and the interviewer would probably
not be too happy about it. This solution is also machine dependent
(You need to be sure that an unsigned integer is 32-bit).
In addition, this solution is not very efficient too, as you need to
iterate 32 times no matter what.
Best solution:
Hint: Remember my last post about making use x & (x-1) to determine if an
integer is a power of two? Well, there are even better uses for that!
Remember every time you perform the operation x & (x-1), a
single 1 bit is erased?
@author: Neo
"""
class Solution:
# @param n, an integer
# @return an integer
def hammingWeight(self, n):
count = 0
while n != 0:
n = n & (n - 1)
count += 1
return count
def hammingWeightBF(self, n):
count = 0
while n:
count += n & 1
n >>= 1
return count
sol = Solution()
print sol.hammingWeightBF(11) |
75d573873cf2fc3fb4509a365f12f207959d9941 | kfahad5607/Library-management-system | /lms.py | 2,965 | 4.25 | 4 | class Library:
def __init__(self, libraryname, listofbooks):
self.libraryname = libraryname
self.listofbooks = listofbooks
self.lentbooksinfo = {}
def printlentbooksinfo(self):
if bool(self.lentbooksinfo) == False:
print('No book has been lent currently.')
else:
for book, user in self.lentbooksinfo.items():
print(f'{book} has been lent to {user}.')
def addbook(self, book):
self.listofbooks.append(book)
print("Book has been added to the book list.")
def displaybooks(self):
print(f"We have following books in our library: {self.libraryname}")
for book in self.listofbooks:
print(book)
def lendbook(self, person, book):
if book in self.listofbooks:
self.listofbooks.remove(book)
self.lentbooksinfo.update({book: person})
print("Lender-Book database has been updated. You can take the book now.")
elif book in self.lentbooksinfo.keys():
print(
f'{book} is not available right now. It has been lent to {self.lentbooksinfo[book]}')
else:
print(f"Sorry, We do not have '{book}'.")
self.displaybooks()
def returnbook(self, book):
if book in self.lentbooksinfo:
self.addbook(book)
self.lentbooksinfo.pop(book)
print("Book has been returned to the library.")
else:
print(f"'{book}'' does not belong to the library.")
if __name__ == "__main__":
fahadliblist = ['Python', 'Rich Daddy Poor Daddy',
'Harry Potter', 'C++ Basics', 'Algorithms by CLRS']
fahadlib = Library('Imperial Library', fahadliblist)
while True:
print('\n')
print(
f"Welcome to the {fahadlib.libraryname}. Enter your choice to continue")
print('1. To display all the books.')
print('2. To add a book.')
print('3. To lend a book.')
print('4. To return a book.')
print('5. Information about lent books.')
print('6. Quit.')
inp = int(input('\n'))
if inp not in [1, 2, 3, 4, 5, 6]:
print("Please enter a valid option")
continue
elif inp == 1:
fahadlib.displaybooks()
elif inp == 2:
print('Enter the name of the book:')
book = input()
fahadlib.addbook(book)
elif inp == 3:
print('Enter the name of person:')
person = input()
print('Enter the name of the book:')
book = input()
fahadlib.lendbook(person, book)
elif inp == 4:
print('Enter the name of the book:')
book = input()
fahadlib.returnbook(book)
elif inp == 5:
fahadlib.printlentbooksinfo()
elif inp == 6:
exit()
else:
print('Unexpexted input!')
|
3af51321a5e8cfa7f75ff8898713152e13fb660d | bootphon/word-count-estimator | /wce/word_count_estimation/rttm_processing.py | 4,803 | 3.53125 | 4 | """Rttm processing
Module to extract segments of speech from the original wavs by reading its
related .rttm file and gather the results of the WCE on the segments that come
from the same audio.
The module contains the following functions:
* extract_speech - extract speech for one file.
* extract_speech_from_dir - extract speech for files in a directory.
* retrieve_word_counts - write the gathered results per file to a .csv file.
"""
import os, sys, glob
import csv
import subprocess
import shutil
import numpy as np
def extract_speech(audio_file, rttm_file, chunks_dir):
"""
Extract speech segments from an audio file.
Parameters
----------
audio_file : str
Path to the audio file.
rttm_file : str
Path to the corresponding rttm file.
chunks_dir : str
Path to the directory where to store the resulting wav chunks.
Returns
-------
wav_list : list
List of the .wav files corresponding to the speech segments.
onsets :
List of the onsets of the speech segments.
offsets :
List of the offsets of the speech segments.
"""
wav_list = []
onsets = []
offsets = []
try:
with open(rttm_file, 'r') as rttm:
i = 0
for line in rttm:
# Replace tabulations by spaces
fields = line.replace('\t', ' ')
# Remove several successive spaces
fields = ' '.join(fields.split())
fields = fields.split(' ')
onset, duration, activity = float(fields[3]), float(fields[4]), fields[7]
if activity == 'speech':
basename = os.path.basename(audio_file).split('.wav')[0]
output = os.path.join(chunks_dir, '_'.join([basename, str(i)])+'.wav')
cmd = ['sox', audio_file, output,
'trim', str(onset), str(duration)]
subprocess.call(cmd)
wav_list.append(output)
onsets.append(onset)
offsets.append(onset+duration)
i += 1
except IOError:
shutil.rmtree(chunks_dir)
sys.exit("Issue when extracting speech segments from wav.")
onsets = np.array(onsets)
offsets = np.array(offsets)
return wav_list, onsets, offsets
def extract_speech_from_dir(audio_dir, rttm_dir, sad_name):
"""
Extract speech for files in a directory.
Parameters
----------
audio_dir : str
Path to the directory containing the audio files (.wav).
rttm_dir : str
Path to the directory containing the SAD files (.rttm).
sad_name : str
Name of the SAD algorithm used.
Returns
-------
wav_list : list
List containing the path to the wav segments resulting from the trim.
"""
wav_list = []
audio_files = glob.glob(audio_dir + "/*.wav")
if not audio_files:
sys.exit(("speech_extractor.py : No audio files found in {}".format(audio_dir)))
chunks_dir = os.path.join(audio_dir, "wav_chunks_predict")
if not os.path.exists(chunks_dir):
os.mkdir(chunks_dir)
else:
shutil.rmtree(chunks_dir)
os.mkdir(chunks_dir)
for audio_file in audio_files:
rttm_filename = "{}_{}.rttm".format(sad_name, os.path.basename(audio_file)[:-4])
rttm_file = os.path.join(rttm_dir, rttm_filename)
if not os.path.isfile(rttm_file):
sys.exit("The SAD file %s has not been found." % rttm_file)
wav_list.append(extract_speech(audio_file, rttm_file, chunks_dir)[0])
wav_list = np.concatenate(wav_list)
return wav_list
def retrieve_files_word_counts(word_counts, wav_chunks_list, output_path):
"""
Retrieve the word count for each file from the wav chunks' word counts.
Parameters
----------
word_counts : list
List of the word counts per wav chunk.
wav_chunks_list : list
List of paths to the wav chunks.
output_path : str
Path to the output_path file where to store the results.
"""
files = []
files_word_counts = []
for f in wav_chunks_list:
filepath = '_'.join(f.split('_')[:-1])
filename = os.path.basename(filepath)
if filename not in files:
files.append(filename)
for f in files:
indices = [x for x, y in enumerate(wav_chunks_list) if f in y]
wc = 0
for i in indices:
wc += word_counts[i]
files_word_counts.append((f, wc))
with open(output_path, 'w') as out:
csvwriter = csv.writer(out, delimiter=';')
for row in files_word_counts:
csvwriter.writerow(row)
print("Output saved at: {}.".format(output_path))
|
3c6fc8bd0b5f86dfa9bb339a4d9c73e61cd19605 | TimeIsOut/workplace | /Solutions/6kyu/Unique in Order.py | 280 | 3.609375 | 4 | def unique_in_order(iterable):
if not iterable: return []
check = iterable[0]
answer = [iterable[0]]
for i in iterable[1:]:
if i != check:
check = i
answer += [i]
if check != iterable[-1]:
answer += [i]
return answer |
dbb300001d54649b48fea252ce963091042baddb | green-fox-academy/ilcsikbalazs | /week-03/day-3/17exercise.py | 261 | 3.625 | 4 | from tkinter import *
root = Tk()
canvas = Canvas(root, width='300', height='300')
canvas.pack()
def lines(x,y,x1,y1):
line = canvas.create_line(x,y,x1,y1,fill="green")
return line
for i in range(150,301,15):
lines(300,i,i,150)
root.mainloop()
|
3162988778dfc6144027b48476ca1240ff5d673f | madnanit/molssi-tapia-camp | /geometry_analysis_2.py | 1,315 | 3.703125 | 4 | import os
import numpy
def calculate_distance(coords1,coords2):
# this function has two parameters. It returns the distance b/w atoms.
"""
this function has two parameters. It returns the distance b/w atoms.
"""
x_distance = coords1[0] - coords2[0]
y_distance = coords1[1] - coords2[1]
z_distance = coords1[2] - coords2[2]
xy_distance = numpy.sqrt(x_distance**2 + y_distance**2 + z_distance**2)
return xy_distance
def bond_check2(blength, minimum=0, maxmimum=1.5):
if blength > minimum and blength < maxmimum:
return True
else:
return False
# a function that checks the distance within a range and returns whether it is true or false
# it is based on the distance and we can define the min and max and their default value as well
position_file = os.path.join('water.xyz')
positions = numpy.genfromtxt(fname=position_file, dtype='unicode', skip_header=2)
atoms = positions[:,0]
data = positions[:,1:]
data = data.astype(numpy.float)
atom_num = len(atoms)
for atm1 in range(0,atom_num):
for atm2 in range(0, atom_num):
if atm2 > atm1:
xy_distance = calculate_distance(data[atm1], data[atm2])
if bond_check2(xy_distance, maxmimum=2) is True:
print(F'{atoms[atm1]} to {atoms[atm2]} = {xy_distance:.3f}')
|
d5573caf7a665c1459145e07187e013ab50aec21 | Tymotheus/Ensimag-Python | /2_Iterations/4_Kaleidoscope/dessin.py | 762 | 3.859375 | 4 | """
File making a drawing? Generation of SVG file?
"""
import random
import triangle
def entete(width, height):
"""
Generates header of svg File
"""
print("<svg height=\""+str(height)+"\" width=\"" + str(width)+ "\">" )
def couleur_aleatoire():
"""
Returns SVG colour code (?)
"""
return((random.randint(0,255), random.randint(0,255), random.randint(0,255)))
def affiche_triangle(tri, colour):
"""
Prints svg-like triangle - returning code on output
"""
print("<polygon points=\"",end="")
for v in tri.vertices:
print(str(v.x) + "," + str(v.y), end=" ")
print("\" fill=\"rgb"+str(colour)+"\" fill-opacity=\"0.5\"/>")
def pied():
"""
Returns ending of a file
"""
print("</svg>")
|
221b844e361cac8765de4050424ff77290e831ff | mmontpetit/HackerRank | /diagonal_difference.py | 297 | 3.921875 | 4 | def diagonalDifference(arr):
# Given a square matrix, calculate the absolute difference between the sums of its diagonals.
primary = 0
secondary = 0
for i in range(len(arr)):
primary += arr[i][i]
secondary += arr[i][(len(arr)-i-1)]
return abs(primary-secondary) |
1e31b3b4e6b1d13c1d55ad1ddb67bcba21f9f234 | ManullangJihan/Linear_Algebra_Courses | /CH 1/CH 1 Sec 6 Part 1/part34.py | 195 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 16 07:21:23 2020
@author: hanjiya
"""
import numpy as np
A = np.array([[2,3],[-5,6]])
det_A = np.linalg.det(A)
print(det_A) |
a40dcdede573f1bee76e8a9d8de5dd9d580c77b0 | mymmym1/Python | /Computational Biology/Algorithms for DNA Sequencing/week3/findingOverlaps.py | 3,618 | 3.765625 | 4 | from itertools import permutations
def overlap(a, b, min_length=3):
""" Return [length of longest suffix of 'a'] matching
a [prefix of 'b'] that is at [least 'min_length']
characters long. If no such overlap exists,
return 0. """
start = 0 # search start from index = 0 of a
while True:
# Syntax: string.find(value, start, end)
start = a.find(b[:min_length], start) # look for b's prefix (min_length) in whole a, everytime return the 1st index found
if start == -1: # no occurrence found (e.g. when a gets too short and no b[:min_length] found)
return 0 # get over overlap() function, no overlap found
# when the left->right 1st overlap index (start) is found, check for full suffix/prefix match
if b.startswith(a[start:]): # if a[start:] including lots of bases don't belong to b.startswith, go to start += 1 and look for the next 1st index found
return len(a)-start # return the max length of overlap
start += 1
# print(overlap('TTACGT', 'CGTGTGC'))
# print(overlap('TTACGT', 'GTGTGC')) # only 2 overlaps < min_length=3, return 0
# print(list(permutations([1,2,3],2)))
'''
def naive_overlap_map(reads, k): # k = min_length of overlap. reads: a list of sequences
olaps = {} # dictionary {(a,b):maxOverlapLen, ...}
for a, b in permutations(reads, 2): # compare each 2 reads
maxOverlapLen = overlap(a, b, min_length=k) # This is slow
if maxOverlapLen > 0:
olaps[(a, b)] = maxOverlapLen
return olaps
reads = ['ACGGATC', 'GATCAAGT', 'TTCACGGA']
# print(naive_overlap_map(reads, 3))
'''
### hw3 ###
def readFastq(filename):
sequences = [] # String list
qualities = []
with open (filename) as fh:
while True:
fh.readline() # read the first line which is a tag
seq = fh.readline().rstrip() # read the second line which is DNA sequence
fh.readline() # read the 3rd line
qual = fh.readline().rstrip()
if len(seq) == 0: # String length
break
sequences.append(seq)
qualities.append(qual)
return sequences, qualities
phix_sequences, _ = readFastq('ERR266411_1.for_asm.fastq')
def naive_overlap_map_faster(reads, k): # k = min_length of overlap. reads: a list of sequences
dic = {}
for r in reads:
kmerSet = set()
for i in range(len(r) - k + 1):
kmerSet.add(r[i:i + k])
for kmer in kmerSet:
if not kmer in dic.keys():
dic[kmer] = set()
dic[kmer].add(r)
olaps = {} # dictionary {(r,r2):maxOverlapLen, ...}
# try not call overlap if r doesn't contain r2's kmer suffix
for r in reads:
for r2 in dic[r[-k:]]:
if r != r2:
maxOverlapLen = overlap(r, r2, min_length=k) # This is slow
if maxOverlapLen > 0:
olaps[(r, r2)] = maxOverlapLen
nodeSet = set()
for s in olaps.keys():
nodeSet.add(s[0])
numNodes = len(nodeSet)
return olaps, numNodes
olaps, numNodes = naive_overlap_map_faster(phix_sequences, 30)
edges = len(olaps)
print(edges) # 904746
print(numNodes) # 7161
# reads = ['ABCDEFG', 'EFGHIJ', 'HIJABC']
# print(naive_overlap_map_faster(reads, 3))
# print(naive_overlap_map_faster(reads, 4))
# reads = ['CGTACG', 'TACGTA', 'GTACGT', 'ACGTAC', 'GTACGA', 'TACGAT']
# print(naive_overlap_map_faster(reads, 4))
# print(naive_overlap_map_faster(reads, 5)) |
323ddddb333ed60fa01d23d54003c2420b6162e2 | jess123000/Crazy-Eights | /CardDeck.py | 4,048 | 3.71875 | 4 | #!/usr/bin/env python
# Alex Harris
# CS160
from Card import Card
#----------------------------------------------------------------------
import random
import os
#----------------------------------------------------------------------
class CardDeck:
"""
class for representing a deck of cards
"""
#------------------------------------------------------------------
def __init__(self):
"""
create a deck of cards represented by numbers 0-51
"""
# prevent inspector from warning about instance variable initialized outside __init__
self.cards = []
self.pos = 52
self.stacked = False
# initialize the deck in order
self.freshDeck()
#------------------------------------------------------------------
def freshDeck(self) -> None:
"""
set the deck to be 52 cards in order A-K of Clubs, A-K of Spades, A-K of Hearts, A-K of diamonds
and sets next card to be dealt as the first card (Ace of Clubs)
:return: None
"""
self.cards = list(range(52))
self.pos = 0
self.stacked = False
# allow deck to be stacked with contents of first line in stacked-deck.txt
if os.path.exists("stacked-deck.txt"):
# string version of the face value
FACES = ('a', '2', '3', '4', '5', '6', '7', '8', '9', '10',
'j', 'q', 'k')
# single character string for each suit
SUITS = ('c', 's', 'h', 'd')
self.stacked = True
infile = open("stacked-deck.txt")
line = infile.readline()[:-1]
for i, card in enumerate(line.split()):
try:
face = card[:-1].lower()
suit = card[-1].lower()
face_pos = FACES.index(face)
suit_pos = SUITS.index(suit)
value = suit_pos * 13 + face_pos
# if exception generated, assume it is a number
except TypeError:
value = card
self.cards[i] = value
#print(self.cards[:10])
#------------------------------------------------------------------
def shuffle(self) -> None:
"""
shuffles all 52 cards
:return: None
"""
if not self.stacked:
random.shuffle(self.cards)
# # for each card in the deck
# for i in range(51):
# # pick a random card to swap it with
# r = random.randrange(i+1, 52)
# self.cards[i], self.cards[r] = self.cards[r], self.cards[i]
#------------------------------------------------------------------
def dealOne(self) -> Card:
"""
deals card and updates internal data structures so next card is dealt when called again
:return: the next Card in deck or None if out of cards
"""
# if cards left to deal
if self.pos < 52:
# get card and update the next card to deal
c = Card(self.cards[self.pos])
self.pos += 1
return c
else:
# noinspection PyTypeChecker
return None
# ------------------------------------------------------------------
def numberOfCardsLeft(self) -> int:
"""
:return: number of cards the deck has left to deal (0 to 52)
"""
return 52 - self.pos
# ------------------------------------------------------------------
def __str__(self) -> str:
"""
return string representation of remaining cards in Deck
:return: string with each remaining card separated by a space
"""
return " ".join(str(Card(c)) for c in self.cards[self.pos:])
# ------------------------------------------------------------------
#----------------------------------------------------------------------
|
76843af208c92c4f9e0d049d016b6ec1a1231aa3 | Sudharshan-Sgr/MyCaptain-Python | /area_of_circleAndextension.py | 450 | 3.828125 | 4 | #Task 1
import math
radius = float(input("Input the radius of the circle: "))
area = math.pi * radius ** 2
print("The area of the circle with radius {} is {}".format(radius, area))
#Task 2
file_name = input("Input the Filename: ")
my_Dict = {".py":"Python",".cpp":"C++", ".C":"C", ".java":"Java"}
for i in range(0,len(file_name)):
if file_name[i] == ".":
temp = file_name[i::]
break
if temp in my_Dict:
print(my_Dict[temp]) |
65184ccaa5b506eccbcd784c9993e2dad0e12b4f | div-dos/Codewars | /kyu 6/decode_the_morse_code.py | 745 | 3.5 | 4 |
def decodeMorse(morse_code):
# ToDo: Accept dots, dashes and spaces, return human-readable message
#morse_code = morse_code.replace('.', MORSE_CODE['.']).replace('-', MORSE_CODE['-']).replace(' ', '')
words = morse_code.split(' ')
sol = []
for i in range(len(words)):
words[i] = words[i].split(' ')
length = len(words[i])
while("" in words[i]) :
words[i].remove("")
length -= 1
print(length)
for j in range(length):
words[i][j] = str(MORSE_CODE.get(words[i][j]))
print(words[i])
sol.append("".join(words[i]))
print(sol)
while("" in sol) :
sol.remove("")
return " ".join(sol)
#print(words) |
1371ffd1bd8fb891f422900a532507940e70b8ca | sathishmanthani/python-intro | /code/Math_Operations.py | 1,132 | 3.953125 | 4 | # Addition
a = 100 + 60
print (a) # Prints value 160
# Subraction
a = 100 - 60
print (a) # Prints value 40
# Multiplication
a = 20 * 30
print (a) # Prints value 600
# Division
a = 80 / 20
print (a) # Prints value 4
# remainder
a = 51 % 2
print (a) # Prints value 0
# power
a = 20 ** 3
print (a) # Prints value 80000
print (4 / 2)
print (4 // 2)
a = 1
b = 2
c = a / b
print (a, "/", b, "=", c)
add = str (a) + "/" + str (b) + "=" + str (c)
print (add)
a = "How"
b = "are"
c = "you"
print (a, b, c) # Prints "How are you"
print (a + b + c) # Prints "Howareyou"
var1 = 10
print (type (var1))
var1 = "abc"
print (type (var1))
str1 = "Hello "
var1 = 3
print (var1 * str1)
str1 = "Pie is "
var2 = 3.14
str3 = str1 + str (var2)
print (str3)
a = 3 + 2j
print (a)
print (type (a))
print (a.real)
print (a.imag)
a = abs (-2.22)
print (a)
a = -1.8
b = 2.9
print (abs (a))
print (abs (b))
var1 = 1
# print("its integer:",var1.is_integer())
# a=1.0.is_integer()
# print(a)
# a=121.3123
a = 1.1
b = 10.0
print (a.is_integer ())
# Outputs False
print (b.is_integer ())
# Outputs True
str1 = "abc"
print (str1.isdigit ())
|
12db99b37202419543e6dc76ab76cc1c68f206ec | yuuuhui/Basic-python-answers | /梁勇版_6.12.py | 224 | 3.796875 | 4 | def printChar(ch1,ch2,numberPerLine):
for x in range(ch1,ch2):
print(chr(x),end = " ")
if (x + 1 - ch1) % 10 == 0:
print("\n")
else:
pass
printChar(65,90,10)
|
5a2bf11d5eb53b94206bc3e70db3dc3d7fe97e5f | karollynecosta/basic_python | /Funcoes/definindo_funcoes.py | 906 | 4.25 | 4 | """
Funções
Conceito: São pequenos partes de código que realizam tarefas específicas
São inerentes a linguagem, ex.: print(), len(), max(), min(), count()
Pode ou não receber entrada de dados e retornar uma saída de dados
úteis para executar procedimentos similares por repetidas vezes
1 função = 1 tarefa. Do simple! DRY(Don't Repeat Yourself)
ex: def nome_func(parametros_entrada):
bloco_da_func
Padrões: nome_func -> SEMPRE letra minuscula, se for composto, usar _
parametros_entrada -> Opcionais, +1 é separado por virgulas
bloco_da_func -> Corpo da função, onde o processamento ocorre.
para utilização: nome_func()
"""
# func integrada(built-in)
cores = ['vermelho', 'azul', 'preto']
print(cores)
cores.append('branco')
# ex de funcao sem parametro de entrada
def diz_oi():
print('oi!')
diz_oi()
|
014e4adfd7468d518b3cd7fae87ac08abec49d37 | PedroLSF/PyhtonPydawan | /12b - CHALLENGE_ADV/12b.3_Classes.py | 10,503 | 4.28125 | 4 | ### 1-Robot Inheritance
class Robot:
all_disabled = False
latitude = -999999
longitude = -999999
robot_count = 0
def __init__(self, speed = 0, direction = 180, sensor_range = 10):
self.speed = speed
self.direction = direction
self.sensor_range = sensor_range
self.obstacle_found = False
Robot.robot_count += 1
self.id = Robot.robot_count
def control_bot(self, new_speed, new_direction):
self.speed = new_speed
self.direction = new_direction
def adjust_sensor(self, new_sensor_range):
self.sensor_range = new_sensor_range
def avoid_obstacles(self):
if self.obstacle_found:
self.direction = (self.direction + 180) % 360
self.obstacle_found = False
# Create the DriveBot class here!
class DriveBot(Robot):
def __init__(self, motor_speed = 0, direction = 180, sensor_range = 10):
super().__init__(motor_speed, direction, sensor_range)
# Create the WalkBot class here!
class WalkBot(Robot):
def __init__(self, steps_per_minute = 0, direction = 180, sensor_range = 10, step_length = 5):
super().__init__(steps_per_minute, direction, sensor_range)
self.step_length = step_length
# Uncomment the robot instantiation!
robot_1 = DriveBot()
robot_2 = WalkBot()
robot_3 = WalkBot(20, 90, 15, 10)
# Use these print statements to test your code!
print(robot_2.id)
print(robot_3.step_length)
print(robot_1.speed)
### 2-Using The Superclass
class Robot:
all_disabled = False
latitude = -999999
longitude = -999999
robot_count = 0
def __init__(self, speed = 0, direction = 180, sensor_range = 10):
self.speed = speed
self.direction = direction
self.sensor_range = sensor_range
self.obstacle_found = False
Robot.robot_count += 1
self.id = Robot.robot_count
def control_bot(self, new_speed, new_direction):
self.speed = new_speed
self.direction = new_direction
def adjust_sensor(self, new_sensor_range):
self.sensor_range = new_sensor_range
def avoid_obstacles(self):
if self.obstacle_found:
self.direction = (self.direction + 180) % 360
self.obstacle_found = False
class DriveBot(Robot):
def __init__(self, motor_speed = 0, direction = 180, sensor_range = 10):
super().__init__(motor_speed, direction, sensor_range)
class WalkBot(Robot):
def __init__(self, steps_per_minute = 0, direction = 180, sensor_range = 10, step_length = 5):
super().__init__(steps_per_minute, direction, sensor_range)
self.step_length = step_length
# Override the adjust_sensor method here!
def adjust_sensor(self, new_sensor_range):
super().adjust_sensor(new_sensor_range)
self.obstacle_found = False
self.step_length = 5
robot_walk = WalkBot(60, 90, 10, 15)
robot_walk.obstacle_found = True
print(robot_walk.sensor_range)
print(robot_walk.obstacle_found)
print(robot_walk.step_length)
# Call the overridden adjust_sensor method here!
robot_walk.adjust_sensor(25)
print(robot_walk.sensor_range)
print(robot_walk.obstacle_found)
print(robot_walk.step_length)
### 3-Conditional Superclass Logic
class Robot:
all_disabled = False
latitude = -999999
longitude = -999999
robot_count = 0
def __init__(self, speed = 0, direction = 180, sensor_range = 10):
self.speed = speed
self.direction = direction
self.sensor_range = sensor_range
self.obstacle_found = False
Robot.robot_count += 1
self.id = Robot.robot_count
def control_bot(self, new_speed, new_direction):
self.speed = new_speed
self.direction = new_direction
def adjust_sensor(self, new_sensor_range):
self.sensor_range = new_sensor_range
def avoid_obstacles(self):
if self.obstacle_found:
self.direction = (self.direction + 180) % 360
self.obstacle_found = False
class DriveBot(Robot):
def __init__(self, motor_speed = 0, direction = 180, sensor_range = 10):
super().__init__(motor_speed, direction, sensor_range)
class WalkBot(Robot):
def __init__(self, steps_per_minute = 0, direction = 180, sensor_range = 10, step_length = 5):
super().__init__(steps_per_minute, direction, sensor_range)
self.step_length = step_length
def adjust_sensor(self, new_sensor_range):
super().adjust_sensor(new_sensor_range)
self.obstacle_found = False
self.step_length = 5
# Override the avoid_obstacles method here!
def avoid_obstacles(self):
if(self.obstacle_found):
if(self.speed <= 60):
super().avoid_obstacles()
else:
self.direction = (self.direction + 90) % 360
self.obstacle_found = False
self.speed /= 2
self.step_length /= 2
robot_1 = WalkBot(150, 0, 10, 10)
robot_1.obstacle_found = True
robot_1.avoid_obstacles()
print(robot_1.direction)
print(robot_1.speed)
print(robot_1.step_length)
robot_2 = WalkBot(60, 0, 20, 40)
robot_2.obstacle_found = True
robot_2.avoid_obstacles()
print(robot_2.direction)
print(robot_2.speed)
print(robot_2.step_length)
### 4- Overriding Dunder Methods
class Robot:
all_disabled = False
latitude = -999999
longitude = -999999
robot_count = 0
def __init__(self, speed = 0, direction = 180, sensor_range = 10):
self.speed = speed
self.direction = direction
self.sensor_range = sensor_range
self.obstacle_found = False
Robot.robot_count += 1
self.id = Robot.robot_count
def control_bot(self, new_speed, new_direction):
self.speed = new_speed
self.direction = new_direction
def adjust_sensor(self, new_sensor_range):
self.sensor_range = new_sensor_range
def avoid_obstacles(self):
if self.obstacle_found:
self.direction = (self.direction + 180) % 360
self.obstacle_found = False
# Override the + and - operations here!
def __add__(self, value):
self.speed += value
def __sub__(self, value):
self.speed -= value
class DriveBot(Robot):
def __init__(self, motor_speed = 0, direction = 180, sensor_range = 10):
super().__init__(motor_speed, direction, sensor_range)
# Override the + and - operations here while using those dunder methods from the superclass!
def __add__(self, value):
super().__add__(value)
self.sensor_range += value
def __sub__(self, value):
super().__sub__(value)
self.sensor_range -= value
class WalkBot(Robot):
def __init__(self, steps_per_minute = 0, direction = 180, sensor_range = 10, step_length = 5):
super().__init__(steps_per_minute, direction, sensor_range)
self.step_length = step_length
def adjust_sensor(self, new_sensor_range):
super().adjust_sensor(new_sensor_range)
self.obstacle_found = False
self.step_length = 5
def avoid_obstacles(self):
if(self.obstacle_found):
if(self.speed <= 60):
super().avoid_obstacles()
else:
self.direction = (self.direction + 90) % 360
self.obstacle_found = False
self.speed /= 2
self.step_length /= 2
# Override the + and - operations here while using those dunder methods from the superclass!
def __add__(self, value):
super().__add__(value)
self.step_length += value / 2
def __sub__(self, value):
super().__sub__(value)
self.step_length -= value / 2
robot_1 = DriveBot()
robot_2 = WalkBot()
# Uncomment these lines when you are ready to test your code!
robot_1 + 20
robot_1 - 10
robot_2 + 10
robot_2 - 5
print(robot_1.speed)
print(robot_1.sensor_range)
print(robot_2.speed)
print(robot_2.step_length)
### 5- Prevent A Robot Takeover
class Robot:
all_disabled = False
latitude = -999999
longitude = -999999
robot_count = 0
def __init__(self, speed = 0, direction = 180, sensor_range = 10):
self.speed = speed
self.direction = direction
self.sensor_range = sensor_range
self.obstacle_found = False
Robot.robot_count += 1
self.id = Robot.robot_count
def control_bot(self, new_speed, new_direction):
self.speed = new_speed
self.direction = new_direction
def adjust_sensor(self, new_sensor_range):
self.sensor_range = new_sensor_range
def avoid_obstacles(self):
if self.obstacle_found:
self.direction = (self.direction + 180) % 360
self.obstacle_found = False
def __add__(self, value):
self.speed += value
def __sub__(self, value):
self.speed -= value
class DriveBot(Robot):
def __init__(self, motor_speed = 0, direction = 180, sensor_range = 10):
super().__init__(motor_speed, direction, sensor_range)
def __add__(self, value):
super().__add__(value)
self.sensor_range += value
def __sub__(self, value):
super().__sub__(value)
self.sensor_range -= value
class WalkBot(Robot):
walk_bot_count = 0
def __init__(self, steps_per_minute = 0, direction = 180, sensor_range = 10, step_length = 5):
super().__init__(steps_per_minute, direction, sensor_range)
self.step_length = step_length
WalkBot.walk_bot_count += 1
if(WalkBot.walk_bot_count >= 5 and Robot.robot_count >= 10):
Robot.all_disabled = True
def adjust_sensor(self, new_sensor_range):
super().adjust_sensor(new_sensor_range)
self.obstacle_found = False
self.step_length = 5
def avoid_obstacles(self):
if(self.obstacle_found):
if(self.speed <= 60):
super().avoid_obstacles()
else:
self.direction = (self.direction + 90) % 360
self.obstacle_found = False
self.speed /= 2
self.step_length /= 2
def __add__(self, value):
super().__add__(value)
self.step_length += value / 2
def __sub__(self, value):
super().__sub__(value)
self.step_length -= value / 2
robot_1 = DriveBot()
robot_2 = WalkBot()
robot_3 = DriveBot()
robot_4 = DriveBot()
robot_5 = WalkBot()
robot_6 = DriveBot()
robot_7 = DriveBot()
robot_8 = WalkBot()
robot_9 = WalkBot()
print(Robot.all_disabled)
robot_10 = WalkBot()
print(Robot.all_disabled)
|
e471b090bb2fa09c3de60fb8ea89a8291513ce4c | debolina-ca/my-projects | /Python Codes 2/pet_conversion.py | 221 | 4.09375 | 4 | # Pet Conversion
about_pet = input("Enter a sentence about your pet: ")
if "dog" in about_pet:
print("Ah a dog")
if "cat" in about_pet:
print("Ah a cat")
if "turtle" in about_pet:
print("Ah a turtle")
|
1f509b3acd304a93fc10a2b1383cc777809f14da | JoseTarinT/PasswordManager | /database.py | 1,732 | 3.953125 | 4 | import sqlite3
# Create the queries that we will use in the functions
CREATE_PW_TABLE = "CREATE TABLE IF NOT EXISTS passwords (app TEXT, user TEXT, password TEXT);"
INSERT_DATA = "INSERT INTO passwords (app, user, password) VALUES (?, ?, ?);"
GET_ALL_DATA = "SELECT * FROM passwords;"
GET_BY_APP = "SELECT * FROM passwords WHERE app = ?;"
GET_BY_USER = "SELECT * FROM passwords WHERE user = ?;"
DELETE_ROW = "DELETE FROM passwords WHERE app = ?"
UPDATE_COLUMN = "UPDATE passwords SET app = ?, user = ?, password = ? WHERE app = ?"
# Create the functions
#Create and connect the table database
def connect():
return sqlite3.connect("passwords.db")
def create_database(connection):
with connection:
connection.execute(CREATE_PW_TABLE)
# Function to add new data in the database
def add_data(connection, app, user, password):
with connection:
connection.execute(INSERT_DATA, (app, user, password))
# Get all the data from the database
def get_all_data(connection):
with connection:
return connection.execute(GET_ALL_DATA).fetchall()
# Get data by the app or website name
def get_by_app(connection, app):
with connection:
return connection.execute(GET_BY_APP, (app)).fetchall()
# Get data by the user name
def get_by_user(connection, user):
with connection:
return connection.execute(GET_BY_USER, (user)).fetchall()
# Delete row
def delete_info(connection, app):
with connection:
return connection.execute(DELETE_ROW, (app,))
# Update app name, user or/and password
def modify_column(connection, app, user, password, appp):
with connection:
return connection.execute(UPDATE_COLUMN, (app, user, password, appp))
|
faca5b9c5cd5f70e157342f2fbb13e22c98568b6 | elli0t-yash/DSA_with_Python | /Array/Reversed.py | 239 | 3.921875 | 4 | def ReversedArray(arr, start, end) :
while start < end :
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
A = [1, 2, 3, 4, 5, 6]
print(A)
end = len(A)
ReversedArray(A, 0, (end - 1))
print(A) |
be3e3ec50b2d0be4a2b3ef8c0f49c7533dfcee44 | rehoboth23/leetcode-base | /new/subtree of another tree.py | 982 | 4 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
def checkSubnodes(root, target):
if (not root and target) or (root and not target):
return False
elif not root and not target:
return True
elif root.val != target.val:
return False
else:
return checkSubnodes(root.left, target.left) and checkSubnodes(root.right, target.right)
def findNode(root, target):
if not root:
return False
check = False
if root.val == target.val:
check = checkSubnodes(root, target)
return check or findNode(root.right, target) or findNode(root.left, target)
return findNode(s, t)
|
1493e9ec78377162c601509e98822945f92b74d6 | starnowski/python-fun | /fundamentals/fundamentals/calendar/print_calendar.py | 636 | 3.53125 | 4 | import calendar
class CalendarPrinter:
def __init__(self, first_day_of_calendar = calendar.MONDAY):
self.first_day_of_calendar = first_day_of_calendar
pass
def return_calendar_string(self):
c = calendar.TextCalendar(self.first_day_of_calendar)
return c.formatmonth(2019, 1, 0, 0)
if __name__ == "__main__":
cp_monday = CalendarPrinter()
cp_wednesday = CalendarPrinter(calendar.WEDNESDAY)
print("Calendar which starts from Monday:")
print(cp_monday.return_calendar_string())
print("Calendar which starts from Wednesday:")
print(cp_wednesday.return_calendar_string())
|
59fd9ad978c793d25317c5ad94efcfca973f0f0f | banggeut01/algorithm | /code/list/5122.py | 3,141 | 3.703125 | 4 | # 5122.py 수열 편집
import sys
sys.stdin = open('5122input.txt', 'r')
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def insertLast(self, node):
if self.head is None: # 빈리스트
self.head = self.tail = node
else:
self.tail.next = node
self.tail = node
def printList(self):
if self.head is None:
print('빈리스트')
else:
cur = self.head
while cur is not None:
print(cur.data, end=' ')
cur = cur.next
print()
def insertAt(self, idx, node):
if self.head is None: # 빈리스트
return
prev, cur = None, self.head
while idx > 0 and cur is not None:
prev = cur
cur = cur.next
idx -= 1
if prev is None: # 첫번째위치에 추가
node.next = self.head
self.head = node
elif cur is None: # 마지막위치에 추가
self.tail.next = node
self.tail = node
else:
prev.next = node
node.next = cur
def updateAt(self, idx, data):
if self.head is None: # 빈리스트
return
cur = self.head
while idx > 0 and cur is not None:
cur = cur.next
idx -= 1
cur.data = data
def deleteAt(self, idx):
if self.head is None: # 빈리스트
return
prev, cur = None, self.head
while idx > 0 and cur is not None:
prev = cur
cur = cur.next
idx -= 1
if prev is None: # 첫번째위치
self.head = cur.next
elif cur is None: # 마지막위치
prev.next = None
self.tail = prev
else:
prev.next = cur.next
def printAt(self, idx):
if self.head is None: # 빈리스트
return -1
cur = self.head
while idx > 0 and cur is not None:
cur = cur.next
idx -= 1
if cur is None:
if idx == 0:# 마지막위치
return self.tail.data
else:
return -1
else:
return cur.data
t = int(input())
for tc in range(1, t + 1):
n, m, l = map(int, input().split()) # n: 수열길이, m: 추가횟수, l: 출력인덱스번호
inputs = list(map(int, input().split()))
# 연결리스트 생성
mylist = LinkedList()
for data in inputs:
mylist.insertLast(Node(data))
for _ in range(m):
inputs = list(input().split())
if inputs[0] == 'I': # 추가
mylist.insertAt(int(inputs[1]), Node(int(inputs[2]))) # idx, node
else:
if inputs[0] == 'C': # 수정
mylist.updateAt(int(inputs[1]), int(inputs[2])) # idx, node
else: # 삭제
mylist.deleteAt(int(inputs[1])) # idx
print('#{} {}'.format(tc, mylist.printAt(l))) |
9150ef237120d557b694cdd238f903325ed08dd1 | mkjmkumar/PythonCheatSheet_SampleCode | /First.py | 126 | 3.734375 | 4 | print("Hello Python")
var=10
name="Mukesh"
var1="29"
def add():
sum=var+int(var1)
print(sum)
add()
print(name) |
ca9764d778f336a59a956bd73ad61f75e0a165c5 | Larionov0/python_v1 | /task1.py | 1,037 | 3.71875 | 4 | from data import dataset
# Написати функцію, що зберігає інформацію про улюблену страву користувача у певній країні
# Викликати функцію
def addUserDish(user_name, country, dish):
if user_name in dataset:
if country in user_name:
dataset[user_name][country].add(dish)
else:
dataset[user_name][country]={dish} #={country:{dish}}
else:
dataset[user_name]={country:{dish}}
#TODO
print("Task 1")
#Додати нового користувача та страву у новій країні
addUserDish("EK346743","USA","Water")
#Додати існуючому користувачу нову країну з новою стравою
addUserDish("PS334743","Ukraine","Water")
#Додати існуючому користувачу нову страву в існуючого країну
addUserDish("EK346743","Ukraine","Kovbasa")
print(dataset)
print("\n\n") |
d1cdae06f73600b5b75c7ff5d5487b0e21873f05 | davidmrau/trec_utils | /line2trectext.py | 862 | 3.5 | 4 | # gets one query per line as input, writes in trectext format
# example usage:
#python3 query2trectext.py filename
import sys
import json
fname = sys.argv[1]
queries = list()
count = 1
fname_pure = fname.split('/')[-1]
out_file = fname + '.trectext'
queries = list()
def make_elem(num, text):
return '<top>\n\n<num> Number: ' + str(num) + '\n\n<title> ' + text + '\n\n <desc> \n\n </top>\n\n\n\n'
with open(fname, 'r') as f:
with open(out_file, 'w') as out:
line = f.readline().strip()
while line:
# check if query file containes query names
query_name = fname_pure[:3] + str(count)
out.write(make_elem(query_name, line))
queries.append({ 'number': query_name , 'text': line })
count += 1
line = f.readline().strip()
with open(fname + '.names', 'w') as f:
for q in queries:
f.write(q['number'] + '\t' + q['text'] + '\n')
|
8bb707012485e30a278376e74ab908b496c2c424 | subnr01/Programming_interviews | /programming-challanges-master/codeeval/098_point-in-a-circle.py | 1,079 | 4.15625 | 4 | #!/usr/bin/env python
"""
Point in Circle
Challenge Description:
Having coordinates of the center of a circle, it's radius and coordinates of a point you need to define whether this point is located inside of this circle.
Input sample:
Your program should accept as its first argument a path to a filename. Input example is the following
Center: (2.12, -3.48); Radius: 17.22; Point: (16.21, -5)
Center: (5.05, -11); Radius: 21.2; Point: (-31, -45)
Center: (-9.86, 1.95); Radius: 47.28; Point: (6.03, -6.42)
All numbers in input are between -100 and 100
Output sample:
Print results in the following way.
true
false
true
"""
import re, sys
if __name__ == '__main__':
regex = re.compile(r'(-?\d+(\.\d+)?)')
with open(sys.argv[1]) as f:
for line in f:
if line.strip():
cx, cy, r, px, py = [float(x[0]) for x in regex.findall(line)]
if (cx - px)**2 + (cy - py)**2 > r * r:
print('false')
else:
print('true')
|
e71afa11d8f3dff9b172c59c646a908c52f41091 | gerald-odonnell7/LearningToProgram | /animal.py | 605 | 3.9375 | 4 | class Animal:
'This class is designed to represent real world animals'
numAnimals = 0
def __init__(self, name, length, weight, color, sound):
self.name = name
self.length = length
self.weight = weight
self.color = color
self.sound = sound
Animal.numAnimals += 1
def eat(self):
print self.name, " is eating"
def sleep(self):
print self.name, " is sleeping"
def run(self):
print self.name, " is running"
def displayAnimalCount(self):
print Animal.numAnimals
kitty = Animal("Fluffy", 18, 5, "Orange", "Meow")
kitty.eat()
kitty.sleep()
kitty.run()
kitty.displayAnimalCount()
|
29d2fab5f23d06fc6229042eefa81180e5d4467d | codeasitis/Python | /RecursionExample.py | 319 | 4 | 4 | def factorial(n):
if n==0 | n==1:
return 1
return n*factorial(n-1)
print(factorial(3))
def fabonacci(n):
if n==1:
return 1
elif n==2:
return 1
elif n>2:
return fabonacci(n-1)+fabonacci(n-2)
for x in range(1,10):
print(x,"",fabonacci(x))
|
32e61668c17365d89fee8262c8d235d8bd5e2ec2 | baloncek2662/advent-of-code-2020 | /solutions/day_07.py | 3,138 | 3.546875 | 4 | #!/usr/bin/env python
import time
SHINY_GOLD = 'shiny gold'
def main():
input_list = get_input_list()
solve_a(input_list)
print()
solve_b(input_list)
def solve_a(bag_list):
result = 0
for b in bag_list:
if contains_gold_bag(bag_list, b) and b.color != SHINY_GOLD:
result += 1
print(f'Number of bags which can contain a shiny gold bag: {result}')
def contains_gold_bag(bag_list, master_bag):
if master_bag.color == SHINY_GOLD:
return True
for contained_bag in master_bag.contained_bags:
if contains_gold_bag(bag_list, get_bag(bag_list, contained_bag.color)):
return True
return False
def solve_b(bag_list):
shiny_gold_bag = get_bag(bag_list, SHINY_GOLD)
result = contained_count(bag_list, shiny_gold_bag) - 1 # minus 1 because the bag does not contain itself
print(f'Number of bags a shiny gold bag can hold: {result}')
def contained_count(bag_list, master_bag):
if len(master_bag.contained_bags) == 0:
return 1
contained_bag_sum = 0
for i in range(0, len(master_bag.contained_bags)):
contained_bag = master_bag.contained_bags[i]
contained_bag_count = master_bag.contained_bag_count[i]
temp = contained_bag_count * contained_count(bag_list, contained_bag)
contained_bag_sum += temp
return contained_bag_sum + 1
def get_input_list():
file = open("../inputs/day_07.txt", "r")
bag_list = []
for line in file.readlines():
master_bag_color = line.split(' bags contain ')[0]
master_bag = get_bag(bag_list, master_bag_color)
if master_bag is None:
master_bag = Bag(master_bag_color)
bag_list.append(master_bag)
contained_bags = line.split(' bags contain ')[1].split('.')[0].split(', ')
if 'no other bags' in contained_bags:
continue
for b in contained_bags:
b = b.split(' bag')[0] # get rid of singular/plural
count = int(b[0]) # first char is number of bags
color = b[2:]
contained_bag = get_bag(bag_list, color)
if contained_bag is None:
contained_bag = Bag(color)
bag_list.append(contained_bag)
master_bag.add_contained(contained_bag, count)
file.close()
return bag_list
def get_bag(bag_list, bag_color):
for b in bag_list:
if b.color == bag_color:
return b
return None
def print_bag(bag_list):
for b in bag_list:
print(b.color)
for cb in b.contained_bags:
print(cb['count'])
print('==============')
class Bag():
def __init__(self, color):
self.color = color
self.contained_bags = []
self.contained_bag_count = []
def add_contained(self, contained_bag, count):
self.contained_bags.append(contained_bag)
self.contained_bag_count.append(count)
if __name__ == "__main__":
start_time = time.time()
main()
end_time = time.time()
print(f'\nExecution time: {end_time - start_time} s') |
a418eab99354bd0d06e66abdc044938fb17b5005 | jiangyanglinlan/Data-Structures-and-Algorithms | /剑指offer/63_数据流中位数.py | 1,432 | 3.75 | 4 | # -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.nums = []
def Insert(self, num):
# write code here
self.nums.append(num)
def GetMedian(self, n=None):
# write code here
nums_length = len(self.nums)
if nums_length & 0b1 == 1:
# 奇数
return self.quick_select(self.nums, 0, nums_length - 1, nums_length / 2 + 1)
else:
num1 = self.quick_select(self.nums, 0, nums_length - 1, nums_length / 2)
num2 = self.quick_select(self.nums, 0, nums_length - 1, nums_length / 2 + 1)
return float(num1 + num2) / 2
def quick_select(self, nums, start, end, k):
if start == end:
return nums[start]
index = self.partition(nums, start, end)
num = index - start + 1
if k == num:
return nums[index]
elif k > num:
return self.quick_select(nums, index + 1, end, k - num)
else:
return self.quick_select(nums, start, index - 1, k)
def partition(self, nums, start, end):
pivot = nums[start]
while start < end:
while start < end and nums[end] >= pivot:
end -= 1
nums[start] = nums[end]
while start < end and nums[start] <= pivot:
start += 1
nums[end] = nums[start]
nums[start] = pivot
return start |
d5534714e74d465a61a7059639b73f03f97ab374 | jinho6225/python_with_django | /syntax/function.py | 1,727 | 4.125 | 4 | #function
print("="*50)
# def name(params):
# do something1
# do something2
# ...
def add(a, b):
return a + b
a = 3
b = 4
c = add(a, b)
print(c)
print("="*50)
def add(a, b):
return a+b
result = add(a=3, b=7) # a에 3, b에 7을 전달
print(result)
print("="*50)
# def name(*params):
# do something1
# do something2
# ...
def add_many(*args):
result = 0
for i in args:
result = result + i
return result
result = add_many(1,2,3)
print(result)
result = add_many(1,2,3,4,5,6,7,8,9,10)
print(result)
print("="*50)
def print_kwargs(**kwargs):
return (kwargs)
print(print_kwargs(a=1))
print(print_kwargs(name='foo', age=3))
print("="*50)
#lambda
add = lambda a, b: a+b
result = add(3, 4)
print(result)
# a = input()
# print(a)
# number = input("input the number: ")
# print(number)
# f = open('new.txt','w')
# for i in range(1, 11):
# data = f"line no.{i}\n"
# f.write(data)
# f.close()
# f = open("new.txt", 'r')
# while True:
# line = f.readline()
# if not line: break
# print(line)
# f.close()
# f = open("new.txt", 'r')
# lines = f.readlines()
# for line in lines:
# print(line)
# f.close()
f = open("new.txt", 'r')
data = f.read()
print(data)
f.close()
f = open("new.txt",'a')
for i in range(11, 20):
data = f"line no.{i}\n"
f.write(data)
f.close()
f = open("new.txt", 'r')
data = f.read()
print(data)
f.close()
print("="*50)
import sys
args = sys.argv[1:]
for i in args:
print(i.upper(), end=' ')
# a = input('\n what is you name?')
print("="*50)
print(f"your name is {a}")
print("you" "need" "python")
print("you"+"need"+"python")
print("you", "need", "python")
print("".join(["you", "need", "python"])) |
1d3409bb5f11b79e016f6f857f8d8d0ad15f12d3 | ckjq202682/AS01 | /main.py | 281 | 3.5625 | 4 | # AS01
mylist = [1, 5, 2, 7, 8, 3, 6, 9, 4]
for a in range(len(mylist) - 1):
for i in range(len(mylist) - 1):
if mylist[i] > mylist[i + 1]:
hold = mylist[i + 1]
mylist[i + 1] = mylist[i]
mylist[i] = hold
print(mylist)
|
dead2a31f068aca0c900ce6fd4e89f62c405c1ad | luiseleazar/curso_python_int | /lambda.py | 369 | 3.546875 | 4 | def run():
my_list = [1, 2, 3, 4, 5]
#filter
odd = list(filter(lambda x: x%2 != 0, my_list))
print(odd)
#map
square = list(map(lambda i : i**2, my_list))
print(square)
#reduce
from functools import reduce
multi = 1
multi = reduce(lambda a,b : a * b, my_list)
print(multi)
if __name__ == '__main__':
run() |
8609aad387b5c2712dac9c2f77fb1b44eddca3f9 | cesnik-jure/Python_SmartNinja | /Python tecaj/lesson_04/counting.py | 855 | 3.984375 | 4 | def sum_of_numbers(a, b):
c = a + b
print(c)
return c
def sum_of_lists(a, b = []):
s = 0
for num in a:
s = s + num
for num in b:
s = s + num
return s
def sum_of_seperate_lists(a = [], b = []):
sum1 = 0
sum2 = 0
for num in a:
sum1 = sum1 + num
for num in b:
sum2 = sum2 + num
return sum1, sum2
def main():
number_one = 15
number_two = 40
d = sum_of_numbers(number_one, number_two)
print(d)
l = [5, 10, 15]
k = [6, 3, 2]
s1 = sum_of_lists(l, k)
print(s1)
s2 = sum_of_lists(l)
print(s2)
# sum1, sum2 = sum_of_seperate_lists(l, k)[0]
print(sum_of_seperate_lists(l, k)[0])
print(sum_of_seperate_lists(l, k)[1])
# https://stackoverflow.com/questions/419163/what-does-if-name-main-do
if __name__ == "__main__":
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.