blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
40392333c565f642a9bd0d795dc57cd899409954 | KangFrank/Python_Start | /Judgement_loop.py | 1,414 | 3.96875 | 4 | #!/usr/bin/env python3
#-*-coding:utf-8 -*-
"""
#Judgements
age=20/2
if age>=18:
print("Your age is %d"%age)
print("Your age is ",age)
elif age>=8:
print("Teenager, your age is ",age)
else:
print('Your age is %d'%age) #The %d used here is to make the result an integer
print('Get away,little child')
#The user_defined input things
birth=int(input('birth: ')) #The input returns a 'str' type, need a compulsive transfer to int type
if birth>2000:
print('00 after')
elif birth>1990:
print('90 after')
else:
print('You are old now, go to die plz!')
"""
#Loop
sum=0
#for type loop
for i in range(1001):
sum=sum+i
print(sum)
#while type loop
sum1=0
n=999
while n>0:
sum1=sum1+n
n-=1
print(sum1)
#Dictionary
M={"Michael":95,'Bob':75,'Tracy':85}
print(M['Bob'])
M['Adams']=99 #Add element directly
print(M)
#judge one element is in the Dic or not
M.get('Tomas',-1) #if not in, return a num, the default number is 0
M.pop('Bob') #Use pop() to cancle a key just as the list,and the value is cancled too
#Set created,need a list as the input,and only contains the keys without the values
s=set([1,2,3])
ss=set([4,2,3])
s.add(4) #Add an element
s.remove(4) #Cancle an element
print(s & ss) #And logic
print(s | ss) #Or logic
##The only distinguish between set and dic is whether there is a correponding value to the key
|
71bdc71f499e6ef9b8dc9610e5670aa43ff800f3 | mirii-ai/DFESW3 | /birds_subclasses.py | 1,357 | 4.0625 | 4 | from abc import ABC, abstractmethod
class Bird(ABC):
fly = True
babies = 0
def noise(self):
return "Squawk"
def reproduce(self):
self.babies += 1
@abstractmethod
def eat(self):
pass
extinct = False
class Owl(Bird):
def reproduce(self):
self.babies += 6
return self.babies
def noise(self):
return "Twit Twoo"
def eat(self):
return "Peck peck"
## we have used Polymorphism to override the reproduce method,
# Abstraction with the eat method and Inheritance in this child class.
class Dodo(Bird):
Fly = False
extinct = True
def eat(self):
return "Nom nom"
def reproduce(self):
if not self.extinct:
self.babies += 1
return self.babies
##For this subclass we have used Polymorphism to override the reproduce
# method and Fly and extinct variables, Encapsulation to keep the babies variable from
# being directly accessed as well as Inheritance again to create a child class of Bird.
JohnTheDodo = Dodo()
FredTheDodo = Dodo()
SamuelTheOwl = Owl()
RingoTheOwl = Owl()
JohnTheDodo.extinct = False
print(JohnTheDodo.extinct)
print(FredTheDodo.extinct)
print(RingoTheOwl.reproduce())
print(FredTheDodo.eat())
print(JohnTheDodo.reproduce(), JohnTheDodo.noise())
print(RingoTheOwl.noise())
|
dabe2b025c035113c49fa0406677eff69b2233b7 | fangpings/Leetcode | /104 Maximum Depth of Binary Tree/untitled.py | 794 | 3.625 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root):
if not root:
return 0
rootd = max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
return rootd
def build_tree(l):
def rec(k):
if k - 1 < len(l):
if l[k-1]:
node = TreeNode(l[k-1])
node.left = rec(2*k)
node.right = rec(2*k+1)
return node
else:
l.insert(2*k-1, None)
l.insert(2*k, None)
return None
return rec(1)
if __name__ == '__main__':
sol = Solution()
r = build_tree([3,9,20,None,None,15,7])
print(sol.maxDepth(None))
|
835db71e4e6daf85f698761ba7a77c9f86437ef6 | Sergey-Laznenko/Stepik | /Python Programming/1_Operators. Variables/1.12_Tasks_1st_week/5.py | 795 | 4.25 | 4 | """
Напишите программу, которая получает на вход три целых числа, по одному числу в строке,
и выводит на консоль в три строки сначала максимальное, потом минимальное, после чего оставшееся число.
"""
n1 = int(input())
n2 = int(input())
n3 = int(input())
if n1 >= n2 >= n3:
print(n1)
print(n3)
print(n2)
elif n1 >= n3 >= n2:
print(n1)
print(n2)
print(n3)
elif n2 >= n1 >= n3:
print(n2)
print(n3)
print(n1)
elif n2 >= n3 >= n1:
print(n2)
print(n1)
print(n3)
elif n3 >= n1 >= n2:
print(n3)
print(n2)
print(n1)
else: # 6
print(n3)
print(n1)
print(n2)
|
6d93455da9505e4e8df2893cce3ee6880bec1881 | gabriellaec/desoft-analise-exercicios | /backup/user_299/ch27_2020_04_06_16_37_11_502842.py | 201 | 3.984375 | 4 | duvidas = True
while duvidas:
temduvidas = input("você tem duvidas?")
if temduvidas == 'não':
print("Até a próxima")
duvidas = False
else:
print("Pratique mais") |
77db6a0822f4195355b481fd9b0a84d1c407d156 | JadoRob/NCI-AWS-Restart | /Programming/Exercises/main.py | 659 | 3.96875 | 4 | import os
import math
from os import system
from Programming.Exercises.calculate import calculateGallonPrice, displayGallonsNeeded, caclulateWallArea
#Ask user for the length width and height
length=int(input('Please enter the length of the room: '))
width=int(input('Please enter the width of the room: '))
height=int(input('Please enter the height of the room: '))
wallArea = caclulateWallArea(length, width, height)
gallonsOfPaint = displayGallonsNeeded(wallArea)
totalPrice = calculateGallonPrice(gallonsOfPaint)
print(f'The number of gallons needed is: {gallonsOfPaint}')
print(f'For {gallonsOfPaint} gallons of paint, the cost will be ${totalPrice}') |
a279c8144ba86ed0feab729acc82b8c94d5b5891 | Matrixuniverses/AI | /Lab2/LCFSFrontier.py | 753 | 3.671875 | 4 | from search import *
class LCFSFrontier():
def __init__(self):
self.container = []
def add(self, path):
self.container.append(path)
def __iter__(self):
return self
def __next__(self):
self.sort_container()
value = self.container.pop(0)
return value
# This implementation uses a counting sort, however using heapq the implementation can be done so
# that heapq manages the sort on each iteration
def sort_container(self):
cost_list = []
for path in self.container:
total = 0
for arc in path:
total += arc[3]
cost_list.append(total)
self.container = [x for _, x in sorted(zip(cost_list,self.container))]
|
d31ee72e51f015c0f56c6a888d91a7483bc790c9 | korchalovsky/python-learn | /sort and search algorithms/binary_tree.py | 7,351 | 3.796875 | 4 | class Leaf:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
def min_left_in_right(current_elem):
current_elem = current_elem.right
while current_elem.left:
current_elem = current_elem.left
return current_elem
def min_left_in_right_parent(parent):
current_elem = parent.right
if current_elem.left.left is None:
parent = current_elem
return parent
else:
while current_elem.left.left:
current_elem = current_elem.left
parent = current_elem
return parent
class Tree:
def __init__(self):
self.first = None
def add(self, new_value, current_elem=None):
if current_elem is None:
current_elem = self.first
if self.first is None:
self.first = Leaf(new_value)
elif new_value < current_elem.value:
if current_elem.left is not None:
return self.add(new_value, current_elem.left)
if current_elem.left is None:
current_elem.left = Leaf(new_value)
elif new_value > current_elem.value:
if current_elem.right is not None:
return self.add(new_value, current_elem.right)
if current_elem.right is None:
current_elem.right = Leaf(new_value)
def print(self, current_elem=None):
if current_elem is None and self.first is not None:
current_elem = self.first
if current_elem.left is not None:
self.print(current_elem.left)
if current_elem.left is None:
print(current_elem.value)
if current_elem.right is not None:
if current_elem.right is not None and current_elem.left is not None:
print(current_elem.value)
self.print(current_elem.right)
if current_elem.right is None and current_elem.left is not None:
print(current_elem.value)
def search(self, value, current_elem=None):
if current_elem is None and self.first is not None:
current_elem = self.first
if current_elem.value == value:
return print(value)
if current_elem.left is not None:
if current_elem.left.value == value:
return print(value)
else:
self.search(value, current_elem.left)
if current_elem.right is not None:
if current_elem.right.value == value:
return print(value)
else:
self.search(value, current_elem.right)
def remove(self, value, current_elem=None):
if current_elem is None and self.first is not None:
current_elem = self.first
# if current_elem.value == value:
# parent = current_elem
# if current_elem.right.left is not None:
# current_elem = min_left_in_right(current_elem)
# parent.right = current_elem
# parent = min_left_in_right_parent(self.first)
# parent.left = None
# current_elem.right = self.first.right
# current_elem.left = self.first.left
# return
# if current_elem.right.left is None:
# parent.right = current_elem.right
# parent.right.left = current_elem.left
# return
if current_elem.left is not None:
if current_elem.left.value == value:
parent = current_elem
current_elem = current_elem.left
if current_elem.left is None and current_elem.right is None:
parent.left = None
return
if current_elem.left is not None and current_elem.right is None:
parent.left = current_elem.left
return
if current_elem.left is None and current_elem.right is not None:
parent.left = current_elem.right
return
if current_elem.left is not None and current_elem.right is not None:
if current_elem.right.left is not None:
temp_curr = current_elem
current_elem = min_left_in_right(current_elem)
parent.left = current_elem
parent = min_left_in_right_parent(temp_curr)
parent.left = None
current_elem.right = temp_curr.right
current_elem.left = temp_curr.left
return
if current_elem.right.left is None:
if current_elem == parent.right:
parent.right = current_elem.right
current_elem.right = parent.left
return
if current_elem == parent.left:
parent.left = current_elem.right
parent.left.left = current_elem.left
return
else:
self.remove(value, current_elem.left)
if current_elem.right is not None:
if current_elem.right.value == value:
parent = current_elem
current_elem = current_elem.right
if current_elem.left is None and current_elem.right is None:
parent.right = None
return
if current_elem.left is not None and current_elem.right is None:
parent.right = current_elem.left
return
if current_elem.left is None and current_elem.right is not None:
parent.right = current_elem.right
return
if current_elem.left is not None and current_elem.right is not None:
if current_elem.right.left is not None:
temp_curr = current_elem
current_elem = min_left_in_right(current_elem)
parent.right = current_elem
parent = min_left_in_right_parent(temp_curr)
parent.left = None
current_elem.right = temp_curr.right
current_elem.left = temp_curr.left
return
if current_elem.right.left is None:
parent.right = current_elem.right
parent.right.left = current_elem.left
return
else:
self.remove(value, current_elem.right)
return
tree = Tree()
tree.add(33)
tree.add(35)
tree.add(5)
tree.add(99)
tree.add(1)
tree.add(20)
tree.add(4)
tree.add(17)
tree.add(31)
tree.add(18)
tree.add(19)
tree.add(16)
tree.add(15)
tree.add(34)
tree.add(70)
tree.add(110)
tree.add(105)
tree.add(80)
tree.add(65)
tree.remove(35)
tree.print()
|
a0bccfb67a18cd3a01e4fac1e493b74f74c48f7e | mrtbld/practice | /leetcode/125-valid-palindrome/125.py | 1,144 | 3.953125 | 4 | class Solution:
# t:O(n), s:O(1)
def isPalindrome(self, s):
"""Return True if given string is a palindrome, False otherwise.
Only consider ASCII alphanumeric chars, case-insensitively.
>>> Solution().isPalindrome('A man, a plan, a canal: Panama')
True
>>> Solution().isPalindrome('race a car')
False
>>> Solution().isPalindrome('')
True
>>> Solution().isPalindrome('!?')
True
>>> Solution().isPalindrome('a')
True
>>> Solution().isPalindrome('abcba')
True
>>> Solution().isPalindrome('abccba')
True
>>> Solution().isPalindrome('abcdba')
False
"""
i = 0
j = len(s) - 1
while i < j:
a = s[i].lower()
if not ('a' <= a <= 'z' or '0' <= a <= '9'):
i += 1
continue
b = s[j].lower()
if not ('a' <= b <= 'z' or '0' <= b <= '9'):
j -= 1
continue
if a != b:
return False
i += 1
j -= 1
return True
|
ef420579f3470b8335c3f26c38490d519e319b60 | tuhiniris/Python-ShortCodes-Applications | /patterns1/alphabet pattern_16.py | 419 | 4.125 | 4 | '''
Pattern:
Enter the number of rows: 5
A
A B A
A B C A B
A B C D A B C
A B C D E A B C D
'''
print('Alphabet Pattern: ')
number_rows=int(input('Enter number of rows: '))
for row in range(1,number_rows+1):
print(' '*(number_rows-row),end=' ')
for column in range(1,row+1):
print(chr(column+64),end=' ')
for column in range(1,row):
print(chr(64+column),end=' ')
print() |
2e7cdf76cbf5cd22f69c7137874e17b887a14357 | velichkosa/gkb_study | /HW/Les1/hw1_2.py | 496 | 4.1875 | 4 | # 2
# Пользователь вводит время в секундах. Переведите время в часы, минуты и
# секунды и выведите в формате чч:мм:сс. Используйте форматирование строк.
sec= input("Введите количество секунд: ")
sec= int(sec)
hh= sec//3600
mm= (sec-((sec//3600)*3600))//60
ss= sec%60
print('%(hour)02d:%(minute)02d:%(second)02d' % {"hour":hh,"minute":mm,"second":ss})
|
92efea4153f4fd452c2ad4209cda157e1c36fcd4 | DenisFuryaev/PythonProjects | /papacode/word_shuffle.py | 555 | 3.65625 | 4 | import re
import string
def dict_from_str(str):
dict = {}
for char in str:
if char in ',.!?':
if char in dict:
dict[char] = dict[char] + 1
else:
dict[char] = 1
for word in re.split('[ ,.!?]+', str.lower()):
if len(word) == 0:
continue
if word in dict:
dict[word] = dict[word] + 1
else:
dict[word] = 1
return dict
str_1 = input()
str_2 = input()
a = dict_from_str(str_1)
b = dict_from_str(str_2)
print(a == b)
|
b8bc2685a062df699e286019bba4ad3f37ddf3a2 | jocelinoFG017/IntroducaoAoPython | /01-Cursos/GeekUniversity/Seção07-Coleções/Tuplas.py | 2,280 | 4.5625 | 5 | """
Tuplas Imutáveis e são representadas por ()
#cuidado 1: As tuplas são representadas por (), mas veja
tupla1 = (1 , 2, 3, 4, 5, 6)
print(tupla1)
print(type(tupla1))
tupla2 = 1 , 2, 3, 4, 5, 6
print(tupla2)
print(type(tupla2))
# CUIDADO 2: Tuplas com 1 elemento
tupla3 = (4) # isso não é uma tupla
print(tupla3)
print(type(tupla3))
tupla4 = (4, ) # isso é uma tupla
print(tupla4)
print(type(tupla4))
# Tuplas são definidas pelo uso da virgula, e não dos parenteses()
# Gerar tupla dinamica com range (inicio,fim, passo)
tupla = tuple(range(11))
print(tupla)
# desenpacotamento de tupla
tupla = ('geek university', 'python')
escola, curso = tupla
print(escola)
print(curso)
# soma, valor maximo, valor minimo e tamanho
tupla = (1, 2, 3, 4, 5, 6)
print(sum(tupla))
print(max(tupla))
print(min(tupla))
print(len(tupla))
# concatenação de tuplas
tupla1 = (1, 2, 3, )
print(tupla1)
tupla2 = (4, 5, 6, )
print(tupla2)
print(tupla1 + tupla2)
# Verificar se determinado elemento está contido na tupla
tupla = (1, 2, 3, )
print(3 in tupla)
# Iterando sobre uma tupla
tupla = (1, 2, 3, )
for n in tupla:
print(n)
# Contando elementos dentro de uma tupla
tupla = ('a', 'b', 'c', 'd', 'e', 'a', 'b')
print(tupla.count('c'))
escola = tuple('geek university')
print(escola)
print(escola.count('e'))
# Dicas na utilização de tuplas
#Deve-se utilizar sempre que não seja necessário modificar os dados cntidos em uma coleção
# Exemplo 1
meses= ('Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho')
print(meses)
# Acesso aos elementos das tuplas é semelhante ao de uma lista
print(meses[5])
# Iterar com while
i = 0
while i < len(meses):
print(meses[i])
i = i + 1
# verificamos em qual indice um elemento está na tupla
print(meses.index('Junho'))
# slicing
# tupla[inicio:fim:passo]
print(meses[0:])
"""
# Por que utilizar tuplas ?
# - tuplas são mais rápidas do que listas
# - tuplas deixam seu código mais seguro*
# *(isso pq trabalhar com elementos imutáveis traz segurança para o código)
# Copiando uma tupla para outra
tupla = (1, 2, 3)
print(tupla)
nova = tupla # Na tupla não temos o problema de shallow copy
print(nova)
print(tupla)
outra = (4, 5, 6)
nova = nova + outra
print(nova)
print(tupla) |
5fc7e7a7af529ad1045a50ad0cf5aed391b3dea9 | devAmoghS/UC-Berkeley-CS61A | /custom_count_method.py | 154 | 3.53125 | 4 | def count(sequence):
if not sequence:
return 0
else:
return 1+count(sequence[1:])
array = [i for i in range(1, 101)]
print(count(array))
|
b30d1bf6d9fc37dc0b5b0b719996c95ac8d91bcc | kelly-gilbert/preppin-data-challenge | /2022/preppin-data-2022-02/preppin-data-2022-02.py | 6,169 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Preppin' Data 2022: Week 2 The Prep School - Birthday Cakes
https://preppindata.blogspot.com/2022/01/2022-week-2-prep-school-birthday-cakes.html
- Input data
- Removing any unnecessary fields (parental fields) will make this challenge easier to see what
is happening at each step
- Format the pupil's name in First Name Last Name format (ie Carl Allchin)
- Create the date for the pupil's birthday in calendar year 2022 (not academic year)
- Work out what day of the week the pupil's birthday falls on
- Remember if the birthday falls on a Saturday or Sunday, we need to change the weekday to Friday
- Work out what month the pupil's birthday falls within
- Count how many birthdays there are on each weekday in each month
- Output the data
Author: Kelly Gilbert
Created: 2022-01-12
Requirements:
- input dataset:
- PD 2022 Wk 1 Input - Input.csv
- output dataset (for results check only):
- PD 2022 Wk 2 Output.csv
"""
import pandas as pd
#---------------------------------------------------------------------------------------------------
# input the data
#---------------------------------------------------------------------------------------------------
df = pd.read_csv(r'.\inputs\PD 2022 Wk 1 Input - Input.csv', parse_dates=['Date of Birth'],
usecols=['id', 'pupil first name', 'pupil last name', 'Date of Birth'])
#---------------------------------------------------------------------------------------------------
# process the data
#---------------------------------------------------------------------------------------------------
# format the pupil's name in First Name Last Name format (ie Carl Allchin)
df['Pupil Name'] = df['pupil first name'] + ' ' + df['pupil last name']
# create the date for the pupil's birthday in calendar year 2022 (not academic year)
df['This Year\'s Birthday'] = df['Date of Birth'].apply(lambda x: x.replace(year=datetime.now().year))
# birthday weekday and month
df['Cake Needed On'] = df['This Year\'s Birthday'].dt.day_name()\
.replace({'Saturday':'Friday', 'Sunday':'Friday'})
df['Month'] = df['This Year\'s Birthday'].dt.month_name()
# count how many birthdays there are on each weekday in each month
df['BDs per Weekday and Month'] = df.groupby(['Cake Needed On', 'Month'])['id'].transform('size')
#---------------------------------------------------------------------------------------------------
# output the file
#---------------------------------------------------------------------------------------------------
columns = ['Pupil Name', 'Date of Birth', 'This Year\'s Birthday', 'Month', 'Cake Needed On',
'BDs per Weekday and Month']
df.to_csv(r'.\outputs\output-2021-02.csv', index=False, columns=columns, date_format='%d/%m/%Y')
#---------------------------------------------------------------------------------------------------
# check results
#---------------------------------------------------------------------------------------------------
solution_files = ['PD 2022 Wk 2 Output.csv']
my_files = ['output-2021-02.csv']
col_order_matters = True
for i, solution_file in enumerate(solution_files):
print('---------- Checking \'' + solution_file + '\' ----------\n')
# read in the files
df_solution = read_csv('.\\outputs\\' + solution_file)
df_mine = read_csv('.\\outputs\\' + my_files[i])
# are the fields the same and in the same order?
solution_cols = list(df_solution.columns)
myCols = list(df_mine.columns)
if not col_order_matters:
solution_cols.sort()
myCols.sort()
col_match = False
if solution_cols != myCols:
print('*** Columns do not match ***')
print(' Columns in solution: ' + str(list(df_solution.columns)))
print(' Columns in mine : ' + str(list(df_mine.columns)))
else:
print('Columns match\n')
col_match = True
# are the values the same? (only check if the columns matched)
if col_match:
# round float values
s = df_solution.dtypes.astype(str)
for c in s[s.str.contains('float')].index:
df_solution[c] = df_solution[c].round(8)
df_mine[c] = df_mine[c].round(8)
# join the dataframes on all columns except the in flags
df_solution_compare = df_solution.merge(df_mine, how='outer',
on=list(df_solution.columns),
suffixes=['_solution', '_mine'], indicator=True)
if len(df_solution_compare[df_solution_compare['_merge'] != 'both']) > 0:
print('*** Values do not match ***\n')
print('In solution, not in mine:\n')
print(df_solution_compare[df_solution_compare['_merge'] == 'left_only'])
print('\n\n')
print('In mine, not in solution:\n')
print(df_solution_compare[df_solution_compare['_merge'] == 'right_only'])
else:
print('Values match')
print('\n')
#---------------------------------------------------------------------------------------------------
# profiling
#---------------------------------------------------------------------------------------------------
from pandas import concat
from pandas import offsets
import timeit
from pandas import to_datetime
df_big = read_csv(r'.\inputs\PD 2022 Wk 1 Input - Input.csv', parse_dates=['Date of Birth'],
usecols=['id', 'pupil first name', 'pupil last name', 'Date of Birth'])
df_big = concat([df_big]*1000)
# using replace
%timeit -n 1 -r 100 df_big['This Year\'s Birthday'] = df_big['Date of Birth'].apply(lambda x: x.replace(year=datetime.now().year))
# using offsets
%timeit -n 1 -r 100 df_big['This Year\'s Birthday'] = df_big['Date of Birth'] + offsets.DateOffset(year=2022)
# using string formatting
%timeit -n 1 -r 100 df_big['This Year\'s Birthday'] = to_datetime('2022-' + df_big['Date of Birth'].dt.strftime('%m-%d'))
|
9ed49fe07a6685a4401b7a9c7c64603e7c8346f1 | linfengzhou/LeetCode | /archive/python/Python/two_pointers/parition_array.py | 886 | 3.609375 | 4 | class Solution:
"""
@param: nums: The integer array you should partition
@param: k: An integer
@return: The index after partition
"""
def partitionArray(self, nums, k):
# write your code here
if not nums or len(nums) == 0:
return 0
left, right = 0, len(nums) -1
index = 0
while left < right:
# find the first left larger than k
while left < right and nums[left] < k:
left += 1
index += 1
while left < right and nums[left] == k:
left += 1
while left < right and nums[right] > k:
right -= 1
if left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
return index + 1 |
433506ca5d26ff24f8a4e9abce66732fe0eb8d9e | alzaia/applied_machine_learning_python | /evaluation_metrics/metrics_linear_regression.py | 1,407 | 3.5625 | 4 | # linear regression evaluation metrics on diabetes dataset
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import datasets
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.dummy import DummyRegressor
# load diabetes dataset
diabetes = datasets.load_diabetes()
X = diabetes.data[:, None, 6]
y = diabetes.target
# train linear regression and dummy models
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
lm = LinearRegression().fit(X_train, y_train)
lm_dummy_mean = DummyRegressor(strategy = 'mean').fit(X_train, y_train)
y_predict = lm.predict(X_test)
y_predict_dummy_mean = lm_dummy_mean.predict(X_test)
print('Linear model, coefficients: ', lm.coef_)
print("Mean squared error (dummy): {:.2f}".format(mean_squared_error(y_test, y_predict_dummy_mean)))
print("Mean squared error (linear model): {:.2f}".format(mean_squared_error(y_test, y_predict)))
print("r2_score (dummy): {:.2f}".format(r2_score(y_test, y_predict_dummy_mean)))
print("r2_score (linear model): {:.2f}".format(r2_score(y_test, y_predict)))
# Plot outputs
plt.scatter(X_test, y_test, color='black')
plt.plot(X_test, y_predict, color='green', linewidth=2)
plt.plot(X_test, y_predict_dummy_mean, color='red', linestyle = 'dashed', linewidth=2, label = 'dummy')
plt.show() |
0a3e0998719daba5314a2bbba9114e604a0a3417 | buy/leetcode | /python/93.restore_ip_address.py | 950 | 3.578125 | 4 | # Given a string containing only digits, restore it by returning all possible valid IP address combinations.
# For example:
# Given "25525511135",
# return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
import re
class Solution:
# @param s, a string
# @return a list of strings
# 11:04
def restoreIpAddresses(self, s):
output, temp = [], []
self.findSection(s, output, temp)
return output
def findSection(self, s, output, temp):
if len(temp) == 4:
if s:
return
else:
output.append('.'.join(temp))
return
for i in range(1, 4):
if i > len(s) or re.findall('^0\d+', s[:i]) or int(s[:i]) > 255:
return
temp.append(s[:i])
self.findSection(s[i:], output, temp)
temp.pop()
s = Solution()
print s.restoreIpAddresses('25525511155')
|
243b84cadc29a40c9a005151203e207cc1ed62c0 | iCiaran/hopson-weekly | /week3/main.py | 2,117 | 3.640625 | 4 | from maze import Maze
from PIL import Image, ImageDraw
from random import random
from math import sin,cos
from sys import exit
def main():
# Super basic config loading
config = load_config()
width = int(config[0])
height = int(config[1])
border = int(config[2])
length = int(config[3])
difficulty = max(min(int(config[4]),100),1)
solve = int(config[5]) == 1
gen_type = int(config[6])
file = config[7]
background_colour = config[8]
wall_colour = config[9]
path_colour = config[10]
# Load in image mask and resize to width and height
mask = Image.open(file).convert("RGB").resize((width, height))
# Create the image to draw to
image = Image.new("RGB", (width*length + 2*border,height*length + 2*border),
color=background_colour)
drawer = ImageDraw.Draw(image)
# Generation Functions
# 0 - random
# 1 - mask
# 2 - modulus
gen = [lambda c: c[0] + random()* (1+difficulty/20),
lambda c: c[1] if get_brightness(mask, c) < 0.5 else (c[0]+random()*(1+difficulty/20)),
lambda c: (c[0] * c[1]) % 10 + c[0] + random()*1.5]
# Generate and draw maze to image
maze = Maze(width, height, gen[gen_type])
print("Generated Maze")
maze.draw(drawer, length, border, wall_colour)
# Save maze image without solution
image.save("maze.png", "png")
print("Saved Maze")
if solve:
# Solve maze and draw path
path = maze.solve((0,0), (width-1,height-1))
print("Solved Maze")
maze.draw_path(path, drawer, length, border, path_colour)
# Save maze image with solution
image.save("maze_solved.png", "png")
print("Saved Maze With Solution")
def load_config(file="default.conf"):
'''Return a list of config values'''
return [line.split("=")[1].strip() for line in open(file)]
def get_brightness(i, xy):
'''Get human perceived brightness of a pixel'''
r,g,b = i.getpixel(xy)
luminance = (0.2126*r) + (0.7152*g) + (0.0722*b)
return luminance/255
if __name__ == '__main__':
main()
|
826d752b55a28b22dc312691579688766fcfa18d | cneal/ProjectWork | /graph.py | 5,750 | 3.5625 | 4 | import numpy as np
class Graph(object):
"""
Une classe generique pour representer un graphe comme un ensemble de
noeuds.
"""
def __init__(self, name='Sans nom'):
self.__name = name
self.__nodes = [] # Private. Array of nodes
self.__num_nodes = 0 # Private. Size of graph
self.__edges = []
self.__num_edges = 0
self.__adjacency_matrix = [] # initialize an empty adjacency matrix
self.__adjacency_matrix_dictionary = {} # initialize an empty adjacency matrix using a dictionary os distionary
def build_from_instance(self, instanceDict={}):
"""
It builds an Graph object from an given instance. The instance is encapsulated in a Dictionary data structure
@:param instanceDict: a dictionary containing information about the TSP problem
"""
if not instanceDict.keys():
print "Instance's dictionary not provided. Please provide a dictionary that contains instance's information."
return
from node import Node
from edge import Edge
self.__instance_dictionary = instanceDict
self.__name = instanceDict["header"]["NAME"] # name of the graph
self.__nodes = [] # Array of nodes
self.__num_nodes = 0 # Number of nodes
self.__edges = [] # Array of edges
self.__num_edges = 0 # Number of edges
self.__adjacency_matrix = [] # initialize an empty adjacency matrix
self.__adjacency_matrix_dictionary = {} # initialize an empty double dictionary adjacency object
# add nodes to the graph
for curNodeVal in xrange(0, instanceDict["header"]["DIMENSION"]):
new_node = Node(curNodeVal, instanceDict["nodes"][curNodeVal]) # create a new node instance
self.add_node(new_node) # add node to the graph
# add edges to graph
for tupleEdge in instanceDict["edges"]:
node_a_id = tupleEdge[0]
node_b_id = tupleEdge[1]
edge_weight = tupleEdge[2]
#if edge_weight > 0:
if node_a_id != node_b_id:
new_edge = Edge(self.__nodes[node_a_id], self.__nodes[node_b_id], edge_weight) # create edge
self.add_edge(new_edge)
def add_node(self, node):
"Add node to the graph"
self.__nodes.append(node)
self.__num_nodes += 1
def add_edge(self, edge):
"""
Add an edge to the graph.
"""
if len(self.__adjacency_matrix) == 0: # create an empty_adjacency_matrix & adjacency_matrix_dictionary if they doesnt exist yet
for dimension in range(1, self.__num_nodes + 1):
self.__adjacency_matrix.append([0] * self.__num_nodes) # size of matrix is (num_nodes) * (num_nodes)
for i in range(0, self.__num_nodes):
self.__adjacency_matrix_dictionary[self.__nodes[i]] = {} # add empty dictionary elements for each node
self.__adjacency_matrix_dictionary[self.__nodes[edge.get_node_a().get_id()]][
self.__nodes[edge.get_node_b().get_id()]] = edge
self.__adjacency_matrix_dictionary[self.__nodes[edge.get_node_b().get_id()]][
self.__nodes[edge.get_node_a().get_id()]] = edge # add edge to both directions
self.__edges.append(edge)
self.__num_edges += 1
def get_adjacency_matrix(self):
"""
:return: self.__adjacency_matrix
"""
return self.__adjacency_matrix
def get_adjacency_matrix_dictionary(self):
return self.__adjacency_matrix_dictionary
def get_name(self):
"Donne le nom du graphe."
return self.__name
def get_nodes(self):
"Donne la liste des noeuds du graphe."
return self.__nodes
def get_num_nodes(self):
"Return the number of nodes in the graph"
return self.__num_nodes
def get_edges(self):
""":return: self.__edges"""
return self.__edges
def get_graph_weight(self):
"""
:return: int - the weight of the graph
"""
weight = 0
for e in self.__edges:
weight += e.get_edge_weight()
return weight
def get_graph_dictionary(self):
""""
Returns a dictionary structure of the Graph. This dictionary structure is the same as what is returned
by the function read_stsp.get_stsp_data() in order to reuse the logic from the plotting of the graph.
This dictionary can be used as an input to Graph_Plotter.py
"""
nodes = {}
n = 0
for node in self.__nodes:
nodes[n] = tuple(node.get_data())
n += 1
edges = set()
for edge in self.__edges:
new_edge = (edge.get_node_a().get_id(), edge.get_node_b().get_id())
edges.add(new_edge)
graph_dict = {}
graph_dict["nodes"] = nodes
graph_dict["edges"] = edges
return graph_dict
def __repr__(self):
name = self.get_name()
nb_nodes = self.get_num_nodes()
#print nodes
s = 'Graph %s has %d nodes' % (name, nb_nodes)
for node in self.get_nodes():
s += '\n ' + repr(node)
#print edges
s += '\n\nGraph %s has %d edges \n' % (name, self.__num_edges)
n = 1
for edge in self.__edges:
s += str(n) + ': ' + repr(edge) + "\n"
n += 1
#print the weight of the graph
s += '\nGraph has weight: %d \n' % (self.get_graph_weight())
return s
if __name__ == '__main__':
from node import Node
G = Graph(name='Graphe test')
for k in range(5):
G.add_node(Node(name='Noeud test %d' % k))
print G
|
d6e0a4089398c8fcbfc850663720d82446b5ca43 | sonikku10/3vs5 | /untitled/Project Euler #1.py | 508 | 4.65625 | 5 | # ------
print("This program will take a number, x, then add up all multiples of 3 and 5 up to that number and")
print("display it.")
print("")
# ------
# Input
x = int(input("Go ahead and enter a positive integer: "))
# Set your current sum
my_sum = 0
for i in range(0, x):
if i % 3 == 0 or i % 5 == 0:
my_sum += i
i += 1
# The print() function goes out side of your loop so it doesn't display each iteration up to the end.
# It will only display the final iteration.
print(my_sum)
|
524860c56a8e490fa923a81aeae444b954e7a9a9 | Likhi-organisations/100-days | /pattern numbers.py | 180 | 3.671875 | 4 | n=5
x=1
for i in range(1,n+1):
for j in range(n,i,-1):
print(' ' ,end='')
for k in range(1,x+1):
print(abs(k-i),end='')
x+=2
print()
|
a6199602fa7912d4be188e2e4b2e5cb62152bd7d | nilsso/challenge-solutions | /exercism/python/pig-latin/pig_latin.py | 422 | 3.9375 | 4 | import re
# 1. a vowel (that isn't u)
# 2. u if it's proceeded by q
# 3. x or y if followed by a consonant
p = re.compile("[aeio]|(?<!q)u|[xy](?![aeiou])")
def translate_word(word):
s = p.search(word).start()
return word[s:]+word[:s]+"ay"
def translate(text):
return (" ".join(map(translate_word, text.lower().split())))
if __name__ == "__main__":
from sys import argv
print(translate(argv[1]))
|
2268ef5387bdb0db374fad226d58f5068b99766d | AdityaShidlyali/Python | /Learn_Python/Chapter_12/2_args_with_normal_parameter.py | 267 | 3.546875 | 4 | # *args with the normal parameters
def tot_all(num, *args) : # the first '2' from the formal parameter will not be considered as the args it will be considered as the num
total = 0
for i in args :
total += i
print(total)
tot_all(2, 2, 2, 2) |
1962cddcd2c28af37f3d174c8dbafe7aa6c878be | Easoncer/swordoffer | /栈的实现.py | 972 | 4.125 | 4 | class stacklist:
def __init__(self):
self.slist=[]
self.top=None
def push(self,x):
self.slist.append(x)
self.top=len(self.slist)-1
def pop(self):
if len(self.slist)==0:
return 'stack is empty!'
temp=self.slist.pop()
self.top-=1
return temp
def isEmpty(self):
return True if not len(self.slist) else False
def print_stack(self):
for i in self.slist:
print i
# print self.top
# using stack to realize the queue
class queuelist:
def __init__(self):
self.s1=stacklist()
self.s2=stacklist()
def enqueue(self,x):
self.s1.push(x)
def dequeue(self):
# if self.s1
if self.s1.isEmpty():
return None
while not self.s1.isEmpty():
self.s2.push(self.s1.pop())
temp=self.s2.pop()
while not self.s2.isEmpty():
self.s1.push(self.s2.pop())
return temp
def print_queue(self):
self.s1.print_stack()
if __name__=="__main__":
q1=queuelist()
q1.enqueue(5)
q1.enqueue(4)
q1.enqueue(3)
q1.dequeue()
q1.print_queue()
|
fd0f820c96618fc7959f9cf5c006eded6dcc295a | clonbg/Curso-python-Manuel-J-Davila | /ficheros.py | 483 | 3.703125 | 4 | # w escribe y reemplaza si existe
# a escribe si no existe y añade al final
# r leer
fichero = open('fichero.txt', 'w')
texto = 'Vamos a escribir una línea'
fichero.write(texto)
fichero.close()
fichero = open('fichero.txt', 'a')
texto = '\nVamos a escribir otra línea'
fichero.write(texto)
fichero.close()
fichero = open('fichero.txt', 'r')
print(fichero.read())
fichero.close()
fichero = open('fichero.txt', 'r')
for item in fichero:
print(item, end='')
fichero.close()
|
cfd30dd8aee84042558bd87b5b27cd5550cf2759 | cecetsui/pygameAndProjects | /cityScroller.py | 7,358 | 4.3125 | 4 | #Import needed modules
import pygame
import random
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREY = (129, 129, 129)
colors = [BLACK, GREEN, BLUE, RED]
#Helper function : Provides random color
def random_color():
return random.choice(colors)
# Initialize the pygame class
pygame.init()
# Set the width and height of the screen [width, height]
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# Set the title of the window
pygame.display.set_caption("CityScroller")
# Loop until the user clicks the close button.
done = False
# Manage how fast the screen updates
clock = pygame.time.Clock()
class Building():
"""
Used to create the building object
It takes:
x_point - an integer that represents where along the x-axis the building will be drawn
y_point - an integer that represents where along the y-axis the building will be drawn
Together the x_point and y_point represent the top, left corner of the building
width - an integer that represents how wide the building will be in pixels.
A positive integer draws the building right to left().
A negative integer draws the building left to right ().
height - an integer that represents how tall the building will be in pixels
A positive integer draws the building up
A negative integer draws the building down
color - a tuple of three elements which represents the color of the building
Each element being a number from 0 - 255 that represents how much red, green and blue the color should have.
It depends on:
pygame being initialized in the environment.
It depends on a "screen" global variable that represents the surface where the buildings will be drawn
"""
def __init__(self, x_point, y_point, width, height, color):
#Initializing
self.x_p = x_point
self.y_p = y_point
self.w = width
self.h = height
self.c = color
def draw(self):
#uses pygame and the global screen variable to draw the building on the screen
pygame.draw.rect(screen, self.c, [self.x_p, self.y_p, self.w, self.h])
def move(self, speed):
"""
Takes in an integer that represents the speed at which the building is moving
A positive integer moves the building to the right
A negative integer moves the building to the left
Moves the building horizontally across the screen by changing the position of the
x_point by the speed
"""
self.x_p -= speed
class Scroller(object):
"""
Used to create the group of buildings to fill the screen and scroll
It takes:
width - an integer that represents in pixels the width of the scroller
This should only be a positive integer because a negative integer will draw buildings outside of the screen
height - an integer that represents in pixels the height scroller
A negative integer here will draw the buildings upside down.
base - an integer that represents where along the y-axis to start drawing buildings for this
A negative integer will draw the buildings off the screen
A smaller number means the buildings will be drawn higher up on the screen
A larger number means the buildings will be drawn further down the screen
To start drawing the buildings on the bottom of the screen this should be the height of the screen
color - a tuple of three elements which represents the color of the building
Each element being a number from 0 - 255 that represents how much red, green and blue the color should have.
speed - An integer that represents how fast the buildings will scroll
It depends on:
A Building class being available to create the building obecjts.
The building objects should have "draw" and "move" methods.
Other info:
It has an instance variable "buildings" which is a list of buildings for the scroller
"""
def __init__(self, width, height, base, color, speed):
self.w = width
self.h = height
self.b = base
self.c = color
self.s = speed
self.buildings = []
self.add_buildings()
def add_buildings(self):
#Will call add_building until there the buildings fill up the width of the scroller.
cwidth = 0
while (cwidth <= self.w):
self.add_building(cwidth)
cwidth += self.buildings[-1].w
def add_building(self, x_location):
"""
takes in an x_location, an integer, that represents where along the x-axis to
put a buildng.
Adds a building to list of buildings.
"""
building_width = random.randint((self.w // 20), (self.w // 4))
max_height = self.b - self.h # this sets the maximum height each building can be
# The building height will be a random integer between 1/4th and just under the max_height
building_height = random.randint((max_height // 4), (max_height - 1))
y_location = self.b - building_height # This tells the building where along the y-axis to draw itself
self.buildings.append(Building(x_location, y_location, building_width, building_height, self.c))
def draw_buildings(self):
#This calls the draw method on each building.
for build in self.buildings:
build.draw()
def move_buildings(self):
"""
This calls the move method on each building passing in the speed variable
As the buildings move off the screen a new one is added.
"""
for build in self.buildings:
build.move(self.s)
new_building_location = self.buildings[-1].x_p + self.buildings[-1].w
self.add_building(new_building_location)
#Define colors of the scrollers
FRONT_SCROLLER_COLOR = (0,0,30)
MIDDLE_SCROLLER_COLOR = (30,30,100)
BACK_SCROLLER_COLOR = (50,50,150)
BACKGROUND_COLOR = (17, 9, 89)
#Creating Scroller objects
front_scroller = Scroller(SCREEN_WIDTH, 500, SCREEN_HEIGHT, FRONT_SCROLLER_COLOR, 3)
middle_scroller = Scroller(SCREEN_WIDTH, 200, (SCREEN_HEIGHT - 50), MIDDLE_SCROLLER_COLOR, 2)
back_scroller = Scroller(SCREEN_WIDTH, 20, (SCREEN_HEIGHT - 100), BACK_SCROLLER_COLOR, 1)
# -------- Main Program Loop -----------
while not done:
# --- Main event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# --- Game logic: Move the scrollers to new position (move buildings)
back_scroller.move_buildings()
middle_scroller.move_buildings()
front_scroller.move_buildings()
# --- Screen-clearing: Clear screen and redraw to make the allusion it is moving
screen.fill(BACKGROUND_COLOR)
# --- Redraw the buildings after moving and clearing screen
back_scroller.draw_buildings()
middle_scroller.draw_buildings()
front_scroller.draw_buildings()
# --- Go ahead and update the screen with what was drawn
pygame.display.flip()
# --- Limit to 60 frames per second
clock.tick(60)
# Close the window and quit.
pygame.quit()
exit() # Needed when using IDLE
|
c92f4b5edc98427e15770e024765efafc2233240 | Balaji0112/System-design-programmer | /Loop_detection.py | 744 | 3.90625 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def append(self,new_data):
new_node=Node(new_data)
new_node.next=self.head
self.head=new_node
def detect_loop(self):
s=set()
temp=self.head
while(temp):
if(temp in s):
print(temp.data)
return True
s.add(temp)
temp=temp.next
return False
llist=LinkedList()
for i in [int(i) for i in input().split()]:
llist.append(i)
llist.head.next.next.next.next=llist.head
if(llist.detect_loop()):
print("Loop found")
else:
print("No Loop")
|
27328a55e926a3c3f1b5695605f3d346221c396c | JackMGrundy/coding-challenges | /common-problems-leetcode/medium/subarray-sum-equals-k.py | 2,105 | 3.953125 | 4 | """
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
Accepted
96,129
Submissions
228,367
"""
# 89th percentile. 56ms.
# builtins.
from itertools import accumulate
from collections import defaultdict
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
if not nums: return 0
res = 0
matches = defaultdict(int)
matches[k] = 1
forward = list(accumulate(nums))
for x in forward:
if x in matches:
res += matches[x]
matches[x+k] += 1
return res
# 89th percentile. 56ms.
# no builtins
from collections import defaultdict
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
if not nums:
return 0
res = 0
matches = defaultdict(int)
matches[k] = 1
sm = 0
for n in nums:
sm += n
if sm in matches:
res += matches[sm]
matches[sm + k] += 1
return res
"""
Notes:
Say you have an arr and you have an array with cumulative sums for the array. Now let's say there are two
cumulative sums that are the same. That means the sum of the values between them must be 0.
Extending this, say the different between the two is k, then the array between them must be k.
So for every cumulative sum, we make that sum+k in a hashtable. Now we know that if we later see
such a sum, we've found an array with sum k.
Final bits
1) We don't just mark that we've seen this cumulative sum. Rather we count how many such
cumulative sums we've seen.
2) We need to mark matches[k] equal to 1 to start. To see why we need this, imagine we didn't have it. We
might march through an array with a sum equal to k, and we wouldn't recognize it as a match.
""" |
b2b9038c6ec5060902b93fb90a2abfef362dd5e3 | faiqashraf32/PersonalProjects | /Logica/main.py | 7,287 | 4.125 | 4 | class Logica:
def start(self):
# welcome user
print("Welcome to Logica!\n")
# seek user input
# a,b,c,d,e,f = [],[],[],[],[],[]
self.a = []
self.b = []
self.c = []
self.d = []
self.e = []
self.f = []
self.u = [] # universal set
a.editSet()
def editSet(self):
self.setEdit = input("Which set would you like to edit? (a-f) or universe (u) >> ")
if self.setEdit == "a":
print("Editing set a. Please enter values, when finished, enter 'stop' \n")
entry = ""
while True:
entry = input("give me something >>> ")
if entry != "stop":
self.a.append(entry)
print("I have added " + entry + " to the set a.\n")
else:
# display values in a
print(self.u)
a.whatNow()
elif self.setEdit == "b":
print("Editing set b. Please enter values, when finished, enter 'stop' \n")
entry = ""
while True:
entry = input("give me something >>> ")
if entry != "stop":
self.b.append(entry)
print("I have added " + entry + " to the set b.\n")
else:
# display values in b
print(self.b)
a.whatNow()
elif self.setEdit == "c":
print("Editing set c. Please enter values, when finished, enter 'stop' \n")
entry = ""
while True:
entry = input("give me something >>> ")
if entry != "stop":
self.c.append(entry)
print("I have added " + entry + " to the set c.\n")
else:
# display values in c
print(self.c)
a.whatNow()
elif self.setEdit == "d":
print("Editing set d. Please enter values, when finished, enter 'stop' \n")
entry = ""
while True:
entry = input("give me something >>> ")
if entry != "stop":
self.d.append(entry)
print("I have added " + entry + " to the set d.\n")
else:
# display values in d
print(self.d)
a.whatNow()
elif self.setEdit == "e":
print("Editing set e. Please enter values, when finished, enter 'stop' \n")
entry = ""
while True:
entry = input("give me something >>> ")
if entry != "stop":
self.e.append(entry)
print("I have added " + entry + " to the set e.\n")
else:
# display values in e
print(self.e)
a.whatNow()
elif self.setEdit == "f":
print("Editing set f. Please enter values, when finished, enter 'stop' \n")
entry = ""
while True:
entry = input("give me something >>> ")
if entry != "stop":
self.f.append(entry)
print("I have added " + entry + " to the set f.\n")
else:
# display values in f
print(self.f)
a.whatNow()
elif self.setEdit == "u":
print("Editing set u. Please enter values, when finished, enter 'stop' \n")
entry = ""
while True:
entry = input("give me something >>> ")
if entry != "stop":
self.u.append(entry)
print("I have added " + entry + " to the set u.\n")
else:
# display values in u
print(self.u)
a.whatNow()
def whatNow(self):
print("Here are your options: \n")
go = input("To overwrite a set, enter 1\nTo use union, enter 2\nTo use intersection, enter 3.\nTo check compliments, enter 4.\nTo quit, enter any other key.\n")
if go == "1":
a.editSet()
elif go == "2":
a.union()
elif go == "3":
a.intersect()
else:
exit(0)
def union(self):
self.uWho = []
entry = ""
while True:
entry = input("Which set you want to unionize? (a-f, enter stop to end) >> ")
if entry != "stop":
if entry == "a":
self.uWho.append(self.a)
elif entry == "b":
self.uWho.append(self.b)
elif entry == "c":
self.uWho.append(self.c)
elif entry == "d":
self.uWho.append(self.d)
elif entry == "e":
self.uWho.append(self.e)
elif entry == "f":
self.uWho.append(self.f)
else:
# print the union
print(self.uWho)
uWho = []
a.whatNow()
def intersect(self):
print("Welcome to intersect Checker!\n")
self.check = []
self.entry = ""
# figure out what sets we want to check for intersection
self.entry = input("What sets do you want to check for intersection (a-f)? Enter response with no spaces and lowercase letters (e.g. abc) >> ")
# figure out what the heck they just entered
self.x = [] # this will store each set value individually
for char in self.entry:
self.x.append(char)
# new container to store the list of the sets we want to find intersection with
self.z = {}
for p in (self.x):
if p == "a":
# we know a is one set
self.z.append(a)
if p == "b":
self.z.append(b)
if p == "c":
self.z.append(c)
if p == "d":
self.z.append(d)
if p == "e":
self.z.append(e)
if p == "f":
self.z.append(f)
# so now that we know what sets we want to find the intersection of, we can go ahead and find the intersection
self.inter = set.intersection(*self.z)
print("The intersection of the sets is: " + str(self.inter))
exit(0)
a.whatNow() # return to main menu
# while entry != "stop":
# entry = input("Which set would you like to check for intersection? >> ")
# # store user input
# self.check.append(entry)
# # lets figure out what they entered above so that we check for intersection in the right sets
# self.sets = [a,b,c,d,e,f]
# self.go = [] # this will contain the sets that we want to check for intersection
# for p in self.check:
# if p in self.sets:
# self.go.append(p)
# # now we check for intersection
# for x,y in zip(self.go)
if __name__ == "__main__":
a = Logica()
a.start() |
99120d8b935daca2990959db1686d67bc656a844 | btrif/Python_dev_repo | /BASE SCRIPTS/generators.py | 3,865 | 3.96875 | 4 |
print('--------------the SIMPLEST POSSIBLE GENERATOR ------------------------')
s = 'abc'
IT = s.__iter__() # or IT = iter(s)
# function returns an iterator object that defines the method __next__()
print('IT, function returns an iterator object that defines the method __next__() :\t\t ', IT )
print('next item : ', IT.__next__() ) # which accesses elements in the container one at a time.
print('next item : ', next(IT) ) # IT.__next__() and next(IT) are equivalent
print('\n--------------------------------------')
def Blum_Blum_Shub_gen(): # EFFICIENT GENERATOR
''' s_0 = 290797
s_(n+1) = s_n×s_n (modulo 50515093)
t_n = s_n (modulo 500) '''
s = 290797
while True :
s = pow(s, 2 , 50515093 )
t = s % 500
yield t
B = Blum_Blum_Shub_gen()
for i in range(12): print( next(B),end=' ; ')
print(next(B), next(B), next(B), next(B) )
print('\n---------------- Same Generator in a simpler way ---------------------')
SMOD = 50515093
TMOD = 500
def blum(pmod=TMOD):
s = 290797
while True:
s = pow(s, 2, SMOD)
yield s % pmod
B2 = blum()
for i in range(16) : print(next(B2), end=' ; ')
def bbs_prng(s=290797, m_s=50515093, m_t=500):
while 1:
s = (s * s) % m_s
yield s % m_t
print('\n\n------------------ RECURSIVE GENERATOR ------------------')
# RECURSIVE GENERATOR
def orduples(size, start, stop, step=1):
if size == 0:
yield ()
elif size == 1:
for x in range(start, stop, step):
yield (x,)
else:
for u in orduples(size - 1, start, stop, step):
for x in range(u[-1], stop, step):
yield u + (x,)
if __name__ == "__main__":
print(list(orduples(3, 0, 5)))
print('\n\n------------------ RECURSIVE GENERATOR - MULTIRANGE ------------------')
print('\n\n------------------ RECURSIVE GENERATOR - Number Partition ------------------')
def partition_nr_into_given_set_of_nrs_limit(nr, S, m=10):
'''Recursive function to partition a number into a given set of numbers
and also having an upper limit lim of the partition length.
:param nr: int, nr to partition, example : 109
:param S: set of numbers used for partitioning
:param m: int, limit, example m=10 represents the maximum partition length
:return: list of partitions , list of lists
'''
nrs = sorted(S, reverse=True)
def inner(n, i, m):
if m >= 0:
if n == 0:
yield []
for k in range(i, len(nrs)):
if nrs[k] <= n:
for rest in inner(n - nrs[k], k, m - 1):
yield [nrs[k]] + rest
return list(inner(nr, 0, m))
P = partition_nr_into_given_set_of_nrs_limit( 810, [ 1, 4, 9, 16, 25, 36 ,49, 64, 81 ], 11 )
print(P)
print('\n--------------------------- Unique Permutations ------------------------ ')
X = [49, 36, 25, 16, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1]
def unique_permutations(lst): # VERY EFFECTIVE
''':Description: Takes a list and makes ONLY Unique Permutations of a list with repeated elements.
If one tries itertools.permutations on a list with 14 elements ==> BANG, computer freezes
:param lst: type list
:return: a list of lists containing all the permutations
'''
if len(lst) == 1:
yield (lst[0],)
else:
unique_lst = set(lst)
for first_element in unique_lst:
remaining_lst = list(lst)
remaining_lst.remove(first_element)
for sub_permutation in unique_permutations(remaining_lst):
yield (first_element,) + sub_permutation
K = unique_permutations(X)
print(K)
# for cnt, i in enumerate(K): print(str(cnt) +'. ', next(K) ) |
3097a88421e23a48afba0ee24cf33c3059087f41 | xibaochat/crescendo_projects | /guess_the_number/baobe.py | 664 | 3.90625 | 4 | def compare_num():
import random
random_num = random.randint (0, 10000)
try:
user_give_number = int (input ('please enter a number:'))
except:
print ('please enter an integer!')
while(random_num != user_give_number):
if random_num < user_give_number:
print ('too high, try again')
user_give_number = int(input('please enter a number:'))
elif random_num > user_give_number:
print ('too low, try again')
user_give_number = int(input('please enter a number:'))
else:
print('felicitation!')
break
compare_num()
|
a53e0b591ae5a72ae93ddd5d53b4a03dee86bb84 | AyrtonDev/Curso-de-Python | /aula09.py | 675 | 4.1875 | 4 | # Aula que trata sobre tratamento de strings
frase = 'Curso em Video Python'
print(frase[9])
print(frase[9:14])
print(frase[9:21])
print(frase[9:21:2])
print(frase[:5])
print(frase[15:])
print(frase[9::3])
print(len(frase))
print(frase.count('o'))
print(frase.count('o',0,13))
print(frase.find('deo'))
print(frase.find('Android'))
print('Curso' in frase)
print(frase.replace('Python', 'Android'))
print(frase.upper())
print(frase.lower())
print(frase.capitalize())
print(frase.title())
frase1 = ' Aprenda Python '
print(frase1.strip())
print(frase1.rstrip())
print(frase1.lstrip())
frase2 = frase.split()
print(frase2)
print('-'.join(frase2))
|
963af2ccfcb9feb468d4ad7cc39447976abe868c | hankyeolk/PythonStudy | /sorting/binary search.py | 1,210 | 4 | 4 | # 이분 탐색
'''
1. 중간 위치를 찾는다
2. 찾는 값과 중간 위치 값을 비교한다
3. 같다면 원하는 값 찾은 것
4. 찾는 값이 중간 값보다 크다면 오른쪽을 대상으로 1번부터 반복
5. 찾는 값이 중간 값보다 작다면 왼쪽을 대상으로 1번부터 반복
* 이분 탐색은 미리 정렬된 리스트의 자료를 가지고만 할 수 있다.
'''
# ver1
def binary_search(a, x):
start = 0
end = len(a) - 1
while start <= end:
mid = (start + end) // 2
if x == a[mid]:
return mid
elif x > a[mid]:
start = mid + 1
else:
end = mid - 1
return -1 # 찾는 값이 없으면 -1의 값을 가진다.
example = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print(binary_search(example, 64))
# ver2 (재귀함수 사용)
def binary_sub(a, x, start, end):
if start > end:
return -1
mid = (start + end) // 2
if x == a[mid]:
return mid
elif x > a[mid]:
return binary_sub(a, x, mid + 1, end)
else:
return binary_sub(a, x, start, mid - 1)
return -1
def binary(a, x):
return binary_sub(a, x, 0, len(a) - 1)
example2 = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
t = binary(example2, 64)
print(t) |
eed9e3c5784097a60c2a0d6c942303bb1808cfa8 | nathanesau/data_structures_and_algorithms | /_courses/cmpt225/practice4-solution/question14.py | 407 | 4 | 4 | """
write an algorithm that gets two binary trees
and checks if they have the same inOrder traversal.
"""
from binary_tree import in_order, build_tree7
def are_equal_in_order(tree1, tree2):
in_order1 = in_order(tree1)
in_order2 = in_order(tree2)
return in_order1 == in_order2
if __name__ == "__main__":
# test tree7
tree7 = build_tree7()
print(are_equal_in_order(tree7, tree7))
|
c5171d47acad85b24b821a97ff19fd5cf6440953 | Ing-Josef-Klotzner/python | /2017/hackerrank/root_with_min_height_(graph_center).py | 1,501 | 4.0625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
from collections import deque
# find root for minimum height to tree (root = graph center)
# Graph is an undirected graph with adjacency list representation
class Graph:
def __init__ (self, V):
self.V = V
self.adj = [[] for i in range (V + 1)]
self.deg = [0 for i in range (V + 1)]
def addEdge (self, v, w):
self.adj [v].append (w) # Adds w to v's list
self.adj [w].append (v) # Adds v to w's list
self.deg [v] += 1 # increment degree of v by 1
self.deg [w] += 1 # increment degree of w by 1
# Method to return roots which gives minimum height to tree
def rootForMinimumHeight (self):
q = deque ()
for i in range (self.V + 1): # all leaves to queue
if self.deg [i] == 1: q.append (i)
while self.V > 2:
for _ in range (len (q)):
lv = q.popleft ()
self.V -= 1
for j in self.adj [lv]: # for all leave neighbours
print (self.adj [lv])
self.deg [j] -= 1
if self.deg [j] == 1: q.append (j)
return q
# Driver code to test above methods
#g = Graph (6)
#g.addEdge (0, 3)
#g.addEdge (1, 3)
#g.addEdge (2, 3)
#g.addEdge (4, 3)
#g.addEdge (5, 4)
g = Graph (5)
g.addEdge (1, 3)
g.addEdge (2, 3)
g.addEdge (3, 4)
g.addEdge (4, 5)
res = g.rootForMinimumHeight ()
for i in res:
print (i, end = ", ")
print ("are center nodes")
|
609679da2132f8f4f39e85043802a692d33ff7b1 | RobertGuerra/Projects | /Edabit Practice Problems/A-G/Find Nemo.py | 397 | 4.09375 | 4 | def find_nemo(sentence):
i = 1
sentence = sentence.split(" ")
for word in sentence:
if word == 'Nemo' or word == 'nemo':
return "I found Nemo at {}!".format(i)
i += 1
return "I can't find Nemo :("
print(find_nemo('No nemo here!'))
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n-1)
print(factorial(9))
|
7b1d357f50a754ab772653d318272421972ddd5e | Sun0921/untutled1 | /jump7(1).py | 169 | 3.734375 | 4 | i=1
while i<101:
a = int(input("请您输入一个数字:"))
if a%7==0 or a%10==7 or a//10==7:
print("跳过")
else:
print(a)
i+=1 |
cd61518d2b2a8c962ff487aa3938e07b8bc474d4 | mali44/PythonNetworkScripts | /BruteFoceFTP.py | 671 | 3.53125 | 4 | import urllib, sys
import ftplib
from ftplib import FTP
urllib.FancyURLopener.version = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36'
_link = 'ftp.barankaraboga.com'
_user = '[email protected]'
ftp = FTP(_link)
f = open('passwordlist.txt','r')
xmas = f.readlines()
for i in xmas:
i = i.strip()
try:
print('şifre deneniyor : ', str(i))
ftp.login(user=_user,passwd=i)
print('deneme başarılı')
ftp.quit()
sys.exit()
except ftplib.error_perm as e:
print('giriş başarısız!')
print('[-] DENENEN ŞİFRE SAYISI ' + str(len(xmas)) + ', EŞLEŞME YOK.')
|
89e992ca9f261c8fa9db4f444b1a7f8a7a0c00e6 | RohanMiraje/DSAwithPython | /DSA/tree/bst.py | 20,814 | 4.34375 | 4 | import sys
class Node:
"""
Binary tree node with three instance attributes
data: holds key/value inserted in node
left: reference to left child node
right: reference to right child node
"""
def __init__(self, key):
self.data = key
self.left = None
self.right = None
class BSTTree:
"""
search, insert, delete operations in BST are O(log(h)), h-height of tree -->in avg case
if BST is either left or right skewed then these operations takes O(n) time
height of single node is zero
height of empty tree is -1
"""
def __init__(self):
self.root = None
def insert(self, root, key):
"""
Idea is to insert key in BST is to follow BST property while inserting
In recursive approach:
insert(root, key):
check if root is None
then insert new node and assign its ref to this root
and return this root to caller
root = get_new_node(key)
return root
check if key is less than or equal to current root data:
then recursively call on left subtree
root.left = insert(root.left, key)
else:
call then recursively call on right subtree
root.right = insert(root.right, key)
finally return root
return root
:param root: root of BST
:param key: key/value to be inserted in BST
:return: root
"""
if root is None:
root = BSTTree.get_new_node(key)
return root
if key <= root.data:
root.left = self.insert(root.left, key)
else:
root.right = self.insert(root.right, key)
return root
def insert_iterative(self, key):
"""
TODO: check how to implement it
:param key:
:return:
"""
if self.root is None:
self.root = BSTTree.get_new_node(key)
return
curr = self.root
if key <= self.root.data:
if self.root.left is None:
self.root.left = BSTTree.get_new_node(key)
return
else:
if self.root.right is None:
self.root.right = BSTTree.get_new_node(key)
return
if key > curr.data:
while curr.right:
curr = curr.right
curr.right = BSTTree.get_new_node(key)
else:
while curr.left:
curr = curr.left
curr.left = BSTTree.get_new_node(key)
@staticmethod
def get_new_node(key):
return Node(key)
def inorder(self, root):
if root is None:
return
self.inorder(root.left)
print(root.data, end=' ')
self.inorder(root.right)
def preorder(self, root):
if root is None:
return
print(root.data, end=' ')
self.preorder(root.left)
self.preorder(root.right)
def iterative_pre(self):
"""
Idea is to use stack while traversing in pre-order
curr = self.root
keep traversing left subtree
while curr:
print(curr.data)
if it has right node
push it to stack
curr = curr.left
if curr is None and stack:
curr = stack.pop()
:return:
"""
if self.root is None:
return
curr = self.root
stack = []
while curr:
print(curr.data, end=' ')
if curr.right:
stack.append(curr.right)
curr = curr.left
if curr is None and stack:
curr = stack.pop()
def postorder(self, root):
if root is None:
return
self.postorder(root.left)
self.postorder(root.right)
print(root.data, end=' ')
def post_order_iterative(self):
from collections import defaultdict
if self.root is None:
return
node_to_its_occurrence_map = dict()
stack = list()
stack.append(self.root)
while stack:
temp = stack[-1]
if node_to_its_occurrence_map.get(temp, 0) == 0:
if temp.left:
node_to_its_occurrence_map[temp] = 0
stack.append(temp.left)
elif node_to_its_occurrence_map.get(temp) == 1:
if temp.right:
stack.append(temp.right)
elif node_to_its_occurrence_map.get(temp) == 2:
print(temp.data, end=' ')
else:
stack.pop()
node_to_its_occurrence_map[temp] = node_to_its_occurrence_map.get(temp, 0) + 1
def delete(self, root, key):
if root is None:
return
if root.data > key:
root.left = self.delete(root.left, key)
elif root.data < key:
root.right = self.delete(root.right, key)
else:
# found case
if root.left is None and root.right is None:
# case 1: node is leaf node
del root
root = None
elif root.left is None:
# case 2: node have a child
temp = root
root = root.right
del temp
elif root.right is None:
# case 2: node have a child
temp = root
root = root.left
del temp
else:
# case 3: node have two children
new_root_data = self.find_min(root.right)
root.data = new_root_data
root.right = self.delete(root.right, new_root_data)
return root
def find_min(self, root):
if root and root.left is None:
return root.data
if root is None:
return -1
data = self.find_min(root.left)
return data
def find_max(self, root):
if root and root.right is None:
return root.data
if root is None:
return -1
data = self.find_max(root.right)
return data
def search(self, root, key):
if root is None:
return False
elif root.data == key:
return True
elif root.data < key:
return self.search(root.right, key)
else:
return self.search(root.left, key)
def search_iterative(self, key):
if self.root is None:
return False
curr = self.root
while curr:
if curr.data == key:
return True
if curr.data < key:
curr = curr.right
else:
curr = curr.left
return False
def find_height_of_tree(self, root):
"""
Idea is to use recursion and get max of height of left-subtree and right-subtree
and add 1 to it
If root is None it return -1 ....assuming height of empty tree as -1
:param root:
:return:
"""
if root is None:
return -1
return max(self.find_height_of_tree(root.left), self.find_height_of_tree(root.right)) + 1
def level_order_traversal(self):
print('level order traversal using queue')
if self.is_empty():
print('BST is empty')
return
queue = list()
queue.append(self.root)
while queue:
curr = queue.pop(0)
print(curr.data, end=' ')
if curr.left:
queue.append(curr.left)
if curr.right:
queue.append(curr.right)
print('')
def level_order_traversal_line_by_line(self, left_view_only=False):
"""
Idea is to use for level order traversal using queue
To print level line by line
size = use queue size # this line is IMP, it would be wrong to iterate over direct queue and not its size
iterate over queue size
curr = dequeue
print curr.data
insert curr.left and curr.right node to queue if exists
:param left_view_only:
:return:
"""
print('level_order_traversal_line_by_line using queue')
if self.is_empty():
print('BST is empty')
return
queue = list()
queue.append(self.root)
while queue:
size = len(queue)
for i in range(size):
curr = queue.pop(0)
if left_view_only is True:
# print only first(left) node in each level
if i == 0:
print(curr.data, end=' ')
else:
# print all nodes in level in a line
print(curr.data, end=' ')
if curr.left:
queue.append(curr.left)
if curr.right:
queue.append(curr.right)
print('')
print('')
def spiral_level_order_traversal(self):
"""
Idea is to use line by line level order traversal using queue and also use stack
while queue is not empty
iterate over curr size of queue
If level is even then push left and then right nodes to stack
and if level is odd then push right and and then left nodes to stack
while stack is not empty
pop and enqueue to queue
:return:
"""
print('spiral_level_order_traversal')
# TODO: please study and come back to me
if self.is_empty():
return
queue = list()
stack = list()
queue.append(self.root)
level = 0
while queue:
size = len(queue)
for i in range(size):
curr = queue.pop(0)
print(curr.data, end=' ')
if level % 2 == 1:
if curr.right:
stack.append(curr.right)
if curr.left:
stack.append(curr.left)
else:
if curr.left:
stack.append(curr.left)
if curr.right:
stack.append(curr.right)
while stack:
queue.append(stack.pop())
level += 1
print('')
def right_view(self):
"""
Idea is to use same concept for level order traversal using queue
To print right view of tree
size = use queue size # this line is IMP, it would be wrong to iterate over direct queue and not its size
iterate over queue size
curr = dequeue
if i== size -1 # this is IMP, to consider last node of each level
print curr.data
insert curr.left and curr.right node to queue if exists
:return:
:return:
"""
print('right_view using queue')
if self.is_empty():
print('BST is empty')
return
queue = list()
queue.append(self.root)
while queue:
size = len(queue)
for i in range(size):
curr = queue.pop(0)
if i == size - 1:
# print only right node at each level
print(curr.data, end=' ')
if curr.left:
queue.append(curr.left)
if curr.right:
queue.append(curr.right)
print('')
print('')
def bottom_view(self, root):
"""
If we look at tree from bottom,
it is obvious that you would be able to see only leaf nodes of that tree
Basically idea is to use recursive approach to find all leaf nodes and print them
:param root:
:return:
"""
if root is None:
# if root is None return to immediate it latest caller
return
if not root.left and not root.right:
# leaf node found, so print it
print(root.data, end=' ')
self.bottom_view(root.left)
self.bottom_view(root.right)
def is_empty(self):
return self.root is None
def get_size(self, root):
"""
TC- O(n) --simply traversal of all nodes in tree
SC- O(h)--proportional to height-->no. active fun calls in stack <= height of tree at any moment
:param root:
:return: int size of tree(total no. of nodes in tree)
"""
if root is None:
return 0
else:
return 1 + self.get_size(root.left) + self.get_size(root.right)
def get_size_using_queue(self):
"""
Idea is to use level order traversal using queue
Keep counter to count no. of nodes until queue is not empty
:return:
"""
if self.root is None:
return 0
queue = list()
queue.append(self.root)
counter = 0
while queue:
counter += 1
curr = queue.pop(0)
if curr.left:
queue.append(curr.left)
if curr.right:
queue.append(curr.right)
return counter
def get_max_in_binary_tree(self, root):
"""
Idea is to using recursion find max from root, left-subtree and right-subtree
This solution is for binary tree.....(for BST there is better solution)
TC- O(n)
SC- O(h)---at most h+1 fun calls in stack-----using level order traversal --O(w)--width of tree
:param root:
:return: max value from tree
"""
if root is None:
return -sys.maxsize
else:
return max(root.key, max(self.get_max_in_binary_tree(root.lef), self.get_max_in_binary_tree(root.right)))
def print_k_dist_nodes(self, root, k):
"""
Idea is to use recursion and find kth level nodes in left and right subtrees
Pass k as argument to fun call
if root is empty simply return
if k == 0 then that is kth level node root
print root.data
else:
recursively call left and right subtree with k-1
:param root:
:param k:
:return:
"""
if root is None:
return
if k == 0: # this should be after only above base case check else none.data would be tried
print(root.data, end=' ')
else:
self.print_k_dist_nodes(root.left, k - 1)
self.print_k_dist_nodes(root.right, k - 1)
def is_balanced_tree(self, root):
"""
TC--->O(n)/theta(n)
SC-->O(h)--->height of tree
Idea is to find height of each node recursively in left and right subtree
And check if there height diff is not more than 1
When height is obtained of left and right subtree of each node
it will decide is balanced or not by comparing height diff
:param root:
:return:
"""
if root is None:
return 0
left_height = self.is_balanced_tree(root.left)
if left_height == -1:
return -1
right_height = self.is_balanced_tree(root.right)
if right_height == -1:
return -1
if abs(left_height - right_height) > 1:
return -1
else:
return max(left_height, right_height) + 1
def get_max_width_of_tree(self):
"""
TC-->theta(n)-->just traversing all nodes and doing const. operation using queue
SC-->O(n)-->theta(w)---max. width would be in a queue at any time
Idea is to use level order traversal line by line using queue
max width would be the max. no. of nodes in any level in the tree
:return: int --> max_width in tree
"""
if self.root is None:
return 0
queue = list()
queue.append(self.root)
max_width = 0
while queue:
size = len(queue)
max_width = max(max_width, size)
for _ in range(size):
curr = queue.pop(0)
if curr.left:
queue.append(curr.left)
if curr.right:
queue.append(curr.right)
return max_width
def bin_tree_to_double_linked_list(self, root):
pass
def spiral_level_order_traversal_using_queue_and_stack(self):
"""
Use line by line level order traversal using queue
reverse = False
while queue:
size = len(queue)
for _ in range(size):
if level has to printed reverse
then push that curr node data to stack
else
print(curr.data, end=' ')
push left and right
while stack:
print(stack.pop(), end=' ')
reverse = not reverse
print('') # new line for line by line spiral traversal
:return:
"""
print('spiral_level_order_traversal_using_queue_and_stack')
if self.is_empty():
return
queue = list()
stack = list()
queue.append(self.root)
reverse = False
while queue:
size = len(queue)
for i in range(size):
curr = queue.pop(0)
if reverse:
stack.append(curr.data)
else:
print(curr.data, end=' ')
if curr.left:
queue.append(curr.left)
if curr.right:
queue.append(curr.right)
if reverse:
while stack:
print(stack.pop(), end=' ')
reverse = not reverse
print('')
def spiral_improved(self):
"""
Idea is to use two stacks
First stack to print a level in left to right order
second stack to print a level in right to left order
:return:
"""
if self.root is None:
return
stack1 = list()
stack2 = list()
stack1.append(self.root)
while stack1 or stack2:
while stack1:
"""
push in stack2 left and right order
"""
curr = stack1.pop()
print(curr.data, end=' ')
if curr.left:
stack2.append(curr.left)
if curr.right:
stack2.append(curr.right)
print('')
while stack2:
"""
reverse order push
push in stack1 right and left order
"""
curr = stack2.pop()
print(curr.data, end=' ')
if curr.right:
stack1.append(curr.right)
if curr.left:
stack1.append(curr.left)
print('')
if __name__ == '__main__':
bst = BSTTree()
# input_array = [15, 10, 20, 8, 12, 17, 25]
# input_array = [1, 2, 3, 4, 5, 6]
# input_array = [10, 5, 20, 3, 7]
# input_array = [100, 80, 300, 10, 90, 200, 700, 8, 9, 150]
input_array = [150, 50, 200, 30, 90, 180, 300, 20, 40, 70, 100, 250, 500, 10]
for val in input_array:
bst.root = bst.insert(bst.root, val)
print('inorder')
bst.inorder(bst.root)
print('')
# print('preorder')
# bst.preorder(bst.root)
# print('')
print('postorder')
bst.postorder(bst.root)
print('')
bst.post_order_iterative()
# print("MIN:{}".format(bst.find_min(bst.root)))
# print("max:{}".format(bst.find_max(bst.root)))
# print("search:{}".format(bst.search(bst.root, -1)))
# print("search_itrative:{}".format(bst.search_iterative(-1)))
# print(bst.find_height_of_tree(bst.root))
# print('iterative pre')
# bst.iterative_pre()
# print('')
# bst.root = bst.delete(bst.root, 12)
# print('Inorder')
# bst.inorder(bst.root)
# print('')
# bst.level_order_traversal()
# bst.level_order_traversal_line_by_line()
# bst.level_order_traversal_line_by_line(left_view_only=True)
# bst.right_view()
# print('bottom view using recursion')
# bst.bottom_view(bst.root)
# print('')
# # bst.spiral_level_order_traversal(bst.root)
# print(bst.get_size(bst.root))
# print(bst.get_size_using_queue())
# print('k dist nodes')
# bst.print_k_dist_nodes(bst.root, 2)
# print('')
# bst.spiral_level_order_traversal()
# bst.spiral_level_order_traversal_using_queue_and_stack()
|
0b0968fca112dfc52a74ebd375f67b7a01603785 | cicekozkan/python-examples | /is_sorted.py | 332 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 29 23:23:28 2014
@author: Ozkan
"""
def is_sorted(t):
"""takes a list as a parameter and returns True
if the list is sorted in ascending order and False otherwise."""
i = 0
for i in range(len(t) - 1):
if t[i] > t[i+1]:
return False
return True |
8be23258154a3b4afa793791a205fdf589b44ed8 | Eleanoryuyuyu/LeetCode | /python/Backtracking/46. 全排列.py | 958 | 3.53125 | 4 | from typing import List
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
if not nums:
return [[]]
self.res = []
self.dfs(nums, [])
return self.res
def dfs(self, nums, path):
if len(path) == len(nums):
self.res.append(path)
return
for i in range(len(nums)):
if nums[i] not in path:
self.dfs(nums, path+[nums[i]])
def permute2(self, nums: List[int]) -> List[List[int]]:
if not nums:
return []
def dfs(first):
if first == n:
res.append(nums[:])
for i in range(first, n):
nums[first], nums[i] = nums[i], nums[first]
dfs(first + 1)
nums[first], nums[i] = nums[i], nums[first]
n = len(nums)
res = []
dfs(0)
return res
nums = [1,2,3]
print(Solution().permute2(nums)) |
f88c4ef601c3dc1fe71e8b22bd01d618b7ebe7a5 | benjamin22-314/codewars | /data-reverse.py | 478 | 4.03125 | 4 | # https://www.codewars.com/kata/data-reverse
def data_reverse(data):
list_of_lists = []
for l in range(int(len(data)/8)):
list_of_lists.append([data[d] for d in range(l*8, l*8 + 8)])
return [a for b in list_of_lists[::-1] for a in b]
# tests
data1 = [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]
data2 = [1,0,1,0,1,0,1,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1]
print(data_reverse(data1))
print(data_reverse(data1) == data2)
|
cd2ee8b63cde2545b7848e58b320c06fea840776 | TomekPk/Python-Crash-Course | /Chapter 7/7.10.Dream Vacation/dream_vacation.py | 757 | 4.28125 | 4 | '''
7-10. Dream Vacation: Write a program that polls users about their dream
vacation. Write a prompt similar to If you could visit one place in the world,
where would you go? Include a block of code that prints the results of the poll.
'''
question = "If you could visit one place in the world, where would you go?"
question +="\nPlease enter answer: "
answer_list = []
while True:
answer = input(question)
print("Your answer is: " + answer)
answer_list.append(answer)
repeat = input("\nWould You like to make another poll? (yes/no): ")
if repeat.lower() == "no":
break
elif repeat.lower() == "yes":
continue
print("\nPoll end. You can see Your answers below: ")
for i in answer_list:
print("\t" + i)
|
c211fda0ac255cd8d9777c70abd78e158bf5e7bd | UX404/Leetcode-Exercises | /#746 Min Cost Climbing Stairs.py | 1,299 | 4.09375 | 4 | '''
On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.
Example 1:
Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.
Example 2:
Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6
Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].
Note:
cost will have a length in the range [2, 1000].
Every cost[i] will be an integer in the range [0, 999].
'''
# 1 Recursion
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
if len(cost) == 0 or len(cost) == 1: return 0
return min(cost[-1] + self.minCostClimbingStairs(cost[:-1]), cost[-2] + self.minCostClimbingStairs(cost[:-2]))
# 2 Iteration
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
front, back = 0, 0
for i in cost: # mincost(n) = i + (mincost(n), mincost(n-1))
temp = i + min(front, back)
back = front
front = temp
return min(front, back) |
1b4acf8d493dc9bc4c337444fb7937f3502922b7 | Mr-ZDS/Python_Brid | /Leetcode/L392 判断子序列.py | 916 | 3.578125 | 4 | '''
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
示例 1:
s = "abc", t = "ahbgdc"
返回 true.
示例 2:
s = "axc", t = "ahbgdc"
'''
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
s_len, t_len = len(s), len(t)
i, j = 0, 0
while i < s_len and j < t_len:
if s[i] == t[j]:
i +=1
j += 1
else:
j += 1
if i == s_len and j <= t_len:
return True
else:
return False |
726a4f920ad0ebd5ffcb15b463ccfd0ea65d4a67 | yatengLG/leetcode-python | /question_bank/insertion-sort-list/insertion-sort-list.py | 1,052 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:160 ms, 在所有 Python3 提交中击败了94.60% 的用户
内存消耗:15.3 MB, 在所有 Python3 提交中击败了7.93% 的用户
解题思路:
见代码注释
"""
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
result = ListNode(float('-inf'), next=head)
r = result # 指针r.next指向当前节点
while r.next: # 当前节点不为None时,
if r.next.val > r.val: # 如果当前节点后一个节点大于当前节点值,后移指针,处理下一个
r = r.next
else: # 小于时,执行插入操作
node = r.next # 记录并删除当前节点node
p = result
r.next = r.next.next
while p.next.val < node.val: # 在排序好的链表中,寻找插入node的位置
p = p.next
node.next = p.next # 插入节点
p.next = node
return result.next |
373e18e363c5fcb3d1510d8ac22ee12523f23414 | titf512/FPRO---Python-exercises | /sum_dictionaries.py | 267 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 14 09:15:34 2021
@author: teresaferreira
"""
def sum_dicts(lst):
dic=dict()
for i in lst:
for key,value in i.items():
dic[key]=dic.get(key,0)+value
return dic |
ffe35ed4b1346d6fd6293261e457363ea28238d8 | christiancyint/python_crashcourse | /chapter3/3_bicycles.py | 396 | 4.4375 | 4 | # Chapter 3 practicing lists in Python
# You can access values in a list by specifying their index, which starts at 0.
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print bicycles[0].title()
print bicycles[2].title()
print bicycles[-1].title()
# Values in an index can be used like any other variable
message = "My first bicycle was a " + bicycles[0].title() + "."
print message
|
872dd8a6489062e83409d23100938ef8cb421837 | katiebug2001/project-euler | /highly_divisible_triangular_number.py | 3,596 | 4.21875 | 4 | import unittest
import math
def factor(num):
"""returns ALL (not just prime) factors of a number"""
limit = int(math.sqrt(num))
factors = [1]
if num > 1:
factors.append(num)
if limit > 1:
if num/limit == limit:
factors.append(limit)
elif num % limit == 0:
factors.extend([limit, num//limit])
for d in range(2, limit):
if num % d == 0:
factors.extend([d, num//d])
print("{} has {} factors".format(num, len(factors)))
factors.sort()
return factors
def next_triangle(triangle_tuple, num_to_skip = 1):
"""takes a triangular number and ordinally which triangular number that one is in a tuple (e.g (1, 1) or (15, 5)
returns the next triangular number and the number of that triangular number in a tuple"""
#print("triangle_tuple = {}".format(triangle_tuple))
#print("num_to_skip = {}".format(num_to_skip))
num_new_triangle = (triangle_tuple[1] + num_to_skip)
#print("num_new_triangle = {}".format(num_new_triangle))
triangle_to_be_added = triangle_tuple[0]
for addend in range((triangle_tuple[1] + 1), (triangle_tuple[1] + num_to_skip + 1)):
#print("addend = {}".format(addend))
#print("triangle_to_be_added = {}".format(triangle_to_be_added))
triangle_to_be_added += addend
return (triangle_to_be_added, num_new_triangle)
def factor_test(up_to):
triangle = (1, 1)
this_triangle_factors = factor(triangle[0])
while True:
print("triangle: {}, factors: {} ".format(triangle[0], len(factor(triangle[0]))))
triangle = next_triangle(triangle)
# last_triangle_factors, this_triangle_factors = this_triangle_factors, factor(triangle[0])
# if len(last_triangle_factors) > len(this_triangle_factors):
# print("fail :(")
# break
if triangle[1] >= up_to:
#print("done!")
break
def find_triangle(factors):
"""takes a number of factors; returns first triangular number with more than that many factors"""
triangle = (1,1)
while len(factor(triangle[0])) <= factors:
triangle = next_triangle(triangle)
return triangle[0]
print(find_triangle(500))
class test_factor_and_next_triangle(unittest.TestCase):
"""tests factor and next_triangle"""
def test_find_triangle(self):
""" tests the function find_triangle """
more_factors_than = [1, 4, 5, 10, 15]
test_hopeful_output = [3, 28, 28, 120, 120]
test_output = []
for input in more_factors_than:
test_output.append(find_triangle(input))
self.assertEqual(test_output, test_hopeful_output)
def test_factor(self):
"""tests the function factor"""
test_numbers = [1, 2, 8, 5, 21, 28]
test_factorizations = [[1], [1, 2], [1, 2, 4, 8], [1, 5], [1, 3, 7, 21], [1, 2, 4, 7, 14, 28]]
returned_factorizations = []
for num in test_numbers:
returned_factorizations.append(factor(num))
self.assertEqual(test_factorizations, returned_factorizations)
def test_next_triangle(self):
"""tests the function next_triangle"""
test_input_tri_tuples = [(1,1), (15,5),]
check_output_tri_tuples = [(3, 2), (21, 6)]
outputs = []
for input in test_input_tri_tuples:
outputs.append(next_triangle(input))
self.assertEqual(next_triangle((10, 4), 5), (45, 9))
self.assertEqual(check_output_tri_tuples, outputs)
if __name__ == "__main__":
unittest.main()
#35942481 |
6874a8fc7f288dc0bed8be071dad175dfea667bc | daniel-reich/ubiquitous-fiesta | /sKXWQym3xg6uBLrpY_0.py | 374 | 3.515625 | 4 |
def iqr(lst):
lst = sorted(lst)
first_half = lst[:len(lst) // 2]
second_half = lst[-(-len(lst) // 2):]
first_half_median = (first_half[len(first_half) // 2] + first_half[~(len(first_half) // 2)]) / 2
second_half_median = (second_half[len(second_half) // 2] + second_half[~(len(second_half) // 2)]) / 2
return second_half_median - first_half_median
|
8d8fe9bf85798a4ff157387081f6d7d0dbd19e6b | AsanakaF/tasks4sm | /laba2.py | 177 | 3.5625 | 4 | koren = float(input('Enter number: '))
a = 0
x = 0.5 * (1 + koren)
while a * a - abs(koren) > 0.01 or a * a - abs(koren) < -0.01:
a = 0.5 * (x + koren / x)
x = a
print(a)
|
6f405b653a7170f946f5867a50c12763d0379ad2 | KivyAcademy/Kivy_training | /basic/03_custom_app.py | 1,046 | 3.546875 | 4 | # -*- coding: utf-8 -*-
## https://kivy.org/doc/stable/guide/basic.html#quickstart
from kivy.app import App
import kivy
kivy.require('1.10.1')
## This class is used as a Base for our Root Widget (LoginScreen) defined later
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
class LoginScreen(GridLayout):
def __init__(self, **kwargs):
# class LoginScreen, we override the method __init__() so
# as to add widgets and to define their behavior:
super(LoginScreen, self).__init__(**kwargs)
self.cols = 2
self.add_widget(Label(text='User name'))
self.username = TextInput(multiline=False)
self.add_widget(self.username)
self.add_widget(Label(text='password'))
self.password = TextInput(password=True, multiline=False)
self.add_widget(self.password)
class MyApp(App):
def build(self):
return LoginScreen()
if __name__ == "__main__":
MyApp().run()
#print(MyApp().username) |
52d4022e10c0bcdc12545bfd3db1d836a15714b4 | chin8628/Pre-Pro-IT-Lardkrabang-2558 | /Prepro-Onsite/W5_D2_CallSum.py | 653 | 3.625 | 4 | """ W5_D2_CallSum """
def main(limit, step, total=0, index=1):
""" this is a main function """
if limit == 1:
return 1
elif step > 0 and limit > 1 and index <= limit:
return main(limit, step, total + index, index + step)
elif step < 0 and limit < 1 and index >= limit:
return main(limit, step, total + index, index + step)
elif (step < 0 and limit < 1 and index < limit) or (step > 0 and limit > 1 and index > limit):
return total
elif step == 0 or (step < 0 and limit > 1) or (step > 0 and limit < 1):
return "Error"
else:
return total
print(main(int(input()), int(input())))
|
b46e32ac6c9d72854994a41af8c86a86e4df6fe6 | KyoungSoo1996/python-coding-practice | /python project/This is Coding Test/DFS.py | 470 | 3.5 | 4 | #그래프 DFS 구현하기
graph = [
[],
[2,3,8],
[1,7],
[1,4,5],
[3,5],
[3,4],
[7],
[2,6,8],
[1,7]
]
checked = [False] * 9
answer = []
def DFS(graph, checked, currentPos):
answer.append(currentPos)
if not checked[currentPos]:
checked[currentPos] = True
for i in graph[currentPos]:
if not checked[i]:
DFS(graph, checked, i)
return answer
print(DFS(graph, checked, 1))
|
18c1b93743fa8979f4af98f50c4c732dfec5f9d1 | sonam2905/My-Projects | /Python/Exercise Problems/full_binary_tree_preorder_postorder.py | 2,139 | 4.21875 | 4 | # Python3 program for construction of
# full binary tree
# A binary tree node has data, pointer
# to left child and a pointer to right child
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# A recursive function to construct
# Full from pre[] and post[].
# preIndex is used to keep track
# of index in pre[]. l is low index
# and h is high index for the
# current subarray in post[]
def constructTreeUtil(pre: list, post: list,
l: int, h: int,
size: int) -> Node:
global preIndex
# Base case
if (preIndex >= size or l > h):
return None
# The first node in preorder traversal
# is root. So take the node at preIndex
# from preorder and make it root, and
# increment preIndex
root = Node(pre[preIndex])
preIndex += 1
# If the current subarry has only
# one element, no need to recur
if (l == h or preIndex >= size):
return root
# Search the next element
# of pre[] in post[]
i = l
while i <= h:
if (pre[preIndex] == post[i]):
break
i += 1
# Use the index of element
# found in postorder to divide
# postorder array in two parts.
# Left subtree and right subtree
if (i <= h):
root.left = constructTreeUtil(pre, post,
l, i, size)
root.right = constructTreeUtil(pre, post,
i + 1, h-1,
size)
return root
# The main function to construct
# Full Binary Tree from given
# preorder and postorder traversals.
# This function mainly uses constructTreeUtil()
def constructTree(pre: list,
post: list,
size: int) -> Node:
global preIndex
return constructTreeUtil(pre, post, 0,
size - 1, size)
# A utility function to print
# inorder traversal of a Binary Tree
def printInorder(node: Node) -> None:
if (node is None):
return
printInorder(node.left)
print(node.data, end = " ")
printInorder(node.right)
# Driver code
if __name__ == "__main__":
pre = [ 1, 2, 4, 8, 9, 5, 3, 6, 7 ]
post = [ 8, 9, 4, 5, 2, 6, 7, 3, 1 ]
size = len(pre)
preIndex = 0
root = constructTree(pre, post, size)
print("Inorder traversal of "
"the constructed tree: ")
printInorder(root)
|
a235690ed6710748ccb66eb3257aa2e2c3197db2 | viveknathani/pps-labwork | /31-03-20/modules/fib.py | 329 | 3.5625 | 4 | def fib(n):
if n<1:
return -1
elif n==1:
return 1
elif n==2:
return 1
else:
return fib(n-1)+fib(n-2)
def fib_series(m):
series=[]
for var in range(1, m+1):
x=fib(var)
if x==-1:
break
else:
series.append(x)
return series
|
0ac7d5fefdeea3c97a0c42002e0562eb45d48a7a | KatiraOrellana/CienciaDatos | /Laboratorio2/.ipynb_checkpoints/FuncionTupla-checkpoint.py | 591 | 3.765625 | 4 | import sys
def main():
try:
elementos = sys.argv[1]
lista = []
a = 1
while a <= int(elementos):
valor = input('Ingrese registro {}: '.format(a))
lista.append(valor)
a = a+1
salida = ''
for a in lista:
salida = salida + str(a)
print(salida)
except IndexError as e:
print('Error: Debe ingresar un parámetro')
except ValueError as e:
print('Error: Debe ingresar un entero')
except Exception as e:
print(e)
if __name__ == '__main__':
main() |
89ac4b1185b80c089458c10a62992a9cd9470526 | gmr50/exec-dash-project | /exec_dash_revisited.py | 1,314 | 3.65625 | 4 | import pandas as pd
def to_usd(input):
result = "${0:,.2f}".format(input)
return result
def get_top_sellers(worked_data):
#deal with item list
counter = 0
item_list = []
sales_list = []
total_sale = 0
overall_total_sales = 0
for index, row in worked_data.iterrows():
overall_total_sales = overall_total_sales + row["sales price"]
counter = counter + 1
if(counter <= 7) or (counter == len(worked_data) - 2):
#total_sale_item = float(row["sales price"])
#changed for revisit
#total_sale_item ='${:,.2f}'.format(total_sale_item)
total_sale_item = (float(row["sales price"]))
total_sale = total_sale + total_sale_item
total_sale_item = to_usd(total_sale_item)
print(str(counter) + ") " + str(index) + ": " + str(total_sale_item))
item_list.append(str(index))
#item_list.append(str(row['Name:']))
#item_list.append(str(row["product"]))
#changed for revisit
#sale_format = '${:,.2f}'.format(float(row["sales price"]))
#sale_format = to_usd(float(row["sales price"]))
sales_list.append(total_sale_item)
sales_dataframe = pd.DataFrame(
{
'item_list': item_list,
'sales_list': sales_list,
'total_sale': total_sale,
'total_overall_sale': overall_total_sales
})
return sales_dataframe
if __name__ == "__main__":
print("main") |
e07b146c23cf354fa9de566bdddd6c4554451282 | ViniciusQueiros16/Python | /PythonExercicios/ex113.py | 899 | 3.921875 | 4 | def leiaint(num):
while True:
try:
valor = int(input(num))
except (ValueError, TypeError):
print('\033[31mERRO! Digite um número inteiro válido.\033[m')
except KeyboardInterrupt:
print('O usuário preferiu não digitar esse número.')
return 0
else:
return int(valor)
def leiafloat(num):
while True:
try:
valor = float(input(num))
except (ValueError, TypeError):
print('\033[31mERRO! Digite um número real válido.\033[m')
except KeyboardInterrupt:
print('\n\033[31mO usuário preferiu não digitar esse número.\033[m')
return 0
else:
return float(valor)
i = leiaint('Digite um numero inteiro: ')
r = leiafloat('Digite um número Real: ')
print(f'O valor inteiro digitado foi {i} e o Real foi {r}')
|
66462fbdcb604a7c730540fca0002e69b996d643 | nvkwo3314200/pyTest | /com/study/17/12-.py | 619 | 3.765625 | 4 | #coding=utf-8
'''
Created on 2018年9月6日
@author: Pan
'''
def tester(start):
state = start
def nested(label):
nonlocal state
print(label, state)
state += 1
return nested
F = tester(0)
F("spam")
F("ham")
F("eggs")
G = tester(43)
G("spam")
G("ham")
F("bacon")
#边界情况
'''
def tester(start):
def nested(label):
state = 0
nonlocal state
print(label, state)
return nested
'''
def tester(start):
def nested(label):
global state
state = 0
print(label, state)
return nested
F = tester(0)
F('abc')
print(state) |
8a51cdfe45dc52ec23e8e793d41aaea6fa8d4ade | Voronica/CS_1134 | /hw3/sz2417_hw3_q2.py | 2,772 | 3.734375 | 4 | import ctypes
def make_array(n):
return (n * ctypes.py_object)()
class ArrayList:
def __init__(self):
self.data_arr = make_array(1)
self.n = 0
self.capacity = 1
def __len__(self):
return self.n
def append(self, val):
if self.capacity == self.n:
self.resize(2 * self.capacity)
self.data_arr[self.n] = val
self.n += 1
def resize(self, new_size):
new_array = make_array(new_size)
for i in range(self.n):
new_array[i] = self.data_arr[i]
self.data_arr = new_array
self.capacity = new_size
def __getitem__(self,ind):
if ind >= 0:
if ind <= self.n - 1:
return self.data_arr[ind]
else:
raise IndexError("Out of range!")
if ind < 0:
if abs(ind) <= self.n:
ind += self.n
return self.data_arr[ind]
else:
raise IndexError("Out of range!")
def __setitem__(self, ind, val):
if not(self.n - 1 >= ind >= 0):
raise IndexError("Invalid index")
self.data_arr[ind] = val
def __iter__(self):
for i in range(self.n + 1):
yield self.data_arr[i]
def extend(self, other_collection):
for elem in other_collection:
self.append(elem)
def insert(self, index, val):
if self.capacity == self.n:
self.resize(2 * self.capacity)
for i in range(self.n - 1, index - 1, -1):
self.data_arr[i + 1] = self.data_arr[i]
self.data_arr[index] = val
self.n += 1
def pop(self, k = -1):
if self.n == 0:
raise IndexError("This is an empty list")
if k >= 0:
if k < self.n:
temp = self.data_arr[k]
for i in range(k, self.n - 1):
self.data_arr[i] = self.data_arr[i + 1]
self.n -= 1
return temp
else:
raise IndexError("Out of range!")
if k < -1:
if abs(k) <= self.n + 1:
temp = self.data_arr[k + self.n]
for i in range(k + self.n, self.n - 1):
self.data_arr[i] = self.data_arr[i + 1]
self.n -= 1
return temp
else:
raise IndexError("Out of range!")
if k == -1:
temp = self.data_arr[self.n - 1]
self.data_arr[self.n - 1] = None
self.n -= 1
return temp
def __repr__(self):
final_str = "["
for i in range(self.n):
final_str += str(self.data_arr[i]) + ","
final_lst = final_str[:-1] + "]"
return final_lst
|
63ad5bd197c0c9c26d7a1ba16e278578c3c6b87a | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/chktak002/push.py | 3,907 | 4.25 | 4 | def push_up (grid):
"""merge grid values upwards"""
for i in range (3):
for row in range(1,4):
for col in range(4):
if grid[row-1][col] == grid[row-1][col] ==0:
grid[row-1][col] = grid[row][col] #Make the item in the row below equal the current 1
grid[row][col] = 0 #removes the value from the grid and assigns 0 to it
for row in range(1,4):
for col in range(4):
if grid[row-1][col] == grid[row][col]: #Check if they are the same
grid[row][col] = 0 #removes th original item by making it = 0
grid[row-1][col] += grid[row-1][col] #"Merge" by multiplying item by 2
for row in range(1,4):
for col in range(4):
if grid[row-1][col]== grid[row-1][col]==0:
grid[row-1][col] = grid[row][col]
grid[row][col] = 0
def push_down (grid):
"""merge grid values downwards"""
for i in range (3):
for row in range (2,-1,-1): #iterates backwards since weare now duing the oposite of pushing up
for col in range (3,-1,-1):
if grid[row+1][col] == grid[row+1][col] ==0:
grid[row+1][col] = grid[row][col] #Make the item in the row above equal to the current item
grid[row][col] = 0 #removes the value from the grid and assigns 0 to it
for row in range(2,-1,-1):
for col in range(3,-1,-1):
if grid[row+1][col] == grid[row][col]: #Check if they are the same
grid[row][col] = 0 #removes the value from the grid and assigns 0 to it
grid[row+1][col] += grid[row+1][col] # merges the two if the are equal
for row in range(2,-1,-1): #Last repetition of the i loop after merging
for col in range(3,-1,-1):
if grid[row+1][col]== grid[row+1][col]==0:
grid[row+1][col] = grid[row][col]
grid[row][col]=0
def push_left (grid):
"""merge grid values left"""
for i in range (3):
for row in range(4):
for col in range(1,4): #Starts from 1 since we don't need first column as the item wouldn't need to move
if grid[row][col-1] == grid[row][col-1] ==0:
grid[row][col-1] = grid[row][col] #Make the item in the column leftwards of current item equal to current item
grid[row][col] = 0 #removes the value from the grid and assigns 0 to it
for row in range(4):
for col in range(1,4):
if grid[row][col-1] == grid[row][col]:
grid[row][col-1] += grid[row][col]
grid[row][col] =0
for row in range(4):
for col in range(1,4):
if grid[row][col-1]== grid[row][col-1]==0:
grid[row][col-1] = grid[row][col]
grid[row][col]=0
def push_right (grid):
"""merge grid values right"""
for i in range (3):
for row in range(3,-1,-1):
for col in range(2,-1,-1):
if grid[row][col+1] == grid[row][col+1] ==0:
grid[row][col+1] = grid[row][col]
grid[row][col] = 0
for row in range(3,-1,-1):
for col in range(2,-1,-1):
if grid[row][col+1] == grid[row][col]:
grid[row][col] = 0
grid[row][col+1] += grid[row][col+1]
for row in range(3,-1,-1):
for col in range(2,-1,-1):
if grid[row][col+1]== grid[row][col+1]==0:
grid[row][col+1] = grid[row][col]
grid[row][col]=0 |
282ff700d555884a480812d5265bb99f7c048ef6 | Georges1998/MealCare | /backend/scripts/setup_db.py | 1,132 | 3.515625 | 4 | # Script to create a Database, User/Role with Password, and grant all privileges on Database
import psycopg2
from psycopg2 import sql
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
try:
con = psycopg2.connect(dbname="template1")
db_name = sql.Identifier("mealcare_dev")
db_test_name = sql.Identifier("mealcare_test")
username = sql.Identifier("mealadmin")
password = sql.Literal("happymeal")
con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = con.cursor()
cur.execute(sql.SQL("CREATE DATABASE {}").format(db_name))
cur.execute(sql.SQL("CREATE DATABASE {}").format(db_test_name))
cur.execute(sql.SQL("CREATE USER {} WITH PASSWORD {}").format(username, password))
cur.execute(
sql.SQL("GRANT ALL PRIVILEGES ON DATABASE {} to {}").format(db_name, username)
)
print("Created database {} successfully!".format("mealcare_dev"))
except (Exception, psycopg2.Error) as error:
print("Error while connecting to PostgreSQL {}".format(error))
finally:
if con:
cur.close()
con.close()
print("PostgreSQL connection is closed")
|
2e96414fc1eddb9d58a961b8b8c4daf549722fca | AssiaHristova/SoftUni-Software-Engineering | /Programming Basics/conditional_statements/fuel_tank.py | 271 | 4.0625 | 4 | fuel = input()
liters = int(input())
if fuel == 'Diesel' or \
fuel == 'Gasoline' or \
fuel == 'Gas':
if liters >= 25:
print(f'You have enough {fuel}.')
else:
print(f'Fill your tank with {fuel}!')
else:
print(f'Invalid fuel!')
|
97e0ab09685126863f7b7874d7660fd1ecaf27c5 | DrEaston/CodingNomads | /labs/13_aggregate_functions/13_03_my_enumerate.py | 406 | 4.125 | 4 | '''
Reproduce the functionality of python's .enumerate()
Define a function my_enumerate() that takes an iterable as input
and yields the element and its index
'''
def my_enumerate(iterable):
count = 0
output = []
for item in iterable:
count += 1
output.append((count, item))
return output
print(my_enumerate(['cats','dogs','spiders','frogs']))
|
cfcfc9efba2ab93678df517eac6104e3dd4bea68 | tom1mol/python-fundamentals | /indexing and lists/list2.py | 1,448 | 4.3125 | 4 | fruits = ["apple", "banana", "peach", "pear", "plum", "orange"]
counter = 0
while counter < len(fruits):
print(fruits[counter])
counter += 1
# OUTPUT:
# Python 3.6.1 (default, Dec 2015, 13:05:11)
# [GCC 4.8.2] on linux
# apple
# banana
# peach
# pear
# plum
# orange
# NOTES:
# Here is a slightly more elaborate example using a while loop and list indexes. Firstly, we have our fruits list which is the
# same list of fruits that we used before. Next we’ve declared a variable called counter. Each time we run this while loop, we’ll
# increase the value of this by one. After this, we have our while loop. This while loop checks to see if the counter is less than
# the length of fruits. This way, every time the counter variable is increased, it will map directly to an index that’s contained
# within the fruits list.
# Let’s take a look at the example below:
# Element “apple” “banana” “peach” “pear” “plum” “orange
# Index 0 1 2 3 4 5
# Instead of using the actual number inside the square brackets, we can just use the counter variable as the
# index value. After that, we just clock up our counter by using the arithmetic operator to add one to the
# existing counter variable, and the process starts again, so long as the condition in the while loop is true! |
0ec4208b74f5b970c3e580346215088b3f24c1f6 | Raushan117/Python | /029_Rename_Filename_Date_Format.py | 2,097 | 3.53125 | 4 | # https://automatetheboringstuff.com/chapter9/
# Project rename files with American style dates to Eurpoean style dates
# American style = MM-DD-YYYY
# European style = DD-MM-YYYY
# Write program that will handle it for you :)
# Step 01: Search all the filesname in current working directory for AM style
# Step 02: When you found it, swap it to European style.
# Create a regex that can identify the text pattern for AM style dates
# Call os.listdir() to find all the files
# Loop over each filename, using the regex to check weather it has a date
# If it has a date, rename the file with shutil.move()
import shutil, os, re
# Create a regex that matches files with the American date format.
# Passing re.VERBOSE allow white space and comment
datePattern = re.compile(r"""^(.*?) # all text before the date
((0|1)?\d)- # one or two digit for the month
((0|1|2|3)?\d)- # one or two digit for the day
((19|20)\d\d) # four digits for the year
(.*?)$ # all text after the date
""", re.VERBOSE)
# To do: Loop over the files in the working directory
for amerFilename in os.listdir('.'):
mo = datePattern.search(amerFilename)
# Skip files without a date.
if mo == None:
continue
# Get the different parts of the filename.
beforePart = mo.group(1)
monthPart = mo.group(2)
dayPart = mo.group(4)
yearPart = mo.group(6)
afterPart = mo.group(8)
# To do: From the European-style filename
euroFilename = beforePart + dayPart + '-' + monthPart + '-' + yearPart + afterPart
# To do: Get the full, absolute file paths
absWorkingDir = os.path.abspath('.')
amerFilename = os.path.join(absWorkingDir, amerFilename)
euroFilename = os.path.join(absWorkingDir, euroFilename)
# To do: Rename the files
# print('Renaming "%s" to "%s"...' % (amerFilename, euroFilename))
print('Renameing {} to {}...'.format(amerFilename, euroFilename))
# shutil.move(amerFilename, euroFilename) # uncomment after testing
|
2b3579c5ca13c5b9f9386fe46770d8423c755632 | lydxlx1/LeetCode | /src/linked-list-in-binary-tree.py | 1,271 | 3.765625 | 4 | """1367. Linked List in Binary Tree
It is hard to solve the problem in a top-down fashion since each tree node can have two choices.
However, since each node has a unique parent, the upwards paths ending at any node are also unique (by its length).
This suggests a DFS approach, where we just need to check whether the last m nodes on the stack match the given listed list at any time.
Time: O(mn)
Space: O(m + h)
m = linked list size, n = binary tree size, h = binary tree height
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSubPath(self, head: ListNode, root: TreeNode) -> bool:
target = []
while head:
target.append(head.val)
head = head.next
def dfs(root, path):
if len(path) >= len(target) and path[-len(target):] == target:
return True
if not root:
return False
path.append(root.val)
if dfs(root.left, path) or dfs(root.right, path):
return True
path.pop()
return False
return dfs(root, [])
|
fda905fe3749cc743490f832440692d0cd9bee96 | Shaileshsachan/Machine_Learning | /data_preprcossing.py | 1,536 | 3.609375 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.impute import SimpleImputer
dataset = pd.read_csv('data.csv')
x = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
imputer.fit(x[:, 1:3])
x[:, 1:3] = imputer.transform(x[:, 1:3])
# print(x)
# encoding categorical data using one hot encoding
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [0])], remainder='passthrough')
x = np.array(ct.fit_transform(x))
# print(x)
# encoding the dependent variable
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
y = le.fit_transform(y)
# print(y)
# Splitting the dataset into the Training and Test set
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=1)
# print(x_train)
# print(y_train)
# print(x_test)
# print(y_test)
# Feature Scaling
# Standard Deviation = {sqrt { {sum (x - mean(x))**2} / {N(Size of the population)} } }
# Standardisation = x(stand) = x - mean(x) / standard deviation(x) .....Value between +3 and -3
# Normalisation = x-min(x) / max(x)-min(x) ......Value between 0 and 1
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
x_train[:, 3:] = sc.fit_transform(x_train[:, 3:])
x_test[:, 3:] = sc.transform(x_test[:, 3:])
# print(x_train)
# print(x_test)
|
9609e4c0ac1261c24163a4b37fed90735a086b3e | pylarva/Python | /day2/shopping_cart/shopping_chart.py | 4,487 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:lichengbing
import sys, time
def shopping_home(user_name,salary):
FLAGE_A = True
shopping_car = []
while FLAGE_A:
product_dict = {
'家电类':[('乐视TV',1999),('海尔冰箱',1500)],
'数码类':[('Mac Pro',9888),('iphone',5888)],
'服饰类':[('Adidas',399),('POLO',299)],
'汽车类':[('Tesla',888888),('TOYOTA',200000)],
}
print(' PRODUCT LIST '.center(50, '-'))
product_type = {}
for i,j in enumerate(product_dict.keys()):
product_type[i] = j
print('%d.%s'% (i,j))
print('-'.center(50,'-'))
user_select = input('请选择商品类型: ')
if user_select.isdigit():
user_select = int(user_select)
if user_select in product_type.keys():
type_name = product_type[user_select]
while type_name != 0:
for item in enumerate(product_dict[type_name]):
index = item[0]
p_name = item[1][0]
p_price = item[1][1]
print(index,'.',p_name,p_price)
user_choice = input('[q=退出,c=查看购物车,b=返回上一层] 您想购买什么?: ')
if user_choice.isdigit():
user_choice = int(user_choice)
if user_choice < len(product_dict[type_name]):
p_item = product_dict[type_name][user_choice]
num = input('请输入您要购买的数量: ')
if num.isdigit():
num = int(num)
if p_item[1]*num <= salary:
shopping_car.append((p_item[0],num,p_item[1]))
salary -= p_item[1]*num
print('Added %s into shopping car successful,you balance is %s...'% (p_item,salary))
continue
else:
user_charge = input('You balance is %s,cannot afford this,do you want recharge? Y|N'% salary)
if user_charge == 'y' or user_charge == 'Y':
recharge(salary)
continue
elif user_choice == 'c':
show_shoppingcar(shopping_car)
elif user_choice == 'q':
show_shoppingcar(shopping_car)
print('谢谢光临,bey...')
sys.exit()
elif user_choice == 'b':
break
else:
print('输入错误,请重新输入...')
time.sleep(1)
def show_shoppingcar(shopping_car):
print('您购物车里已购商品如下: ')
print('商品 数量 价格 总价')
for m, n in enumerate(shopping_car):
print('%d.%s %s * %s 【%d】' % (m, n[0], n[1], n[2], (n[1] * n[2])))
print('_'.center(50, '_'))
def recharge(salary):
exit_flag = False
while exit_flag is not True:
user_charge = input('请输入您要充值的金额: ')
if user_charge.isdigit():
user_charge = int(user_charge)
salary += user_charge
print('充值成功,您的当前余额为:%d'% salary)
break
else:
print('输入错误,请重新输入...')
continue
user_file = open('C:/software/github/Python/day2/shopping_cart/user.txt','r+')
user_list = user_file.readlines()
user_name = input('请输入您的用户名: ')
for user_line in user_list:
(user,password,salary) = user_line.split()
salary = int(salary)
if user == user_name:
i = 0
while i < 3:
passwd = input('请输入密码: ')
if passwd == password:
print('\033[32;1m%s\033[0m,欢迎您!您当前余额为 \033[31;1m%d\033[0m...'% (user_name,salary))
print('正在进入购物页面...')
time.sleep(1)
shopping_home(user_name,salary)
else:
print('密码错误,还剩%d次机会...'% (2-i))
i += 1
continue
print('用户未找到...')
sys.exit()
|
b673803b73d1ccf30151bd61b48fad0f8f796cb6 | hrishitelang/100-days-of-python | /Day 29/main.py | 3,279 | 3.671875 | 4 | from tkinter import *
from tkinter import messagebox
import random
import pyperclip
# ---------------------------- PASSWORD GENERATOR ------------------------------- #
def generate():
letters = ['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', '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']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
nr_letters = random.randint(8, 10)
nr_symbols = random.randint(2, 4)
nr_numbers = random.randint(2, 4)
password_list = [random.choice(letters) for char in range(nr_letters)]
password_list += [random.choice(letters) for char in range(nr_symbols)]
password_list += [random.choice(numbers) for char in range(nr_numbers)]
random.shuffle(password_list)
password = "".join(password_list)
password_text.insert(0, password)
pyperclip.copy(password)
# ---------------------------- SAVE PASSWORD ------------------------------- #
def save_text():
name_answer = name_text.get()
email_answer = email_text.get()
password_answer = password_text.get()
if name_answer == "":
messagebox.showerror(title="Error", message="Please enter the name of the website.")
if email_answer == "":
messagebox.showerror(title="Error", message="Please enter your email address.")
if password_answer == "":
messagebox.showerror(title="Error", message="Please enter your password.")
else:
flag = messagebox.askokcancel(title=name_answer, message=f"Here are the details:\nSite: {name_answer}\nEmail: {email_answer}\nPassword: {password_answer}\n"
f"Are you sure you want to save these details?")
if flag:
with open('data.txt', 'a') as file:
file.write(f"{name_answer} | {email_answer} | {password_answer}\n")
name_text.delete(0, 'end')
email_text.delete(0, 'end')
password_text.delete(0, 'end')
# ---------------------------- UI SETUP ------------------------------- #
window = Tk()
window.title('Password Manager')
# window.minsize(400,400)
window.config(padx=40, pady=40)
canvas = Canvas(height=200, width=200)
image = PhotoImage(file='logo.png')
canvas.create_image(100, 100, image=image)
canvas.grid(row=1, column=2)
name_label = Label(text="Website:")
name_label.grid(row=2, column=1)
name_text = Entry(width=39)
name_text.grid(row=2, column=2, columnspan=2)
name_text.focus()
email_label = Label(text="Email/Username:")
email_label.grid(row=3, column=1)
email_text = Entry(width=39)
email_text.grid(row=3, column=2, columnspan=2)
email_text.insert(0,"[email protected]")
password_label = Label(text="Password:")
password_label.grid(row=4, column=1)
password_text = Entry(width=21, textvariable=StringVar())
password_text.grid(row=4, column=2)
generate_password = Button(text="Generate Password", command=generate)
generate_password.grid(row=4, column=3)
add = Button(text="Add", width=36, command=save_text)
add.grid(row=5, column=2, columnspan=2)
window.mainloop() |
91359afece49e2aa34f686c2ea6f8d5d39319f00 | gahakuzhang/PythonCrashCourse-LearningNotes | /9.classes/9.1.2 dog.py | 1,273 | 4.71875 | 5 | #9.1.2 making an instance from a class 根据类创建实例
# accessing attributes 访问属性
class Dog():
"""a simple attempt to model a dog"""
def __init__(self,name,age):
"""initialize name and age attributes 初始化属性"""
self.name=name
self.age=age
def sit(self):
"""simulate a dog sitting in response to a command"""
print(self.name.title()+" is now sitting.")
def roll_over(self):
"""simulate rolling over in response to a command"""
print(self.name.title()+" rolled over!")
my_dog=Dog('willie',6)
print("My dog's name is "+my_dog.name.title()+".")
print("My dog is "+str(my_dog.age)+" years old.")
# my_dog.name 句点表示法,表示访问实例的属性
# calling methods 调用方法
# class Dog():
# --snip--
#
# my_dog=Dog('willie',6)
# my_dog.sit()
# my_dog.roll_over()
# creating multiple instances
# class Dog():
# --snip--
#
# my_dog=Dog('willie',6)
# your_dog=Dog('lucy',3)
# print("My dog's name is "+my_dog.name.title()+".")
# print("My dog is "+str(my_dog.age)+" years old.")
# my_dog.sit()
# print("\nYour dog's name is "+my_dog.name.title()+".")
# print("Your dog is "+str(your_dog.age)+" years old.")
# your_dog.sit() |
fbd421dc8e8edc5cc16a3d1857c53a0a6bf00dfc | Veterun/Interview-1 | /language/python/note.py | 3,407 | 4.34375 | 4 | #comparison chaining
testing whether a number is the largest of three: a < x > b
a == b < c actually means a == b and b < c in python!
******************
str.join(iterable)
#Return a string which is the concatenation of the strings in the iterable iterable
ex : ["->".join(["22","33","11"])]
['22->33->11']
**********************
Map(function, iterable)
Return an iterator that applies function to every item of iterable,
yielding the results. If additional iterable arguments are passed,
function must take that many arguments and is applied to the items from all iterables in parallel.
With multiple iterables, the iterator stops when the shortest iterable is exhausted.
**************************
`n`
Backquotes calls the __repr__() , so the result would be a string rather than a int
compute the “official” string representation of an object
r[1:] = `n`
it replaces everything after the first element in r (or everything, in case r is empty) by just n
——————————————————————————————————————————————————————————————————————————————————————————————
enumerate(iterable, start=0)
Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
**************
zip(*iterables)
# zip('ABCD', 'xy') -->[ Ax By ]
Make an iterator that aggregates elements from each of the iterables.
Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.
zip() in conjunction with the * operator can be used to unzip a list:
#zip(*iterables)
#Make an iterator that aggregates elements from each of the iterables.
#s=Counter({'1': 1, '0': 1, '2': 1})
#d=Counter({'1': 1, '0': 1, '3': 1})
#zip (s,d)
#[('1', '1'), ('0', '0'), ('2', '3')]
*************************
Lambda expressions (sometimes called lambda forms) are used to create anonymous functions.
The expression ** lambda arguments: expression ** yields a function object.
The unnamed object behaves like a function object defined with
*********************
reduce(function, iterable[, initializer])
Apply function of two arguments cumulatively to the items of sequence, from left to right,so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).
The left argument, x, is the accumulated value and the right argument, y, is the update value from the sequence.
If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
If initializer is not given and sequence contains only one item, the first item is returned.
*****************************
collections.counter return a dict(key:value),
It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values
for counting the hashable obejects
collections.Counter("102")
Counter({'1': 1, '0': 1, '2': 1})
|
35944d653998cddab0a3e4a228b853f0f864124f | juliadejane/CursoPython | /ex017.py | 179 | 3.625 | 4 | import math
c1 = float(input('Qual é a medida de um cateto? '))
c2 = float(input('Qual é a medida do outro cateto? '))
print('A hipotenusa é {:.2f}'.format(math.hypot(c1, c2))) |
ecad01e55c18479cbee5aff3242b78dceab4091e | Success2014/Leetcode | /maximumDepthofBirnaryTree.py | 1,386 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 22 12:52:21 2015
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path
from the root node down to the farthest leaf node.
Tags: Tree Depth-first Search
Similar Problems (E) Balanced Binary Tree (E) Minimum Depth of Binary Tree
@author: Neo
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param {TreeNode} root
# @return {integer}
"""
recursive
"""
def maxDepth(self, root):
if root is None:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
"""
iterative, use two stacks, one for node, one for tracking node level
"""
def maxDepthIter(self, root):
if root is None:
return 0
depth = 1
stack = [root] # stack
level = [1]
while stack:
s = stack.pop()
l = level.pop()
if l > depth:
depth = l
if s.left is not None:
stack.append(s.left)
level.append(l + 1)
if s.right is not None:
stack.append(s.right)
level.append(l + 1)
return depth
|
75b50501d33d3a2ecc33d28e4c10008a8f9ea6c8 | smiroshnikov/ebaPo4tu | /haim/lecture3/practice3.py | 1,247 | 4.09375 | 4 | import fractions
a = 3
b = 4
print("hello" if b > a else "salam")
print('haifa' if b > a and b > 0 else 'ramat gan')
print(109 if a > b else "rehovot")
print("tel aviv" if 'a' in 'abcd' else 'noope')
print('blue ' if 'b' not in "moish" else "red")
print('winter ' if a > 2 and a % 2 == 1 else "summer")
print(123 if 'y' not in 'yahoo' else 'x')
a = fractions.Fraction(3, 4)
b = fractions.Fraction(3, 4)
c = fractions.Fraction(6, 8)
d = a
print(a is b)
print(a is d)
print(a == b)
print(a == c)
print(d is not a)
print(a < b)
a = {1, 2, 3}
b = {2, 3, 4}
print((a | b)) # union
print((a & b)) # bitwise XOR set symmetric difference
print((a ^ b)) # bitwise AND, Set intersection
print((a - b)) # bitwise subtraction, set difference
a = [1, 2, 3]
b = [5, 6, 7]
c = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a * 2)
print(b * 3)
print(71 / 5)
print(71 // 5)
print(2 ** 3)
print(4 ** 2)
print(a[1])
print(b[2])
print(a[0])
print(c[2:7])
a = 12
b = 24
c = 7
print(c < a < b)
print(a < b < c)
print(c < a < b)
num = (a +
b +
c +
d)
ob = a, b, c = 'aaa', 'bbb', 'ccc'
[a, b, c] = [1, 2, 3]
text = "fuck"
[a, b, c, d] = text
print("part 2 ")
[a, b, *c] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(a, b)
print(c)
a = b = c = 'xyz'
|
b7a4e06cd313134bba3d7914d06c545f0feb9535 | mayankmahajan/datavalidation | /learnPython/passwordGenerator.py | 982 | 3.90625 | 4 | import random
def generatePassword(strength):
lowerCap = False
upperCap = False
numChar = False
specialChar = True
password = ''
while True:
randomInt = random.randrange(32,126)
if randomInt in range(48,58):
numChar = True
password = password + chr(randomInt)
elif randomInt in range(65,91):
upperCap = True
password = password + chr(randomInt)
elif randomInt in range(97,123):
lowerCap = True
password = password + chr(randomInt)
else:
specialChar = True
password = password + chr(randomInt)
if strength == 's' and numChar and upperCap and lowerCap and specialChar and len(password)>=6:
return password
if strength == 'w' and len(password)>=6:
return password
if __name__ == '__main__':
strength = raw_input("Enter strength w/s: ")
print generatePassword(strength)
|
4943e3a4e1052cf99184daa0dd613c99c4713de3 | SociallyAwkwardTurtle/Python | /kilpkonn.py | 282 | 3.765625 | 4 | #Karolina 10IT
from turtle import*
col = input("What is your favourite colour? ")
side = input("How long should the side be? ")
color(col)
begin_fill()
forward(int(side))
left(90)
forward(int(side))
left(90)
forward(int(side))
left(90)
forward(int(side))
end_fill()
exitonclick() |
140d044640b7a648fb5f8a610c5ba81adf1e4020 | stasi009/FDSA | /hanoi_tower.py | 1,698 | 4.21875 | 4 |
def __move(N,frompole,topole,withpole):
"""
plate 1~N are on from pole
we are going to move plate 1~N from 'frompole' to 'topole' via 'withpole'
"""
if N == 1:
print "%d: %s ==> %s"%(N,frompole,topole)# move directly
else:
__move(N-1,frompole,withpole,topole)
print "%d: %s ==> %s"%(N,frompole,topole)
__move(N-1,withpole,topole,frompole)
def move(N):
__move(N,"L","R","M")
move(3)
############################## print out pole status at each time
class Pole(object):
def __init__(self,name,N=0):
self.name = name
self.items = range(N,0,-1)
def push(self,e):
self.items.append(e)
def pop(self):
return self.items.pop() # pop from tail only O(1)
def display(self):
print "%s: %s"%(self.name," ".join((str(e) for e in self.items)))
class HanoiTower(object):
def __init__(self,N):
self.N = N
self.poles = [Pole("L",N),Pole("M"),Pole("R")]
self.counter = 0
def display(self):
for p in self.poles:
p.display()
def __move(self,n,frompole,topole,withpole):
if n>=1:
self.__move(n-1,frompole,withpole,topole)
self.counter +=1
top = frompole.pop()
assert top == n # the last one
topole.push(top)
print "\n[%-3dth] disk#%-3d: %s ===> %s"%(self.counter,top,frompole.name,topole.name)
self.display()
self.__move(n-1,withpole,topole,frompole)
def move(self):
self.display()
self.__move(self.N,self.poles[0],self.poles[2],self.poles[1])
ht = HanoiTower(10)
ht.move()
|
21481840664b9b9eff9f9fb4e6a2781d6a3aa6f2 | stalnaya/H__W | /task_01_01.py | 92 | 3.640625 | 4 | y=int(input())
if ((y%4==0) and (y%100 != 0)) or (y%400==0): print ('yes')
else: print('no') |
49eee157f074aeb05e323bf592ebc4e05ecb39fc | chhenning/python_tutorial | /Advent Of Code/2018/8/solution_2.py | 870 | 3.5 | 4 |
# %%
input = '2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2'
with open('8/input.txt') as fp:
input = fp.readline()
it = map(int, input.split())
counter = 0
def parse(it):
global counter
num_childs, num_meta = next(it), next(it)
name = chr(ord('A') + counter)
counter += 1
childs = [parse(it) for c in range(num_childs)]
meta = [next(it) for m in range(num_meta)]
return (name, childs, meta)
root = parse(it)
# print(root)
# %%
# only leaf nodes (no childs) sum their meta data
# if a node has childs use the meta as references
# to the childs
def node_value(node):
name, childs, meta = node
if childs:
return sum(node_value(childs[i-1])
for i in meta if 1 <= i <= len(childs))
else:
return sum(meta)
print(node_value(root))
# %%
a = 0
a = 1
if 1 <= a <= 10:
print('possible')
|
55ed781220297c41bfd9ddc6de6e4a6bf195f989 | txjzwzz/leetCodeJuly | /Decode_Ways.py | 1,205 | 4.03125 | 4 | #-*- coding=utf-8 -*-
__author__ = 'zz'
"""
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding "12" is 2.
"""
class Solution(object):
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
if not s or s[0] == "0":
return 0
matrix = [1 for i in range(len(s)+1)]
asc_6 = ord('6')
for i in range(1, len(s)):
if s[i] == '0':
if s[i-1] != '1' and s[i-1] != '2': # invalid
return 0
else:
matrix[i+1] = matrix[i-1]
else:
if s[i-1] == '1' or (s[i-1] == '2' and ord(s[i]) <= asc_6):
matrix[i+1] = matrix[i] + matrix[i-1]
else :
matrix[i+1] = matrix[i]
return matrix[len(s)]
if __name__ == '__main__':
solution = Solution()
print solution.numDecodings("12") |
06cf5e2c10cbb82b026f6eb33e2462c535f3a1b9 | trangnguyen1010/python | /functions.py | 2,233 | 3.703125 | 4 | import random
from collections import namedtuple
global connection, cursor
import sys
def luhn_algorithm(acc_number):
acc_number = list(map(int, str(acc_number)))
for i, _ in enumerate(acc_number, 1):
if i % 2 != 0:
acc_number[i-1] *= 2
if acc_number[i-1] > 9:
acc_number[i-1] -= 9
return sum(acc_number)
def checksum(sum_number):
return 10 - sum_number % 10 if sum_number % 10 != 0 else 0
def generate_account():
account_number = 400000000000000 + random.randint(000000000, 999999999)
luhn_num = luhn_algorithm(account_number)
checksum_number = checksum(luhn_num)
card_number = account_number*10 + checksum_number
return card_number
def check_card(card_number):
luhn_num = luhn_algorithm(card_number[:-1])
check_sum = checksum(luhn_num)
return check_sum == int(card_number[-1])
def generate_pin():
pin = ""
for _ in range(4):
pin += str(random.randrange(10))
return pin
def log_in_card_num() -> int:
print()
return int(input("Enter your card number:\n"))
def log_in_pass() -> int:
print()
return int(input("Enter your PIN:\n"))
def balance_input() -> int:
print()
return int(input("1. Balance\n2. Log out\n0. Exit\n"))
def balance():
print()
print("Balance: 0")
def log_out():
print()
print("You have successfully logged out!")
def compare(card_n, pin_n) -> int:
global account
global password
if card_n == account:
if pin_n == password:
print("You have successfully logged in!")
return 1
else:
return 0
def exit():
print("Bye!")
connection.close()
sys.exit()
import sqlite3
from collections import namedtuple
conn = sqlite3.connect('card.s3db')
cursor = conn.cursor()
card_number = '4000000457698704'
Account = namedtuple('Account', 'id, card, pin, balance')
cursor.execute('select * from card')
list_card_balance = {}
for acc in map(Account._make, cursor.fetchall()):
list_card_balance[acc.card] = acc.pin
balance = list_card_balance[card_number]
print("Balance: ", balance)
print(list_card_balance) |
d26edaccbd046da13fe6d69a578c235769055b32 | rishi772001/Competetive-programming | /Algorithms/Dynamic Programming/01 knapsack.py | 960 | 3.640625 | 4 | '''
@Author: rishi
https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/
'''
def knapsack(totweight, wt, val, n):
"""
:param totweight: total weight of knapsack
:param wt: weight array of items
:param val: values array of items
:param n: number of items or len of wt or val
"""
dp = [[0 for x in range(totweight + 1)] for x in range(n + 1)]
for i in range(n + 1):
for w in range(totweight + 1):
# if this item can be added
if wt[i - 1] <= w:
# find max of this item added and not added
# if added we need to check for that weight(curr wt - the wt of added item)
dp[i][w] = max(val[i - 1] + dp[i - 1][w - wt[i - 1]],
dp[i - 1][w])
else:
dp[i][w] = dp[i - 1][w]
return dp[-1][-1]
items = [1, 2, 3]
values = [2, 5, 3]
totwt = 4
print(knapsack(totwt, items, values, len(items)))
|
aa1f63db7444dcdfe7d5e894bdbf02c36c01a874 | shrenik-jain/HackerRank-Solutions | /1.Python/05.Math/002.FindAngleMBC.py | 322 | 4.0625 | 4 | '''
Question : You are given the lengths AB and BC.
Your task is to find angle MBC (angle theta, as shown in the figure) in degrees.
Link : https://www.hackerrank.com/challenges/find-angle/problem
'''
import math
a = int(input())
b = int(input())
print(round(math.degrees(math.atan(a/b))), u'\N{DEGREE SIGN}' , sep='')
|
60feef496ed09e8c327ca1753229dba5cf1a66f1 | chanmile/Cryptography | /fermat_factorization.py | 1,253 | 4.4375 | 4 | #
# Fermat's Factorization Method
#
# Author: chanmile
'''
Fermat's Factorization method relies on the following equation:
N = a^2 - b^2 = (a+b)(a-b)
If (a+b) != 1 and (a-b) != 1, then N has been factored.
Starting at a = sqrt(N), we will compute various values of b^2 using
b^2 = a^2 - N
We compute b by computing sqrt(b^2), and if b is an integer (if b is a square),
then we have found a and b that satisfy (a+b)(a-b) and we have factored N.
From Wikipedia:
For N with multiple prime factors, Fermat's Factorization method will return the
factorization with the least values of a and b. That is, a+b is the smallest factor
>= sqrt(N) and a-b is the largest factor <= sqrt(N)
'''
import math
def fermat_factor(composite_N):
'''
Please restrict usage to composite_N > 3
'''
lowBound_N = math.ceil(math.sqrt(composite_N))
upBound_N = composite_N-1
print('Attempting to factor %s' % composite_N)
for a in range(lowBound_N,upBound_N):
b_squared = a**2 - composite_N
b = math.sqrt(b_squared)
if b.is_integer():
print('Found factorization (%s, %s)' % (int(a+b),int(a-b)))
return (int(a+b),int(a-b))
return None
|
c37dc6c4343d633be027a5c0e74822e851451ae9 | Panuvat-Dan/100-Day-project | /day2/Day2-tip-genarator.py | 734 | 4.15625 | 4 | # Greeting users
print("Welcome to the tip calculator")
individual_pay = 0
while individual_pay >= 0 :
# to ask user the total bill
total_bill = input("What was the total bill?: ")
# to ask percentage tip
percentage_tip = input("What was your tip would you like to give? 10 or 12 or 15%: ")
# to ask the number of people sharing
number_sharing = input("How many people to split the bill: ")
# calulating the bill for each
total_bill_integer = int(total_bill)
percentage_tip_interger = int(percentage_tip)
number_sharing_interger = int(number_sharing)
individual_pay = (total_bill_integer * 1+(percentage_tip_interger/100)) / number_sharing_interger
print(f"Each person should pay {individual_pay} $.")
|
71c72c92b258285239ea15db1de67bff49254bbe | lucas-deschamps/tiny-python-PoC | /numerosprimos_trabalho.py | 716 | 4.09375 | 4 | # a small program that prints out all prime numbers in a user-defined range.
# written for a college assignment.
numeros_primos = []
numero_inicial = int(input("\nDigite o número inicial: \n"))
numero_final = int(input("Digite o número final: \n"))
range_primos = range(numero_inicial, numero_final)
print(f"\n\t\t\t[Números primos entre {numero_inicial} e {numero_final}.]\n")
for numero in range_primos:
if numero > 1:
for divisor in range(2, numero):
if numero % divisor == 0:
break
else:
numeros_primos.append(numero)
print(f"Números primos: {numeros_primos}")
print("\nNúmeros primos são os números somente divisíveis por si mesmos e 1.")
|
5402068009616069a4f436d2ddd990bdb1aed7c6 | rosauraruiz-lpsr/class-samples | /chooseHaiku.py | 498 | 3.9375 | 4 | # Opens the haiku 3 and 4
myThirdHaiku = open('haiku3.txt', 'r')
myFourthHaiku = open('haiku4.txt', 'r')
# Welcomes you and gives you options
print("Hi, welcome to the Haiku Reader!")
print(" 3 For a haiku about a silly person. ")
print(" 4 For a haiku about writing haiakus. ")
response = raw_input()
# It will print the 3rd haiku if 3 was inserted
if response == '3':
print(myThirdHaiku.read())
# It will give the 4th haiku if 4 was inserted
elif response == "4":
print(myFourthHaiku.read())
|
46fc2c7caeb690e77e9d38aa849612a16e64c359 | shamanengine/HackerRank | /src/18_stuff/task01.py | 247 | 3.59375 | 4 | '''
Sum all 2-digit numbers from the sequence
'''
arr = list(map(int, input().strip().split()))
print(sum([x for x in arr if (10 <= x <= 99) or (-99 <= x <= -10)]))
'''
Input
1 2 3 11 322 20 9989 99
1 2 3 11 322 20 9989 -99
Output
130
-68
'''
|
3dfee1aeb967e714860bc24630e4793001023aef | WeeJang/basic_algorithm | /LinkedListCycle.py | 779 | 3.953125 | 4 | #!/usr/bin/env python2
#-*- coding:utf-8 -*-
"""检测环,快慢指针 """
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: head: The first node of linked list.
@return: True if it has a cycle, or false
"""
def hasCycle(self, head):
# write your code here
if head is None:
return False
slow_p,fast_p = head,head.next
while True:
if fast_p == None:
return False
if slow_p == fast_p:
return True
if fast_p.next == None:
return False
fast_p = fast_p.next.next
slow_p = slow_p.next
|
d516acdb263862143336541eaed3d8ca03e6c2ea | kstager/Python300-SystemDevelopmentWithPython-Spring-2014 | /week-06/datetime/examples/datetime_naive_to_sqlite.py | 1,158 | 3.96875 | 4 | import datetime
import itertools
import sqlite3
import pytz
"""Dates and times in sqlite3 are stored as TEXT, REAL, or INTEGER values
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
sqlite3 will handle the translation from datetime to strings
"""
input_values = []
input_values.append([datetime.datetime(2019,11,1,12,0)])
input_values.append([datetime.datetime(2019,11,1,13,0)])
# input_values.append([datetime.datetime(2019,11,1,12,0,tzinfo=pytz.UTC)])
conn = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
cursor = conn.cursor()
cursor.execute("CREATE TABLE timetable(t timestamp)")
cursor.executemany("INSERT INTO timetable(t) VALUES (?)", input_values)
for row,input_value in itertools.izip(cursor.execute("SELECT t FROM timetable"), input_values):
from_db = row[0]
from_input = input_value[0]
print from_db
print type(from_db)
print from_input
assert(from_db == from_input)
|
42cc260b3b53e13ef8f99713a53e55c056ae6e84 | danielgu88/bill-splitter | /stage2.py | 525 | 4.125 | 4 | list_of_friends = []
friends_dict = {}
friends = int(input("Enter the number of friends joining (including you):\n"))
if friends >= 1:
print("\nEnter the name of every friend (including you), each on a new line:")
for i in range(friends):
list_of_friends.append(input())
print("\nEnter the total bill value:")
bill = int(input())
friends_dict = dict.fromkeys(list_of_friends, round(bill / friends, 2))
print()
print(friends_dict)
else:
print("\nNo one is joining for the party")
|
a895728f18ef4173e12440ce680c04205882d878 | prajjaldhar/basic_python | /basic_python/09_dictionary.py | 1,002 | 3.9375 | 4 | #indexed
#mutubale
#unordered
#must have unique keys
mydict={
"fast":"car",
"mahatma":"Gandhi",
"knowledge":"vivekenand",
"pacer":"cheeta",
"captain":"prajjal",
"honest":"harsihchandra",
"marks":[1,3,5],
"anotherdict":{"brothers":"Prajjal,Abhra,Shubra"},
"anothertuple":(1,2,3)
}
print(mydict)
print(mydict["honest"])
print(mydict["anotherdict"]["brothers"])
print(mydict.values())
print(mydict["anotherdict"].values())#printing values of dict inside dict
print(mydict["anothertuple"][0])#printing value of tuple inside dict using indexing
print(mydict.keys())
print(mydict.items())#prints key value pair in tuple format
update_dict={
"Friends_list":["abhitesh","raj","terminal-xd"],
"Enemy_list":["thanos","gogo"]
}
mydict.update(update_dict)
print(mydict)
print(mydict.get("prajjal",-1))#.get method never throughs an error,if key is not present-->dict.get("value",default_value)
#print(mydict["prajjal"])#returns keyerror
|
10244dfc2865dd651b03225b0d3e41f190195019 | shuzhancnjx/leetcode- | /Programming-Algorithm/Jump_Game_II.py | 1,771 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 21 14:55:13 2015
@author: ZSHU
"""
"""
recursive and greedy, but too many recursive steps and over the limit
"""
nums = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
nums=[1,2,3]
move=0
level=1
res=[len(nums)]
def jump(move, nums, level, res):
if move+nums[move]>=len(nums)-1:
if res[0]>level: res[0]=level
return
elif move>=len(nums) or level>=res[0] or nums[move]==0:
return
else:
temp=move
for i in range(1, nums[move]+1):
if nums[i+move]+i+move>temp+nums[temp]:
temp=i+move
jump(temp, nums, level+1, res)
""""
Greedy, the maximum movement in every step
贪心算法,每次前移最大宽度
"""
class Solution:
# @param {integer[]} nums
# @return {integer}
def jump(self, nums):
if len(nums)==1: return 0
else:
temp, move,level=0,0,1
while move <len(nums) and temp<len(nums) and level<len(nums):
for i in range(0, nums[move]+1):
if nums[i+move]+i+move >= len(nums)-1:
if i==0: return level
else: return level+1
else:
if nums[i+move]+i+move>temp+nums[temp] and nums[i+move]!=0:
temp=i+move
move=temp
level+=1
return None |
f1789b8d178f5a4dfc646d0bdc648f5fd610cf79 | FatalTsai/Data-Structures-and-Algorithms | /Data Structures/Graph/BFS.py | 397 | 3.859375 | 4 | import collections
def BFS(g, r):
visited = set()
queue = collections.deque([r])
while queue:
v = queue.popleft()
print(v)
for nbr in graph[v]:
if nbr not in visited:
visited.add(nbr)
queue.append(nbr)
if __name__ == "__main__":
graph = {0:[1,2], 1:[0,3], 2:[0], 3:[1]}
BFS(graph,0)
# BFS(graph,1)
|
3af5c6a803ae19375ead94f947238231ca57a2b5 | UKDR/eng57_2 | /Week_3_Python/Exercises/102_more_strings_variables.py | 698 | 4.09375 | 4 | # Practice strings
# Welcome to Sparta - exercise
# Version 1 specs - with concatenation
# define a variable name, and assign a string
# prompt the user for input and ask the user for his/her name
# re assign the original variable this this input
# use concatenation to print a welcome message and use methods to format the name/input (remove white spaces)
# Version 2 - with interpolation
# ask the user for a first name, save it in a variable
# ask the user for a last name, save it in a variable
# use interpolation to print the message
# Calculate year of birth
# gather details on age and name
# print something like
# OMG <person>, you are <age> years old so you were born in <year> |
26f9468d089f17977f201176ae635f00567b4219 | jemcghee3/ThinkPython | /06_11_exercise_4.py | 698 | 4.21875 | 4 | """Exercise 4
A number, a, is a power of b if it is divisible by b and a/b is a power of b.
Write a function called is_power that takes parameters a and b and returns True if a is a power of b.
Note: you will have to think about the base case."""
def is_power(a, b):
if a < 0 and b < 0: # to take care of negative numbers
a = -a
b = -b
if b == 1 or b == -1: # to end infinite recursion if b == 1
return False
if a % b != 0 and a >= 1 and b >= 1: # if a is not divisible by b
return False
if -1 < a < 1 or -1 < b < 1:
if b < a:
return False
if a == b:
return True
return is_power(a/b, b)
print(is_power(-8, -2)) |
7ce76a9af58986a37151e63036edf1da66f33f39 | Nishantballa16/ATM_program_python | /ATM Project/atmdemo.py | 1,053 | 3.53125 | 4 | #atmdemo.py---main program
from atmmenu import menu
from bankexcep import DepositError,WithdrawError,InSuffFundError
from bankoperations import deposit,withdraw,balenq
import sys
while(True):
try:
menu()
ch=int(input("Enter Ur Choice:"))
if(ch==1):
try:
deposit()
except DepositError:
print("Don't Try to deposit -ve / zero Values:")
except ValueError:
print("Don't enter strs / special symbols and alpha-numerics for deposits")
elif(ch==2):
try:
withdraw()
except WithdrawError:
print("Don't Try to Withdraw -ve / zero Values:")
except InSuffFundError:
print("U don't have sufficient Funds!")
except ValueError:
print("Don't enter strs / special symbols and alpha-numerics for withdarw")
elif(ch==3):
balenq()
elif(ch==4):
print("Thanks for using this ATM:")
sys.exit()
else:
print("Ur Choice of Operation is wrong--try again")
except ValueError:
print("Don't enter strs / special symbols and alpha-numerics for choice of operation:") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.