blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
79d53a38bbd5724729c41638dfc8755aa0517dd4 | thewinterKnight/Python | /dsa/Linked Lists/4.py | 1,947 | 4.40625 | 4 | # How do you reverse a singly linked list without recursion?
import copy
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_next(self, new_node):
self.next = new_node
class LinkedList(Node):
def __init__(self, head=None):
self.head = head
def insert_node(self, data):
if self.head is None:
self.head = Node(data)
else:
ptr = self.head
while ptr.get_next() is not None:
ptr = ptr.get_next()
ptr.set_next(Node(data))
def print_linked_list(self):
if self.head is None:
print("Nothing to print\n")
return
ptr = self.head
while ptr is not None:
print(ptr.get_data())
ptr = ptr.get_next()
def reverse_linked_list(ptr):
ptr1 = ptr.get_next()
ptr2 = ptr1.get_next()
ptr.set_next(None)
while ptr2 is not None:
ptr1.set_next(ptr)
ptr = ptr1
ptr1 = ptr2
ptr2 = ptr2.get_next()
ptr1.set_next(ptr)
ptr = ptr1
global reverse_head
reverse_head = ptr
if __name__ is "__main__":
linked_list = LinkedList()
linked_list.insert_node(5)
linked_list.insert_node(10)
linked_list.insert_node(15)
linked_list.insert_node(20)
linked_list.insert_node(25)
linked_list.insert_node(30)
linked_list.insert_node(35)
linked_list.insert_node(40)
linked_list.print_linked_list()
print("Reversing...\n")
copy_linked_list = copy.deepcopy(linked_list)
reverse_linked_list(copy_linked_list.head)
reverse_linked_list = LinkedList(reverse_head)
reverse_linked_list.print_linked_list()
print('\n\nOriginal linked list(after reversed list is generated...) :\n')
linked_list.print_linked_list()
|
30ff67d5f30f79a7ef343623320227d1d5a46464 | maurya20/assignment2 | /task3.py | 1,062 | 4.15625 | 4 | str = "i like sam sung samsung mobile ice cream icecream man go mango"
dict = str.split() # Making a list of stored dicttionary words.
input_string = input("Enter your string:") # Taking a string input from user.
out = [] # An empty list.
for x in dict: # Looping in the stored dicttionary words.
if (input_string.find(x) == -1):
pass # If it is not found in input string, do nothing.
else:
out.append(x) # If it is found in input string, append it in out = [] list.
if not out:
print("Input not found in dictionary.") # If out is empty print this.
else:
print("Yes, the string can be segmented as-") # If out is not empty print this.
foundstr = ' '.join(out) # Converting out list in a space segmented string.
print(foundstr) # printing space segmented string.
|
1d54857b26a727e011993a813cdff4267426222b | Arjun-N-Koushik/NewHack | /set.py | 583 | 3.6875 | 4 | s = set()
a = [1,2,3,4]
s_from_list = set(a)
print(s_from_list)
print(type(s_from_list))
s.add(1)
s.add(2)
s.add(3)
print(s_from_list)
s1 = s.isdisjoint({4,5,6})
print(s1)
# a = 56
# b = 62
# print("Enter your Age..")
# age = int(input())
# # c = int(input())
#
# if age>100 or age<7 :
# print("Enter the age between 7 and 100")
# elif age > 18 :
# print("Congratulations \n You are eligible to drive!!")
# elif age == 18:
# print("Opps!! \n You need to get in touch with us..")
# else:
# print("We're Sorry!! \n You're not eligible to drive") |
41260a59af5469d2c603a7fe48b26881abcb4b7d | jaysurn/Leetcode_dailies | /Longest_Non_repeating_Substring.py | 1,536 | 4.28125 | 4 | # Goal : Given a string, find the length of the longest substring ( i.e. abcabcbb: abc , bbbb: b )
# Given : Single string
# Assumption : String consists only of letters , numbers, and symbols
def longest_substr_len( string ):
len_max = 0 # Used to record length
start = 0 # Used to track beginning index of current substring
hash = {} # Used to track non-repeating characters
for i , char in enumerate( string ): # Enumerate to get index value and character
if char in hash and start <= hash[char]: # If character is repeated, check if it starts after current start point
start = hash[char] + 1 # Update substring start point ( +1 since index starts at 0 )
else:
len_max = max( len_max , i - start + 1 ) # Update longest substring length
hash[char] = i # Enter character into dict with current index
return len_max
def main():
str1 = "racecar" # User defined teststring 1
str2 = "tmmzuxta" # User defined teststring 2 using repeating characters
str3 = "6.02234" # User defined teststring 3 using symbols
print( "Finding length of longest substring of {0}".format( str1 ) )
res_val = longest_substr_len( str1 )
print( res_val )
print( "Finding length of longest substring of {0}".format( str2 ) )
res_val = longest_substr_len( str2 )
print( res_val )
print( "Finding length of longest substring of {0}".format( str3 ) )
res_val = longest_substr_len( str3 )
print( res_val )
main() |
b8ca7bc1faed5e8b9bc2ca57677c2b4083e185cc | cookies5127/algorithm-learning | /leetcode/default/24_swap_pairs.py | 1,243 | 3.921875 | 4 | from utils import build_list_node
from utils.types import ListNode
'''
24. Swap Noeds in Pairs
Given a linked list, swap every two adjacent nodes and return ints head.
You may not modify the values in the list's node, only ondes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
'''
'''
解题思路:
1. 交换偶数位置的节点,中间的位置存在上下关系。
2.
'''
EXAMPLES = [
(
build_list_node(1, 2, 3, 4),
build_list_node(2, 1, 4, 3),
),
]
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head:
return []
node = head.next
if node is None:
r = head
else:
head.next = node.next
node.next = head
r = node
i = 1
while node is not None:
prev_node = node
node = node.next if node else None
next_node = node.next if node else None
if i % 2 == 0 and next_node:
node.next = next_node.next
prev_node.next = next_node
next_node.next = node
node = next_node
i += 1
return r
|
9569db4c45da84ff4ba6e948747ad74ad10f72c5 | manhar336/manohar_learning_python_kesav | /Operators/Membershipoperators.py | 1,242 | 4.65625 | 5 | '''--------------------------------------------------------------'''
# 6. Membership Operators :
'''--------------------------------------------------------------'''
'''
in and not in are the membership operators in Python.
They are used to test whether a value or variable is found in a sequence
(string, list, tuple, set and dictionary).
# Membership operators test for membership in a sequence, such as
# strings, lists, or tuples.
1. in = x in y, here in results in a 1 if x is a member of sequence y.
2. not in = x not in y, here not in results in a 1 if x is not a member of sequence y.
'''
'''--------------------- Examples ----------------------------'''
#Example #5: Membership operators in Python
"""
x = 'Hello world'
y = {1:'a',2:'b'}
# Output: True
print('H' in x)
# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
# Output: False
print('a' in y)
"""
a = "python world"
b = {"name":"manohar","age":36}
c= [1,2,3,4]
print("python" in a) # here condition is true
print("python" not in a) # Here condition is false
print("name" in b) #Here condition is True
print("manohar" in b) #Here we can not call values in dictionary and we can call only keys
print(type(c),"10" in c)
print("20" not in c) |
622dfcaa9419e0bd470f2aa01b944ea3fbfd849e | Xn-qon7tvkkj/Landscape | /Landscape.py | 5,615 | 3.625 | 4 | import turtle
la = turtle.Turtle()
tr = turtle.Turtle()
ho = turtle.Turtle()
su = turtle.Turtle()
no = turtle.Turtle()
turtle.bgcolor("blue")
def wall(side):
for size in range(4):
ho.forward(200)
ho.left(90)
def pane(side):
for size in range(4):
ho.forward(12)
ho.left(90)
def triangle(side):
for size in range(3):
ho.forward(5)
ho.left(80)
def land(side):
for size in range(2):
la.forward(800)
la.right(90)
la.forward(600)
la.right(90)
def roof(side):
for size in range(1):
no.forward(200)
no.left(120)
no.forward(200)
no.left(120)
no.forward(200)
def bars(side):
for size in range(2):
tr.left(90)
tr.forward(200)
tr.left(90)
tr.forward(15)
def ladder(side):
for size in range(1):
su.right(180)
su.forward(30)
su.right(180)
su.forward(30)
def bars3(side):
for size in range(2):
su.left(90)
su.forward(200)
su.left(90)
su.forward(35)
def slide(side):
for size in range(2):
no.left(89)
no.forward(50)
no.left(90)
no.forward(200)
def door(side):
for size in range(2):
no.right(90)
no.forward(90)
no.right(90)
no.forward(60)
def chimney(side):
for size in range(1):
tr.left(90)
tr.forward(90)
tr.left(90)
tr.forward(90)
tr.left(90)
tr.forward(90)
tr.left(90)
tr.forward(90)
def sun(side):
for size in range(65):
su.forward(10)
su.left(7)
def window(side):
for size in range(4):
ho.forward(25)
ho.left(90)
tr.fillcolor("white")
tr.penup()
tr.goto(360, 180)
tr.pendown()
tr.pencolor("white")
tr.begin_fill()
tr.circle(10, 180)
tr.goto(250, 180)
tr.circle(-10, 180)
tr.end_fill()
tr.fillcolor("tan")
tr.penup()
tr.goto(360, 25)
tr.pendown()
tr.pencolor("brown")
tr.begin_fill()
bars(1)
tr.end_fill()
tr.fillcolor("tan")
tr.penup()
tr.goto(280, 25)
tr.pendown()
tr.pencolor("brown")
tr.begin_fill()
bars(1)
tr.end_fill()
tr.fillcolor("brown")
tr.penup()
tr.goto(200, 35)
tr.pendown()
tr.pencolor("brown")
tr.begin_fill()
bars(1)
tr.end_fill()
tr.fillcolor("brown")
tr.penup()
tr.goto(200, 220)
tr.right(90)
tr.pendown()
tr.pencolor("brown")
tr.begin_fill()
bars(1)
tr.end_fill()
tr.fillcolor("gray")
tr.penup()
tr.goto(10, 260)
tr.pendown()
tr.pencolor("gray")
tr.begin_fill()
chimney(1)
tr.end_fill()
tr.fillcolor("black")
tr.penup()
tr.goto(350, 75)
tr.pendown()
tr.pencolor("black")
tr.begin_fill()
tr.right(90)
tr.forward(70)
tr.left(90)
tr.forward(10)
tr.left(90)
tr.forward(70)
tr.left(90)
tr.forward(10)
tr.end_fill()
ho.fillcolor("tan")
ho.penup()
ho.goto(-10, 50)
ho.pendown()
ho.pencolor("black")
ho.begin_fill()
wall(1)
ho.end_fill()
no.fillcolor("brown")
no.penup()
no.goto(100, 140)
no.pendown()
no.pencolor("brown")
no.begin_fill()
door(1)
no.end_fill()
ho.fillcolor("yellow")
ho.penup()
ho.goto(-3, 138)
ho.pendown()
ho.pencolor("black")
ho.begin_fill()
window(1)
ho.end_fill()
ho.penup()
ho.goto(10, 150)
ho.pendown()
ho.pencolor("black")
pane(1)
ho.left(90)
pane(1)
ho.left(90)
pane(1)
ho.fillcolor("yellow")
ho.penup()
ho.goto(163, 163)
ho.pendown()
ho.pencolor("black")
ho.begin_fill()
window(1)
ho.end_fill()
ho.penup()
ho.goto(150, 150)
ho.pendown()
ho.pencolor("black")
pane(1)
ho.left(90)
pane(1)
ho.left(90)
pane(1)
la.fillcolor("yellow")
la.penup()
la.goto(50, 80)
la.pendown()
la.pencolor("black")
la.begin_fill()
la.circle(3, 360)
la.end_fill()
no.fillcolor("red")
no.penup()
no.goto(-10, 247)
no.pendown()
no.pencolor("red")
no.begin_fill()
roof(1)
no.end_fill()
la.fillcolor("green")
la.penup()
la.goto(-400, 60)
la.pendown()
la.pencolor("green")
la.begin_fill()
land(1)
la.end_fill()
no.fillcolor("gray")
no.penup()
no.goto(-200, -300)
no.pendown()
no.pencolor("gray")
no.begin_fill()
slide(1)
no.end_fill()
su.fillcolor("brown")
su.penup()
su.goto(-70, -320)
su.pendown()
su.pencolor("brown")
su.begin_fill()
bars3(1)
su.end_fill()
su.fillcolor("red")
su.penup()
su.goto(-65, -220)
su.pendown()
su.pencolor("yellow")
su.begin_fill()
ladder(1)
su.penup()
su.goto(-65, -240)
su.pendown()
ladder(1)
su.penup()
su.goto(-65, -260)
su.pendown()
ladder(1)
su.penup()
su.goto(-65, -280)
su.pendown()
ladder(1)
su.penup()
su.goto(-65, -300)
su.pendown()
ladder(1)
su.penup()
su.goto(-65, -200)
su.pendown()
ladder(1)
su.penup()
su.goto(-65, -180)
su.pendown()
ladder(1)
su.penup()
su.goto(-65, -160)
su.pendown()
ladder(1)
su.penup()
su.goto(-65, -140)
su.pendown()
ladder(1)
su.penup()
su.goto(-65, -120)
su.pendown()
ladder(1)
su.end_fill()
la.fillcolor("gray")
la.penup()
la.goto(-10, -400)
la.pendown()
la.pencolor("black")
la.begin_fill()
la.circle(-4, 360)
la.end_fill()
la.fillcolor("gray")
la.penup()
la.goto(-25, -400)
la.pendown()
la.pencolor("black")
la.begin_fill()
la.circle(-4, 360)
la.end_fill()
la.fillcolor("blue")
la.penup()
la.goto(-5, -400)
la.pendown()
la.pencolor("black")
la.begin_fill()
la.left(90)
la.circle(15, 180)
la.end_fill()
la.fillcolor("red")
la.penup()
la.goto(-5, -495)
la.pendown()
la.pencolor("red")
la.begin_fill()
triangle(1)
la.end_fill()
su.fillcolor("gold")
su.penup()
su.goto(300, 300)
su.pendown()
su.pencolor("orange")
su.begin_fill()
sun(1)
su.end_fill()
su.fillcolor("yellow")
su.penup()
su.goto(300, 380)
su.pendown()
su.pencolor("red")
su.begin_fill()
size = 1
for i in range(200):
su.forward(size)
su.right(138)
size += 1
su.end_fill()
turtle.exitonclick()
|
ffe9e6dde703c3b0a782db8d7fcd413e99b97ce3 | SylphDev/Actividades_Algoritmos | /prepas_ejercicios/4_semana/prepa_extra.py | 9,204 | 3.796875 | 4 | # Ejercicio Base de Datos
class Sirius:
'''
Base de datos de estudiantes de la UNIMET
'''
def __init__(self):
self.database = {}
def get_options(self):
'''
El usuario ingresa la opcion de lo que desea hacer en la base de datos
'''
valid = False
while valid is False:
try:
option = int(input("Que desea hacer?: "))
if option < 1 or option > 5:
print("La opcion ingresada no es valida")
else:
valid = True
except ValueError:
print("Debe ingresar un numero de las opciones indicadas")
return option
def add_student(self):
'''
Agrega un estudiante a base de datos. Requiere que el usuario ingrese cedula,
nombre, carnet, edad y materias cursando.
'''
student = input("Ingrese el nombre del estudiante: ")
valid = False
while valid is False:
try:
age = int(input("Ingrese la edad del estudiante: "))
id = int(input("Ingrese la cedula del estudiante: "))
student_id = int(input("Ingrese el carnet del estudiante: "))
valid = True
except ValueError:
print("Por favor ingrese los datos en numeros")
subject_valid = False
subjects = []
while subject_valid is False:
current_subject = input("Ingrese la materia que esta cursando: ")
subjects.append(current_subject)
more_subjects = input("Desea anexar mas materias? (Si o No): ")
if more_subjects == "no":
subject_valid = True
elif more_subjects == "si":
continue
else:
print("La opcion ingresada no es valida")
break
if student_id in self.database:
print("Ya existe un estudiante con este carnet")
else:
self.database[student_id] = {"Nombre": student, "Cedula": id, "Edad": age, "Materias": subjects}
def delete_student(self):
'''
Eliminar un estudiante de la base de datos
'''
valid = False
while valid is False:
try:
student = int(input("Ingrese el carnet del estudiante que desea eliminar: "))
valid = True
except ValueError:
print("Debe ingresar el numero de carnet del estudiante")
if student in self.database:
self.database.pop(student)
print("Se ha eliminado exitosamente")
else:
print("El estudiante NO esta en la base de datos")
def update_database(self):
'''
Actualizar los datos de un estudiante en la base de datos (nombre, carnet, cedula,
edad o materias)
'''
valid = False
while valid is False:
try:
student = int(input("Ingrese el carnet del estudiante que desea actualizar: "))
valid = True
except ValueError:
print("Debe ingresar el numero de carnet del estudiante")
if student in self.database:
valid = False
print("Puede actualizar:\n1. Nombre\2. Cedula\n3. Edad\4. Carnet\n5. Materias")
update_option = self.get_options()
if update_option == 1:
self.database[student]["Nombre"] = input("Ingrese el nuevo nombre del estudiante: ")
elif update_option == 2:
valid = False
while valid is False:
self.database[student]["Cedula"] = int(input("Ingrese la nueva cedula del estudiante: "))
valid = True
elif update_option == 3:
valid = False
while valid is False:
self.database[student]["Edad"] = int(input("Ingrese la nueva edad del estudiante: "))
valid = True
elif update_option == 4:
valid = False
while valid is False:
new_student_id = int(input("Ingrese el nuevo carnet del estudiante: "))
valid = True
self.database[new_student_id] = self.database.pop(student)
else:
valid = False
while valid is False:
try:
option = int(input("Desea agregar una materia (1), eliminar una materia (2) o reescribir las materias cursantes? (3): "))
if option > 0 and option < 4:
valid = True
else:
print("La opcion ingresada no es valida")
except ValueError:
print("Debe ingresar una opcion entre 1, 2 y 3")
if option == 1:
valid = False
while valid is False:
new_subject = input("Ingrese el nombre de la materia a agregar: ")
self.database[student]["Materias"].append(new_subject)
option = input("Desea agregar otra materia? (Si o No): ").lower()
if option == "si":
continue
elif option == "no":
valid = True
else:
print("La opcion ingresada no es valida")
break
elif option == 2:
delte_subject = input("Ingrese el nombre de la materia a eliminar: ")
if delte_subject in self.database[student]["Materias"]:
index = self.database[student]["Materias"].index(delte_subject)
self.database[student]["Materias"].pop(index)
print("La materia se elimino con exito")
else:
new_subjects = []
while valid is False:
current_subject = input("Ingrese las nuevas materia que esta cursando: ")
new_subjects.append(current_subject)
more_subjects = input("Desea anexar mas materias? (Si o No): ")
if more_subjects == "no":
valid = True
elif more_subjects == "si":
continue
else:
print("La opcion ingresada no es valida")
break
self.database[student]["Materias"] = new_subjects
else:
print("El estudiante NO esta en la base de datos")
def print_database(self):
'''
Imprime los estudiantes y sus datos de la base de datos
'''
if self.database == {}:
print("No hay estudiantes en la base de datos!!!!")
else:
print("\nLista de estudiantes:\n---------------------")
for id in sorted(self.database):
print(">>Nombre: {}\n>>Edad: {}\n>>Carnet: {}\n>>Cedula: {}".format(self.database[id]["Nombre"],
self.database[id]["Edad"],
id, self.database[id]["Cedula"]))
print(">>Materias:")
print(*self.database[id]["Materias"], sep=" / ")
print("---------------------")
def looping_options(self):
valid = False
while not valid:
option_continue = input("Desea hacer algo mas? (Si o No): ").lower()
if option_continue == "no":
print("Entendido, que tenga un feliz dia!")
return_valid = True
valid = True
elif option_continue == "si":
return_valid = False
valid = True
continue
else:
print("La opcion ingresada no es valida, se retornara al menu!")
return return_valid
def execute(self):
'''
Ejecuta las funciones add_student(), delete_student(), update_database() y
print_database() segun las necesidades del usuario.
'''
print("Bienvenido a la base de datos de Sirius")
valid_option = False
while valid_option is False:
print("Estas son sus opciones:\n1. Agregar un usuario\n2. Eliminar un usuario\n3. Actualizar datos\n4. Ver la Base de datos\n5. Salir")
option = self.get_options()
if option == 1:
self.add_student()
elif option == 2:
self.delete_student()
elif option == 3:
self.update_database()
elif option == 4:
self.print_database()
else:
print("Entendido, se cerrara el programa")
exit()
valid_option = self.looping_options()
Sirius().execute() |
dbec152b0e60aa09ce68aa161d19fae6b4bc1645 | CarolineXiao/AlgorithmPractice | /TopKLargestNumbers.py | 475 | 3.734375 | 4 | import heapq
class Solution:
"""
@param nums: an integer array
@param k: An integer
@return: the top k largest numbers in array
"""
def topk(self, nums, k):
if len(nums) <= k:
return sorted(nums, reverse=True)
heap = []
for i in range(len(nums)):
heapq.heappush(heap, nums[i])
if len(heap) > k:
heapq.heappop(heap)
return sorted(heap, reverse=True)
|
c046a966135ec74290538a7ec5a1d9dda9f85f3d | soufal/python_hand_way | /hand_way/ex4.py | 795 | 4.0625 | 4 | #the num of cars
cars = 100
#the space of a car
space_in_a_car = 4.0
#the num of drivers
drivers = 30
#the num of passengers
passengers = 90
#the num of cars are not driven
cars_not_driven = cars - drivers
#the num of cars are driven
cars_driven = drivers
#the carpool capacity
carpool_capacity = cars_driven * space_in_a_car
#average of passengers for per car
average_passengers_per_car = passengers / cars_driven
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
print("There will be", cars_not_driven, "empty cars today.")
print("We can transport", carpool_capacity, "people today.")
print("We have", passengers, "to carpool today.")
print("We need to put about", average_passengers_per_car,"in each car.") |
de9217cb8194ea4a4391fd55879158664e2666d1 | Pluto-Zmy/Python-OJ | /3/D.电商二.py | 353 | 3.78125 | 4 | def get_upper(string):
return ''.join([ch for ch in string if ch.isupper()])
bookNum = int(input())
bookList = [input() for i in range(bookNum)]
bookListPlus = []
for currentName in bookList:
bookListPlus.append([get_upper(currentName), currentName])
sortedListPlus = sorted(bookListPlus, key=(lambda x: x[0]))
for i in sortedListPlus:
print(i[1])
|
c524538d67a999d67afc95e1db3e6089e68d4868 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_85/71.py | 3,110 | 3.71875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
SpaceEmergency.py
Created by Graham Dennis on 2011-05-22.
Copyright (c) 2011 __MyCompanyName__. All rights reserved.
"""
import sys
# def permutations(*iterables):
# def permuteTwo(it1, it2):
# for o1 in it1:
# for o2 in it2:
# if isinstance(o1, tuple):
# yield o1 + (o2,)
# else:
# yield (o1, o2)
#
# if len(iterables) == 1:
# return iterables[0]
#
# it = iterables[0]
# for it2 in iterables[1:]:
# it = permuteTwo(it, it2)
#
# return it
#
# def combinations(itemCount, *lsts):
# """Generator for all unique combinations of each list in `lsts` containing `itemCount` elements."""
# def _combinations(itemCount, lst):
# if itemCount == 0 or itemCount > len(lst):
# return
# if itemCount == 1:
# for o in lst:
# yield (o,)
# elif itemCount == len(lst):
# yield tuple(lst)
# else:
# if not isinstance(lst, list):
# lst = list(lst)
# for o in _combinations(itemCount-1, lst[1:]):
# yield (lst[0],) + o
# for o in _combinations(itemCount, lst[1:]):
# yield o
# if len(lsts) == 1:
# return _combinations(itemCount, lsts[0])
# iterables = [list(_combinations(itemCount, lst)) for lst in lsts]
# return permutations(*iterables)
def combinations(N, items):
if N == 0:
pass
elif N == 1:
for i in items:
yield (i,)
elif N == 2:
for i in xrange(len(items)):
for j in xrange(i):
yield (items[j], items[i])
def main():
f = open(sys.argv[1])
T = int(f.readline())
for case in xrange(T):
integers = map(int, f.readline().split())
L, t, N, C = integers[:4]
distancePattern = integers[4:]
distances = distancePattern * ((N/C) + 1)
times = [2 * sum(distances[:N])]
validBoosterLocations = []
currentTime = 0
for i in xrange(N):
currentTime += 2 * distances[i]
if currentTime > t:
validBoosterLocations.append(i)
if len(validBoosterLocations) < L:
L = len(validBoosterLocations)
# print validBoosterLocations
for boosterPattern in combinations(L, validBoosterLocations):
currentTime = 0
for i in xrange(N):
if not i in boosterPattern:
currentTime += 2 * distances[i]
elif currentTime >= t:
currentTime += distances[i]
elif currentTime + 2 * distances[i] <= t:
currentTime += 2 * distances[i]
else:
remainingDistance = distances[i] - (t - currentTime)/2
currentTime = t + remainingDistance
times.append(currentTime)
print "Case #%i: %i" % (case + 1, min(times))
if __name__ == "__main__":
sys.exit(main())
|
1a29d171b6b98d6868948ccb08189b91b1553cff | DimpleOrg/PythonRepository | /GeeksforGeeks/vAnil/03. List Programs/30.py | 796 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 20 17:06:49 2021
@author: ANIL
"""
'''
Given two lists, sort the values of one list using the second list.
Examples:
Input : list1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
list2 = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
Output :['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
'''
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
x = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
print(sort_list(x, y))
x = ["g", "e", "e", "k", "s", "f", "o", "r", "g", "e", "e", "k", "s"]
y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
print(sort_list(x, y)) |
0f9ee5d7bb600b486cde447ed22c7a3fbd65ee64 | rafaelsaidbc/Exercicios_python | /ex027.py | 306 | 4.03125 | 4 | nome = str(input('Digite seu nome completo: ')).strip() # strip para ignorar possíveis espaços no início da digitação
nome_split = nome.split()
primeiro_nome = nome_split[0]
ultimo_nome = nome_split[-1]
print('O primeiro nome de {} é {} e o último é {}!'.format(nome, primeiro_nome, ultimo_nome))
|
e697bd3df3fed704af8336e1cb0c44ef056430ff | carlonuccio/data-modeling-postgres | /create_tables.py | 2,891 | 3.875 | 4 | import psycopg2
from sql_queries import list_drop_tables, list_create_tables
def insert_from_dataframe(hostname, dbname, table, dataframe):
"""
Insert Rows in a db table from a dataframe
:param hostname: Host Database Address
:param dbname: Database Name
:param table: Table Name
:param dataframe: Pandas Dataframe
"""
conn, cur = db_connection(hostname, dbname)
for index, row in dataframe.iterrows():
try:
cur.execute('''INSERT INTO ''' + table + '''
VALUES (''' + ','.join(['%s' for x in row]) + ''');''',
row)
except psycopg2.Error as e:
print("Error insert cursor")
print(e)
cur.close()
conn.close()
def create_database(hostname, dbname):
"""
- Drop and creates the database
:param hostname: Host Database Address
:param dbname: Database Name
:return: connection conn and a cursor cur
"""
# connect to default database
conn = psycopg2.connect("host=" + hostname + " dbname=studentdb user=student password=student")
conn.set_session(autocommit=True)
cur = conn.cursor()
# create sparkify database with UTF8 encoding
cur.execute("DROP DATABASE IF EXISTS " + dbname)
cur.execute("CREATE DATABASE " + dbname + " WITH ENCODING 'utf8' TEMPLATE template0")
# close connection to default database
cur.close()
conn.close()
def db_connection(hostname, dbname):
"""
- Connects to a database
- Returns the connection and cursor to database
:param hostname: Host Database Address
:param dbname: Database Name
:return: connection conn and a cursor cur
"""
try:
conn = psycopg2.connect("host="+ hostname + " dbname=" + dbname + " user=student password=student")
conn.set_session(autocommit=True)
except psycopg2.Error as e:
print("Error connection to database")
print(e)
try:
cur = conn.cursor()
except psycopg2.Error as e:
print("Error init cursor")
print(e)
return conn, cur
def main(hostname, dbname):
"""
- Drops (if exists) and Creates the sparkify database.
- Establishes connection with the sparkify database and gets
cursor to it.
- Drops all the tables.
- Creates all tables needed.
- Finally, closes the connection.
:param hostname: Host Database Address
:param dbname: Database Name
"""
create_database(hostname, dbname)
conn, cur = db_connection(hostname, dbname)
# Drops each table using the queries in `list_drop_tables` list.
for query in list_drop_tables:
cur.execute(query)
# Creates each table using the queries in `list_create_tables` list.
for query in list_create_tables:
cur.execute(query)
cur.close()
conn.close()
if __name__ == "__main__":
main("127.0.0.1", "sparkifydb") |
3047addb624844e0c572dabcae31219eee124747 | vonzhou/Core-Python-Programming | /chapter8/Continue.py | 358 | 3.984375 | 4 | #P200
def checkPwd():
valid = False
count = 3
passwordList = ('123456', 'vonzhou')
while count > 0:
input = raw_input('Enter password:')
for each in passwordList:
if input == each:
valid = True
break
if not valid:
print 'invalid input password'
count -= 1
continue
else:
print 'Good input'
break
checkPwd()
|
f2b5bc39e4067be7d6563989ffdf0a3e39e26ec3 | majf2015/python_practice | /test_proj/class2.py | 505 | 3.6875 | 4 | class Baseclass(object):
def __init__(self,k):
self.__k = k
self.__v = 1
def printself(self):
print self.__k, self.__v
def getVelue(self):
return self.__k, self.__v
class Deriveclass(Baseclass):
def __init__(self):
Baseclass.__init__(self, "first")
a, b = self.getVelue()
self.__L = str(a) + str(b)
def printL(self):
print self.__L
A = Deriveclass()
A.printself()
A.printL()
import os
lis = os.listdir('..')
print lis |
eef60905a5d8de48577dabfd070155dac21cd6e6 | harshaveeturi/DataStructures_Algorithms_Python | /stacks/linkedlist_stack.py | 2,085 | 4.21875 | 4 | class Node:
def __init__(self,element):
self.element=element
self.next=None
class Stack:
def __init__(self):
self.top=None
def push(self,push_element):
'''this function pushes the elements in to the stack'''
if self.top is None:
self.top=Node(push_element)
else:
new_node=Node(push_element)
new_node.next=self.top
self.top=new_node
def pop(self):
'''this function gets the top element from the stack'''
pop_element=None
if self.top is not None:
pop_element=self.top.element
self.top=self.top.next
return f"popping out {pop_element}"
else:
raise Exception("Stack is empty..")
return
def print_elements(self):
'''this function print the elements in the stack'''
itr=self.top
while itr:
print(itr.element)
itr=itr.next
def count_elements(self):
'''this function return the number of elements present in the stack'''
count=0
itr=self.top
while itr:
count+=1
itr=itr.next
return f"the number of elements in the stack are {count}"
def search_element(self,search_key):
'''this function checks whether the search key present in the stack or not'''
itr=self.top
while itr:
if itr.element==search_key:
return f"{search_key} search key found in the stack"
itr=itr.next
if itr is None:
return f"{search_key} search key not found in the stack"
if __name__ == "__main__":
stack=Stack()
stack.push(4)
stack.push(3)
stack.push(2)
stack.push(1)
print(stack.count_elements())
print(stack.pop())
print(stack.pop())
print(stack.pop())
print("elements in the stack are :")
stack.print_elements()
print(stack.count_elements())
print(stack.search_element(4))
print(stack.search_element(5))
print(stack.search_element(58)) |
126ab46ee83a568e00dd296229728c5784c53b07 | MatejBabis/AdventOfCode2k18 | /day5/part2.py | 525 | 3.765625 | 4 | import part1
if __name__ == "__main__":
s = part1.read_input("input.txt")
results = {}
# store the length of reaction string when 'c' is removed
for c in "abcdefghijklmnopqrstuvwxyz":
results[c] = len(part1.polymer_reaction(s, c))
# find the minimum value in the dictionary
minimum_val = min(results.items())
# what letter does it correspond to
result = [key for key, val in results.items() if val == minimum_val][0]
print("Answer: {0} ('{1}')".format(results[result], result))
|
547b5ea2ac7500bad4af65ab23b3a0cbc4518221 | zl0bster/LearnPythonProject | /Exersises 20201119 rnd gen.py | 2,327 | 4.03125 | 4 | def lam3():
def makeAdd(n):
def addX(x):
return x + n
return addX
def lam31():
makeAdd = lambda n: lambda x: x + n
add_5 = makeAdd(5)
print(add_5(5))
def lam1():
"""
Создать список, в котором каждый элемент – кортеж из двух чисел.
Отсортировать данный список по убыванию вторых элементов кортежей.
"""
from operator import itemgetter
n = 5
a = [(n - i, i) for i in range(n)]
print(a)
# print(sorted(a, key=lambda tup: tup[1], reverse=True))
print(sorted(a, key=itemgetter(1), reverse=True))
def lam2():
"""
Отсортируйте список слов по убыванию длины слова.
"""
words = "один два шесть восемь"
list_words = words.split()
print(list_words)
print(sorted(list_words,
key=lambda w: len(w),
reverse=True))
# if __name__ == "__main__":
# words = "один два шесть восемь"
# for word in gen1(words):
# print(word)
def gen1(words):
listW = words.split()
for word in listW:
yield word
# def gen2(start, step):
# # for i in range(start, step):
# i = start
# while True:
# arg = yield i
# if arg != None:
# i = int(arg[0])
# step = int(arg[1])
# i += step
#
#
# if __name__ == "__main__":
# step = 10
# a = gen2(10, step)
# while True:
# l = a.send(None)
# print(l)
# if l > 100:
# break
# step += 5
# print("--" * 6)
# print(a.send((10, step)))
# print("--" * 6)
# while True:
# l = a.send(None)
# print(l)
# if l > 200:
# break
def my_random(x0: int = 1, a: int = 23, m: int = 3, c: int = 4):
"""
Xn1 = (a * Xn + c) % m
:param x0:
:param a:
:param m:
:param c:
:return:
"""
while True:
xn1 = (a * x0 + c) % m
yield xn1
x0 = xn1
if __name__ == "__main__":
rnd = my_random()
for _ in range(20):
l=rnd()
print(l) |
7525b2e648797a3e62024e6606936c31a89a7c96 | rajaupadhyay/Risk_Engine_BAML_Hackathon | /data_formulation.py | 5,363 | 3.5 | 4 | import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
import math
from scipy.stats import norm
import random
import pandas as pd
'''
def plot_bell(mean, variance):
sigma = math.sqrt(variance)
x = np.linspace(mean-3*sigma, mean+3*sigma,100)
plt.plot(x,mlab.normpdf(x, mean, sigma))
plt.show()
# data = np.random.normal(loc=5.0, scale=2.0, size=1000)
# mean,std=norm.fit(data)
x = [random.randint(1,100) for _ in range(20)]
# print(np.var(x))
'''
def stock_calculator(sp_index, dataframe):
# print("Reading sp_index file into pandas Dataframe")
# df_spindex = pd.read_csv(sp_index)
# print("Reading stockprice file into dataframe")
# df = pd.read_csv(csvfile)
df_spindex = sp_index
df = dataframe
df.insert(6, "closeNew", df_spindex["close"])
df = df[["close", "closeNew"]]
df.columns = ["close_stocks", "close_benchmark"]
print("Raveling columns")
close_stocks_values = df.close_stocks.values
close_benchmark_values = df.close_benchmark.values
close_stocks_values = close_stocks_values[::-1]
close_benchmark_values = close_benchmark_values[::-1]
# print(" Max Benchmark Values", max(close_benchmark_values))
# print(" Min Benchmark Values", min(close_benchmark_values))
# print(close_stocks_values[:100])
# print("Calculating mean and variance of stock prices")
# # Variance and mean calculations
# # stock_var = np.var(close_stocks_values)
# stock_mean = sum(list(close_stocks_values)) / len(close_stocks_values)
# stock_var = sum([(i-stock_mean)**2 for i in close_stocks_values])/(len(close_stocks_values)-1)
#
# print("Calculating mean and variance of benchmark index")
# # benchmark_var = np.var(close_benchmark_values)
# benchmark_mean = sum(list(close_benchmark_values)) / len(close_benchmark_values)
# benchmark_var = sum([(i-benchmark_mean)**2 for i in close_benchmark_values])/(len(close_benchmark_values)-1)
close_stocks_change = []
close_benchmark_change = []
print("Calculating % change in stock prices")
for i in range(1, len(close_stocks_values)):
close_stocks_change.append(
(close_stocks_values[i] - close_stocks_values[i - 1]) / close_stocks_values[i - 1])
print("Calculating % change in benchmark values")
for i in range(1, len(close_benchmark_values)):
close_benchmark_change.append(
(close_benchmark_values[i] - close_benchmark_values[i - 1]) / close_benchmark_values[i - 1])
close_stocks_change = np.array(close_stocks_change)
close_benchmark_change = np.array(close_benchmark_change)
print("Calculating mean and variance of close stock prices")
# Variance and mean calculations
stock_var = np.var(close_stocks_change)
stock_mean = sum(list(close_stocks_change)) / len(close_stocks_change)
# stock_var = sum([(i - stock_mean) ** 2 for i in close_stocks_values]) / (len(close_stocks_values) - 1)
print("Calculating mean and variance of close benchmark index")
benchmark_var = np.var(close_benchmark_change)
benchmark_mean = sum(list(close_benchmark_change)) / len(close_benchmark_change)
# benchmark_var = sum([(i - benchmark_mean) ** 2 for i in close_benchmark_values]) / (len(close_benchmark_values) - 1)
df_change = pd.DataFrame(close_stocks_change)
# print(df_change.head())
df_change.insert(1, "change_benchmark", close_benchmark_change)
df_change.columns = ["%change_stocks", "%change_benchmark"]
# print("Writing % changes to CSV")
# df_change.to_csv(csvfile.split(".")[0]+ "_percent_change" + ".csv", index=False)
# print("Calculation on {} complete".format(csvfile))
return df_change, stock_var, stock_mean, benchmark_var, benchmark_mean
# res = stock_calculator("daily_SPY-1.csv", ["daily_GOOG.csv", "daily_MSFT-1.csv"])
# print(res)
'''
dfMSFT = pd.read_csv("daily_MSFT-1.csv")
# dfMSFT = dfMSFT["close"]
dfSPY = pd.read_csv("daily_SPY-1.csv")
dfMSFT.insert(6,"closeNew",dfSPY["close"])
# dfMSFT['close'] = dfSPY['close']
# print(dfMSFT.head())
dfMSFT = dfMSFT[["close", "closeNew"]]
dfMSFT.columns = ["close_stocks", "close_benchmark"]
print(dfMSFT.head())
close_stocks_values = dfMSFT.close_stocks.values
close_benchmark_values = dfMSFT.close_benchmark.values
# variance and mean calculations
stock_var = np.var(close_stocks_values)
stock_mean = sum(list(close_stocks_values))/len(close_stocks_values)
benchmark_var = np.var(close_benchmark_values)
benchmark_mean = sum(list(close_benchmark_values))/len(close_benchmark_values)
close_stocks_change = []
close_benchmark_change = []
for i in range(1, len(close_stocks_values)):
close_stocks_change.append((close_stocks_values[i]-close_stocks_values[i-1])/close_stocks_values[i-1])
for i in range(1, len(close_benchmark_values)):
close_benchmark_change.append((close_benchmark_values[i]-close_benchmark_values[i-1])/close_benchmark_values[i-1])
close_stocks_change = np.array(close_stocks_change)
close_benchmark_change = np.array(close_benchmark_change)
df_change = pd.DataFrame(close_stocks_change)
print(df_change.head())
df_change.insert(1,"change_benchmark",close_benchmark_change)
df_change.columns = ["%change_stocks", "%change_benchmark"]
print(df_change.head())
df_change.to_csv("df_change.csv", index=False)
''' |
d7d1218a8560abe221fdead0ded0850d603f1e5d | accolombini/A_IC | /FINANCAS/LABORATORIOS/lab101_tax_ret_simples_br.py | 1,953 | 3.671875 | 4 | """
Neste laboratório vamos trabalhar com a taxa de retorno simples de um ativo.
REQUISITOS: - para este laboratório precisaremos de alguns módulos Python
- será preciso -> numpy
- será preciso -> pandas
- será preciso -> matplotlib
- onde buscar pelos módulos: https://pypi.org/
- usaremos para análise o site: https://finance.yahoo.com/
- PANDAS-DATAREADER:
https://readthedocs.org/projects/pandas-datareader/downloads/pdf
/latest/
"""
# Realizando os imports de: numpy, pandas_datareader, matplolib.pyplot
import numpy as np
from pandas_datareader import data as wb
import matplotlib.pyplot as plt
# Nosso papel é avaliar a VALE3
# O que queremos -> baixar 25 anos de movimentação financeira da VALE3
VALE3 = wb.DataReader('VALE3.SA', data_source='yahoo',
start='2000-01-01')
# Visualizar se tivemos ou não sucesso, cuidado o ticket é importante
print(f'{VALE3.head(2)}')
print(f'{VALE3.tail(2)}')
# Retorno simples = papel_dia/papel_dia_anterior - 1
VALE3['simple_return'] = (VALE3['Adj Close'] / VALE3['Adj Close'].shift(1)) - 1
print(f'{VALE3["simple_return"].head(20)}')
print(f'{VALE3["simple_return"].tail(20)}')
# Vamos fazer uma análise gráfica desse período => retorno diário
VALE3['simple_return'].plot(figsize=(8, 5)) # Exibe a variação do rendimento diário do papel
plt.show()
# Faremos o cálculo da média diária
avg_return_d = VALE3['simple_return'].mean()
# print(avg_return_d)
print(f'A média diária calculada é -> {avg_return_d}')
# Faremos o cálculo da média anual -> 365 - 360 -> pregão -> 250, 251, 252
avg_return_a = VALE3['simple_return'].mean() * 250
print(f'A média anual calculada é -> {avg_return_a}')
print(f'A média anual em porcentagem -> {str(round(avg_return_a, 5) * 100) + "%"}')
|
db71c57fba658fd19f3b8a85fef155f61188340b | luckycoolrana03/AI-chatbot-using-python-main | /sorce code.py | 2,246 | 3.90625 | 4 | import pyttsx3
import speech_recognition as sr
import wikipedia
import datetime
import os
import webbrowser
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
print("Skynet: ", audio)
def wishMe():
hour = int(datetime.datetime.now().hour)
if True:
speak("Welcome Back sir!")
speak("How may I help you sir!")
def takecommand():
r = sr.Recognizer() #Speech recognition means that when humans are speaking, a machine understands it. Here we are using Google Speech API
# in Python to make it happen. We need to install the following packages for this − Pyaudio
with sr.Microphone()as source:
print("Listening...")
r.pause_threshold = 1
r.adjust_for_ambient_noise(source) #adjust_for_ambient_noise(source, duration = 1) Adjusts the energy threshold dynamically using audio from source
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio, language='en-in')
print(f"You: {query}\n")
except Exception as e:
print(e)
print("Sorry I didnt get that , Please say that again")
speak("Sorry I didnt get that , Please say that again")
return "None"
return query
if __name__ == "__main__":
wishMe()
while True:
query = takecommand().lower() #lower means here to take query in lower-case alphabets
if 'wikipedia' in query:
speak("Searching wikipedia")
query = query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences=2)
speak("According to wikipedia")
print(results)
speak(results)
elif 'open youtube' in query:
webbrowser.open("https:\\www.youtube.com")
elif 'open google' in query:
webbrowser.open("https:\\www.google.com")
elif 'play music' in query:
music_dir ='C:\\Users\LuckyRana\Music'
songs = os.listdir(music_dir)
print(songs)
os.startfile(os.path.join(music_dir, songs[0]))
|
3f3c22d7ce34e48b06135a223c757ec2756219bd | andrewnvu/DCP | /DCP4.py | 339 | 4 | 4 | #Find the first missing positive in a an array of integers
def first_missing_positive(numbers):
#gets rid of negative numbers
s = set(numbers)
i = 1
#if 1 is in the set, increment it until i is not in s
while i in s:
i += 1
return i
myArray = [1,2,4,-2, -5]
print(first_missing_positive(myArray))
|
de32cd87d0f8e6699c03f41f91d70a8519262bda | anneusagi/nganguyen-lab-sc4e18 | /Session03/f-math-problem/freak.py | 793 | 3.703125 | 4 | # from random import *
# x = randint(0,10)
# y = randint(0,10)
# cal = choice("+,-,*,/")
# if cal == "+":
# result = x + y
# elif cal == "-":
# result = x - y
# elif cal == "*":
# result = x * y
# else:
# result = x / y
# error = randint(-1,0,1)
# print("{0} {1} {2} = {3}".format(x, cal, y, result+error))
from random import radint, choice
# from eval import calc
import eval
x = randint(1, 10)
y = randint(1, 10)
ops = ["+", "-", "*", "/"]
op = choice(ops)
res = calc (x, y, op)
# res = -9999
# if cal == "+":
# result = x + y
# elif cal == "-":
# result = x - y
# elif cal == "*":
# result = x * y
# else:
# result = x / y
err = choice([-1, 0, 1])
display_res = res + err
print("*" * 20)
print("{0} {1} {2} = {3}".format(x, op, y, display_res))
|
fd63f7dd9f80ad70f7f4aa0c1ff4a7e078f36724 | xiyiwang/leetcode-challenge-solutions | /2021-05/2021-05-20-levelOrder.py | 1,271 | 3.8125 | 4 | """
LeetCode Challenge: Binary Tree Level Order Traversal (2021-05-20)
Given the root of a binary tree, return the level order traversal
of its nodes' values. (i.e., from left to right, level by level).
Constraints:
- The number of nodes in the tree is in the range [0, 2000].
- -1000 <= Node.val <= 1000
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# bfs - runtime: 32 ms (beats 80.06%)
def levelOrder(self, root: TreeNode) -> list:
if not root: return []
ans = []
queue, values = [root], []
while queue:
curr_lvl = queue[:]
queue.clear()
while curr_lvl:
node = curr_lvl.pop(0)
values.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
ans.append(values[:])
values.clear()
return ans
root1 = TreeNode(val=3, left=TreeNode(val=9), right=TreeNode(val=20, left=TreeNode(val=15), right=TreeNode(val=7)))
# [3,9,20,None,None,15,7] -> output: [[3],[9,20],[15,7]]
root2 = TreeNode(val=1)
# output: [[1]]
root3 = None # output: []
|
0ba666b3be4ce7a2fe00d802909e27eb92622f3f | mosfeqanik/Python_Exercises | /turtlewhileloop.py | 196 | 3.734375 | 4 | import turtle
turtle.color("red")
turtle.speed(5)
counter =0
while counter<36:
for i in range (4):
turtle.forward(100)
turtle.right(90)
turtle.right(10)
counter +=1
turtle.exitonclick()
|
5bf011dbadac2252cf6c6e6d5a45a39ea32be686 | semmani/Lecture2A | /OLACabLayout.py | 4,417 | 3.875 | 4 | #to be completed from the github
# Ram is volatile memory i.e temporary
# whenver process is finsished, program will beb finished
#Saving data somewhere--->Persistence
# we perform serialization and De-Serialization
class Customer:
def __init__(self,name,phone,email):
self.name = name
self.phone = phone
self.email = email
def showCustomerDetails(self):
print("Name: {},Phone: {},Email: {}".format(self.name,self.phone,self.email))
class Driver(Customer): # inheritance---> inheriting Customer class
def __init__(self,name,phone,email,licenseNumber):
Customer.__init__(self,name,phone,email) # referring to Customer class data within Base cass Driver
self.licenseNumber = licenseNumber # driver class own member
def showDriverDetails(self):
print("DRIVER DETAILS:")
self.showCustomerDetails() # shows customer details within driver details
print("License Number:",self.licenseNumber)
class Cab: # cab class prints details of the cab and further different cabs selected define their own cabs
def __init__(self,regNumber,basePrice):
self.regNumber = regNumber
self.basePrice = basePrice
def showCabDetails(self):
print("CAB DETAILS:")
print("Reg Number:{}, Base Price:{}".format(self.regNumber,self.basePrice))
class OlaMini(Cab):
def showCabDetails(self):
print("OLA MINI ON THE WAY!")
print("Reg Number:{}, Base Price:{}".format(self.regNumber, self.basePrice))
class OlaMicro(Cab):
def showCabDetails(self):
print("OLA MICRO ON THE WAY!")
print("Reg Number:{}, Base Price:{}".format(self.regNumber, self.basePrice))
class OlaSedan(Cab):
def showCabDetails(self):
print("OLA SEDAN ON THE WAY")
print("Reg Number:{}, Base Price:{}".format(self.regNumber, self.basePrice))
class Ride: # this class intakes various fields to provide a ride(rideno,name,source-destination,driver etc)
rideNumber = 1
def __init__(self,customer):
self.ride = Ride.rideNumber
self.customer = customer
Ride.rideNumber += 1 #increments ride number evrytime the ride is taken
def sourceAnddestination(self):
self.source = input("ENTER THE SOURCE FOR PICK UP: ")
self.destination = input("ENTER THE DESTINATION TO GO: ")
print("RIDE SELECTED SUCCESSFULLY, {} TO {}".format(self.source,self.destination))
def selectCab(self):
self.cab = None
print("WHICH CAB DO YOU WANT TO SELECT FOR THE RIDE")
print("OLA MINI | OLA MICRO | OLA SEDAN ")
choice = input("ENTER WHICH RIDE YOU WANT TO BOOK? ")
# Runtime polymorphism, during runtime the call is resolved i.e during runtime the cab refers to either of olamini,micro or sedan
if choice == "MINI":
self.cab = OlaMini("PB10AD0041",100)
elif choice == "MICRO":
self.cab = OlaMicro("PB10AD1125",150)
else:
self.cab = OlaSedan("PB10HH0042",100)
def attachDriver(self,driver):
self.driver = driver
def showRideDetails(self): # this will print all the ride details showing from source to destination,cab/driver/cust details
print("RIDE BOOKED ( FROM {} TO {} )".format(self.source,self.destination))
print("YOUR RIDE NUMBER: ",self.ride)
self.cab.showCabDetails()
self.driver.showDriverDetails()
self.customer.showCustomerDetails()
# REFERENCE TO THE CUSTOMER CLASS AND DRIVER CLASS
customer = Customer("David Essen","+91 258369 222","davide@gmail.com")
driver = Driver("Jeevan Singh","+91 852741","jeevan@gmail.com","X1254B9")
anothrcustomer = Customer("Mike Dawson","+956325896","mike@hotmail.com")
anothrdriver = Driver("Jenna Hayer","+91 25825822","jennahayer@gmail.com","YH1234")
# REFERENCE TO RIDE NOW IN ORDER TO BOOK IT AND GO AROUND
ride = Ride(customer)
ride.sourceAnddestination()
ride.selectCab()
ride.attachDriver(driver)
ride.showRideDetails()
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
reply = input("------- WANT TO BOOK ANOTHER RIDE----------\n TYPE YES, FOR BOOKING ELSE NO----------\n")
while reply == 'YES': # IMPROVEMENTS NEEDED HERE!!
ride = Ride(anothrcustomer)
ride.sourceAnddestination()
ride.selectCab()
ride.attachDriver(anothrdriver)
ride.showRideDetails()
print("********************************THANKYOU FOR BOOKING***************************************")
|
3410910eee41f273757a2d6375bf93a11ec90721 | Kvazar78/Skillbox | /15_list1/task_152_2.py | 1,077 | 3.90625 | 4 | # Кратность
#
# Пользователь вводит список из N чисел и число K. Напишите код, выводящий на экран сумму индексов элементов списка,
# которые кратны K.
#
# Пример:
#
# Кол-во чисел в списке: 4
#
# Введите 1 число: 1
# Введите 2 число: 20
# Введите 3 число: 30
# Введите 4 число: 4
#
# Введите делитель: 10
#
# Индекс числа 20: 1
# Индекс числа 30: 2
#
# Сумма индексов: 3
nums_list = []
N = int(input('Кол-во чисел в списке: '))
for i in range(N):
num = int(input(f'Введите {i + 1} число: '))
nums_list.append(num)
deliver = int(input('Введите делитель: '))
summ = 0
for i in nums_list:
if i % 10 == 0:
number_index = nums_list.index(i)
print(f'Индекс числа {i}: {number_index}')
summ += number_index
print(f'Сумма индексов: {summ}') |
59c97dea54dfb56aa435ce9cc3d8e953e98beca4 | pranter21/Santotomas_estructuras_programacion | /guia5_python/G5_ejercicio3.py | 1,842 | 3.75 | 4 | #!/usr/bin/env python
# coding=utf-8
from colored import bg, fg, attr
"""
@author: Adrian Verdugo
@contact: adrianverdugo273@gmail.com
@github: adrian273
"""
# array para los datos de los trabajadores
data_workers = []
total = 0
"""
@type = variables para dar estilos
"""
colors = [bg('blue') + fg(15), bg('red') + fg(15), bg('purple_3') + fg(15)]
reset = attr('reset')
bold = attr('bold')
print bold + colors[0] + "Ejercicio numero 3" + reset
for i in range(1):
#_____________ datos de trabajadores _______________________
print "¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨"
name = str(raw_input('>> ingresa nombre \n'))
hours_work = int(raw_input('>> ingresa horas de trabajo \n'))
value_hours = int(raw_input('>> ingresa valor hora \n'))
number_cargo = int(raw_input('>> Ingrese numero carga \n'))
#_____________ salario normal del trabajador _______________
salary = hours_work * value_hours
if number_cargo >= 3:
salary = salary * 1.1
elif number_cargo == 1 or number_cargo == 2:
salary = salary * 1.05
"""
* agregando los valores al
* @diccionario de datos
"""
data_workers.append(
{
'name': name,
'hours_work': hours_work,
'value_hours': value_hours,
'number_cargo': number_cargo,
'salary': salary
}
)
print colors[2] + bold + "Datos a pagar al trabajador \n" +reset
"""
@data_workers = [{}]
"""
for data in data_workers:
print colors[0] + "* Nombre "+ data['name'].title() + ", sueldo a pagar $" + str(int(data['salary'])) + reset
total = int(data['salary']) + total
print "--------------------------------------------------------------\n"
print colors[1] + "Total a pagar: $" + str(total) + reset
|
7a6ed35ca27160a9b5ae03a815df1571239cfec8 | ramaranjanruj/Machine-Learning | /ML - Regression - 1.py | 3,631 | 3.90625 | 4 | # Getting all libraries that have dependencies
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.cross_validation import train_test_split
# importing the data from csv files
train_data = pd.read_csv('kc_house_train_data.csv')
test_data = pd.read_csv('kc_house_test_data.csv')
train_data.head()
# Taking the price column from the pandas data frame
price = train_data.ix[:,2:3]
# Doing some basic calculations on the data array.
sum_of_prices = price.sum()
size = price.size
avg = sum_of_prices/size
print "The mean of price using method one is ", str(avg)
print train_data['price'].values.size
print train_data['sqft_living'].values.size
# Defining a function for a simple linear regression using the scikit-learn library
def simple_linear_regression(input_feature, output):
# use the formula for the slope
regr = linear_model.LinearRegression()
model = regr.fit(input_feature, output)
return model.intercept_, model.coef_
# Checking the output of the defined fiunction
input_feature = train_data['sqft_living']
output = train_data['price']
sqft_intercept, sqft_slope = simple_linear_regression(input_feature.reshape(-1,1), output)
print sqft_intercept, sqft_slope
# Estimating the price of the house for a given sq.ft area.
my_house_sqft = 2650
estimated_price = get_regression_predictions(my_house_sqft, sqft_intercept, sqft_slope)
print "The estimated price for a house with %d squarefeet is $%.2f" % (my_house_sqft, estimated_price)
# Defining a function to get the resuduals.
def get_residual_sum_of_squares(input_feature, output, intercept, slope):
# First get the predictions
predictions = get_regression_predictions(input_feature, intercept, slope)
# then compute the residuals (since we are squaring it doesn't matter which order you subtract)
residuals = predictions - output
# square the residuals and add them up
RSS = sum(residuals**2)
return RSS
# Checking the residuals for a set of points.
rss_prices_on_sqft = get_residual_sum_of_squares(train_data['sqft_living'], train_data['price'], sqft_intercept, sqft_slope)
print 'The RSS of predicting Prices based on Square Feet is : ' + str(rss_prices_on_sqft)
# Defining a function for getting the inverse of the residuals.
def inverse_regression_predictions(output, intercept, slope):
estimated_feature = (output - intercept)/slope
return estimated_feature
# Checking the inverse resudial function
my_house_price = 800000
estimated_squarefeet = inverse_regression_predictions(my_house_price, sqft_intercept, sqft_slope)
print "The estimated squarefeet for a house worth $%.2f is %d" % (my_house_price, estimated_squarefeet)
# Checking the RSS based on the number of bedrooms on the TEST dataset.
input_feature = train_data['bedrooms']
output = train_data['price']
sqft_intercept, sqft_slope = simple_linear_regression(input_feature.reshape(-1,1), output)
rss_prices_on_bedrooms = get_residual_sum_of_squares(test_data['bedrooms'], test_data['price'], sqft_intercept, sqft_slope)
print 'The RSS of predicting Prices based on bedrooms is : ' + str(rss_prices_on_bedrooms)
# Checking the RSS based onn the sq.ft area of the TEST dataset.
input_feature = train_data['sqft_living']
output = train_data['price']
sqft_intercept, sqft_slope = simple_linear_regression(input_feature.reshape(-1,1), output)
rss_prices_on_test_sqft = get_residual_sum_of_squares(test_data['sqft_living'], test_data['price'], sqft_intercept, sqft_slope)
print 'The RSS of predicting Prices based on sqft is : ' + str(rss_prices_on_test_sqft) |
ae97bd763e6ad580f63f63b8b6d659044dde9814 | ThomasHJorgensen/ConsumptionSaving | /consav/misc.py | 9,140 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""newton_raphson
This module provides misc functions.
"""
import time
import math
import numpy as np
from scipy.stats import norm
from numpy.linalg import svd
from numba import njit
def elapsed(t0,t1=None):
""" time elapsed since t0 with in nice format
Args:
t0 (double): start time
t1 (double,optional): end time (else now)
Return:
(str): elapsed time in nice format
"""
if t1 is None:
secs = time.time()-t0
else:
secs = t1-t0
days = secs//(60*60*24)
secs -= 60*60*24*days
hours = secs//(60*60)
secs -= 60*60*hours
mins = secs//(60)
secs -= 60*mins
text = ''
if days > 0: text += f'{days} days '
if hours > 0: text += f'{hours} hours '
if mins > 0: text += f'{mins} mins '
if days > 0 or hours > 0:
pass
elif mins > 0:
text += f'{secs:.0f} secs '
else:
text = f'{secs:.1f} secs '
return text[:-1]
def nonlinspace(x_min, x_max, n, phi):
""" like np.linspace. but with unequal spacing
Args:
x_min (double): maximum value
x_max (double): minimum value
n (int): number of points
phi (double): phi = 1 -> eqaul spacing, phi up -> more points closer to minimum
Returns:
y (list): grid with unequal spacing
"""
assert x_max > x_min
assert n >= 2
assert phi >= 1
# 1. recursion
y = np.empty(n)
y[0] = x_min
for i in range(1, n):
y[i] = y[i-1] + (x_max-y[i-1]) / (n-i)**phi
# 3. assert increaing
assert np.all(np.diff(y) > 0)
return y
def equilogspace(x_min,x_max,n):
""" like np.linspace. but (close to) equidistant in logs
Args:
x_min (double): maximum value
x_max (double): minimum value
n (int): number of points
Returns:
y (list): grid with unequal spacing
"""
pivot = np.abs(x_min) + 0.25
y = np.geomspace(x_min + pivot, x_max + pivot, n) - pivot
y[0] = x_min # make sure *exactly* equal to x_min
return y
@njit
def nonlinspace_jit(x_min, x_max, n, phi):
""" like nonlinspace, but can be used in numba """
y = np.zeros(n)
y[0] = x_min
for i in range(1,n):
y[i] = y[i-1] + (x_max-y[i-1]) / (n-i)**phi
return y
def gauss_hermite(n):
""" gauss-hermite nodes
Args:
n (int): number of points
Returns:
x (numpy.ndarray): nodes of length n
w (numpy.ndarray): weights of length n
"""
# a. calculations
i = np.arange(1,n)
a = np.sqrt(i/2)
CM = np.diag(a,1) + np.diag(a,-1)
L,V = np.linalg.eig(CM)
I = L.argsort()
V = V[:,I].T
# b. nodes and weights
x = L[I]
w = np.sqrt(math.pi)*V[:,0]**2
return x,w
def normal_gauss_hermite(sigma, n=7, mu=None, exp=True):
""" normal gauss-hermite nodes
Args:
sigma (double): standard deviation
n (int): number of points
mu (double,optinal): mean
exp (bool,optinal): take exp and correct mean (if not specified)
Returns:
x (numpy.ndarray): nodes of length n
w (numpy.ndarray): weights of length n
"""
if sigma == 0.0 or n == 1:
x = np.ones(n)
if mu is not None:
x += mu
w = np.ones(n)
return x,w
# a. GaussHermite
x,w = gauss_hermite(n)
x *= np.sqrt(2)*sigma
# b. log-normality
if exp:
if mu is None:
x = np.exp(x - 0.5*sigma**2)
else:
x = np.exp(x + mu)
else:
if mu is None:
x = x
else:
x = x + mu
w /= np.sqrt(math.pi)
return x,w
def create_shocks(sigma_psi,Npsi,sigma_xi,Nxi,pi=0,mu=None):
""" log-normal gauss-hermite nodes for permanent transitory model
Args:
sigma_psi (double): standard deviation of permanent shock
Npsi (int): number of points for permanent shock
sigma_xi (double): standard deviation of transitory shock
Nxi (int): number of points for transitory shock
pi (double): probability of low income shock
mu (double): value of low income shock
Returns:
psi (numpy.ndarray): nodes for permanent shock of length Npsi*Nxi+1
psi_w (numpy.ndarray): weights for permanent shock of length Npsi*Nxi+1
xi (numpy.ndarray): nodes for transitory shock of length Npsi*Nxi+1
xi_w (numpy.ndarray): weights for transitory shock of length Npsi*Nxi+1
Nshocks (int): number of nodes = Npsi*Nxi+1
"""
# a. gauss hermite
psi, psi_w = normal_gauss_hermite(sigma_psi, Npsi)
xi, xi_w = normal_gauss_hermite(sigma_xi, Nxi)
# b. add low inncome shock
if pi > 0:
# a. weights
xi_w *= (1.0-pi)
xi_w = np.insert(xi_w,0,pi)
# b. values
xi = (xi-mu*pi)/(1.0-pi)
xi = np.insert(xi,0,mu)
# c. tensor product
psi,xi = np.meshgrid(psi,xi,indexing='ij')
psi_w,xi_w = np.meshgrid(psi_w,xi_w,indexing='ij')
return psi.ravel(), psi_w.ravel(), xi.ravel(), xi_w.ravel(), psi.size
def tauchen(mu,rho,sigma,m=3,N=7,cutoff=np.nan):
""" tauchen approximation of autoregressive process
Args:
mu (double): mean
rho (double): AR(1) coefficient
sigma (double): std. of shock
m (int): scale factor for width of grid
N (int): number of grid points
cutoff (double):
Returns:
x (numpy.ndarray): grid
trans (numpy.ndarray): transition matrix
ergodic (numpy.ndarray): ergodic distribution
trans_cumsum (numpy.ndarray): transition matrix (cumsum)
ergodic_cumsum (numpy.ndarray): ergodic distribution (cumsum)
"""
# a. allocate
x = np.zeros(N)
trans = np.zeros((N,N))
# b. discretize x
std_x = np.sqrt(sigma**2/(1-rho**2))
x[0] = mu/(1-rho) - m*std_x
x[N-1] = mu/(1-rho) + m*std_x
step = (x[N-1]-x[0])/(N-1)
for i in range(1,N-1):
x[i] = x[i-1] + step
# c. generate transition matrix
for j in range(N):
trans[j,0] = norm.cdf((x[0] - mu - rho*x[j] + step/2) / sigma)
trans[j,N-1] = 1 - norm.cdf((x[N-1] - mu - rho*x[j] - step/2) / sigma)
for k in range(1,N-1):
trans[j,k] = norm.cdf((x[k] - mu - rho*x[j] + step/2) / sigma) - \
norm.cdf((x[k] - mu - rho*x[j] - step/2) / sigma)
# d. find the ergodic distribution
ergodic = _find_ergodic(trans)
# e. apply cutoff
if not np.isnan(cutoff):
trans[trans < cutoff] = 0
# f. find cumsums
trans_cumsum = np.array([np.cumsum(trans[i, :]) for i in range(N)])
ergodic_cumsum = np.cumsum(ergodic)
return x, trans, ergodic, trans_cumsum, ergodic_cumsum
def markov_rouwenhorst(rho,sigma,N=7):
"""Rouwenhorst method analog to markov_tauchen
Args:
rho (double): AR(1) coefficient
sigma (double): std. of shock
N (int): number of grid points
Returns:
y (numpy.ndarray): grid
trans (numpy.ndarray): transition matrix
ergodic (numpy.ndarray): ergodic distribution
"""
# a. parametrize Rouwenhorst for n=2
p = (1+rho)/2
trans = np.array([[p,1-p],[1-p,p]])
# b. implement recursion to build from n = 3 to n = N
for n in range(3, N + 1):
P1, P2, P3, P4 = (np.zeros((n, n)) for _ in range(4))
P1[:-1, :-1] = p * trans
P2[:-1, 1:] = (1 - p) * trans
P3[1:, :-1] = (1 - p) * trans
P4[1:, 1:] = p * trans
trans = P1 + P2 + P3 + P4
trans[1:-1] /= 2
# c. invariant distribution
ergodic = _find_ergodic(trans)
# d. scaling
s = np.linspace(-1, 1, N)
mean = np.sum(ergodic*s)
sigma_ = np.sqrt(np.sum(ergodic*(s-mean)**2))
s *= (sigma / sigma_)
y = np.exp(s) / np.sum(ergodic * np.exp(s))
# e. find cumsums
trans_cumsum = np.array([np.cumsum(trans[i, :]) for i in range(N)])
ergodic_cumsum = np.cumsum(ergodic)
return y, trans, ergodic, trans_cumsum, ergodic_cumsum
def _find_ergodic(trans,atol=1e-13,rtol=0):
""" find ergodic distribution from transition matrix
Args:
trans (numpy.ndarray): transition matrix
atol (double): absolute tolerance
rtol (double): relative tolerance
Returns:
(nump.ndarray): ergodic distribution
"""
I = np.identity(len(trans))
A = np.atleast_2d(np.transpose(trans)-I)
_u, s, vh = svd(A)
tol = max(atol, rtol * s[0])
nnz = (s >= tol).sum()
ns = vh[nnz:].conj().T
return (ns/(sum(ns))).ravel()
@njit
def choice(r,p_cumsum):
""" select from cumulated probilities
Args:
r (double): uniform random number
p_cumsum (numpy.ndarray): vector of cumulated probabilities, [x,y,z,...,1] where z > y > x > 0
Returns:
i (int): selection index
"""
i = 0
while r > p_cumsum[i] and i+1 < p_cumsum.size:
i = i + 1
return i
|
d2c9173a504c5317ebe0cb37d7064879ff4da658 | faterazer/LeetCode | /2032. Two Out of Three/Solution.py | 378 | 3.546875 | 4 | from collections import defaultdict
from typing import List
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
cnt = defaultdict(int)
for i, arr in enumerate((nums1, nums2, nums3)):
for x in arr:
cnt[x] |= 1 << i
return [k for k, v in cnt.items() if v & (v - 1)]
|
2924d27c8050b210ea6e5c472a15c57aba6f4c55 | rouseguy/learnAlgorithms2 | /py_sort.py | 325 | 3.875 | 4 | import os
import sys
if __name__ == "__main__":
fileName = input("enter the file name that has the numbers to sort:")
with open(fileName) as f:
data = f.readlines()
data = [int(d) for d in data]
print("Given numbers:", data)
sorted_num = sorted(data)
print("Sorted numbers:", sorted_num)
|
587cd3144ff3245a867c3d041d9c684026af0494 | Mgallimore88/GeneticAlgorithms | /EnuBubbleSort.py | 1,480 | 4.375 | 4 | # Takes an input list of values with positional tag and uses a bubble sort swapping algorithm
# to find and return the highest n values in the list.
# The inputs are of the fort [(tag_0, value_0), (tag_1, value_1), ...(tag n-1, value n-1)]
#
# If the 2nd argument
# of the input field is left blank, n = full list and the whole list is sorted.
# Otherwise only the n comparisons required are made and returned.
def bubble_sort(input_list, num_of_values=None): # Set default output to entire list
if num_of_values == None:
num_of_values = len(input_list)
else:
num_of_values = num_of_values
# proof# print(input_list)
n = 1
for _ in range(
num_of_values
): # ?? is it ok to have unused varibles in loops? Should a while loop be used instead or should I reference Shake somewhere? #Here a shake represents the rising to the top of the list of one max value
for bubble in range(
len(input_list) - n
): # bubble = one swap or move along the list
if input_list[bubble][1] > input_list[bubble + 1][1]:
input_list[bubble], input_list[bubble + 1] = (
input_list[bubble + 1],
input_list[bubble],
)
# proof# print("n " + str(n) + str(input_list))
n += 1
return input_list[-int(num_of_values) :]
# bubble_sort([(0, 34),(1, 2),(2, 777),(3, 45),(4, 50),(5, 40),(6, 231),(7, 0),(8, 5)], 4)
|
8426c6c806e0d7ff8d548b9e83b0cfb8a173a482 | Leaaaaaa/learn_python | /day7/使用集合.py | 1,090 | 4.15625 | 4 | #使用集合
def main():
set1 = {1, 2 , 3 , 3, 2,}
print(set1)
print('Length = ', len(set1))
set2 = set(range(1, 10))
print(set2)
set1.add(4)
set2.add(5)
set2.update([11,12])
print(set1)
print(set2)
set2.discard(5)
#remove的元素如果不存在会引发keyerror
if 4 in set2:
set2.remove(4)
print(set2)
#将元组转换成集合
set3 = set((1, 2, 3, 3, 3, 1))
print(set3.pop())
print(set3)
#集合的交集、并集、差集、对称差运算
print(set1 & set2)
#print(set1.intersection(set2))交集
print(set1 | set2)
#print(set1.union(set2)) 并集
print(set1 - set2)
#print(set1.defference(set2))差集
print(set1 ^ set2)
#print(set1.symmetric_difference(set2))对称差
#判断子集和超集
print(set2 <= set1)
#print(set2.issubset(set1))
print(set3 <= set1)
#print(set3.issubset(set1))
print(set1 >= set2)
#print(set1.issuperset(set2))
print((set1 >= set3))
#print(set1.issuperset(set30)
if __name__ == '__main__':
main() |
5933afe07555d99815fb9c050e09b01d7ebf560c | AndresDuque/Scientific-Programming | /relacion sobre gui/ejercicio3.py | 596 | 3.921875 | 4 | """Construye un visualizador de matrices."""
from Tkinter import *
import random
def RGBs(num):
# Colores RGB aleatoriso
return [[random.randint(0,255) for i in range(0,3)] for j in range(0,num)]
def rgb2Hex(rgb_tuple):
return '#%02x%02x%02x' % tuple(rgb_tuple)
def drawGrid(w,colors):
col = 0; row = 0
colors = [rgb2Hex(color) for color in colors]
for color in colors:
w.create_rectangle(col, row, col+1, row+1, fill=color, outline=color)
col+=1
if col == 100:
row += 1; col = 0
root = Tk()
w = Canvas(root)
w.grid()
colors = RGBs(5000)
drawGrid(w,colors)
root.mainloop()
|
1b190ab8117d4db4e3d7dc7e31d61ee26da5b48b | syvn/pythonStudy | /fun-build-in/typeConversion.py | 1,008 | 4.09375 | 4 | # 内置方法 类型转换
# int() 将 字符串或数字转换成整数
# 语法 class int(x, base=10)
print(int()) # 0 不传入参数时, 得到结果0
print(int(3)) # 3
print(int(3.1)) # 3
# float() 将整数和字符串转换成浮点数
print(float(1)) # 1.0
print(float()) # 0.0
print(complex(1, 2)) # 1 + 2j
print(complex('1+2j')) # 1 + 2j '1+2j' + 前后无空格
# str() 将对象转化为适于人阅读的形式
# class str(object='')
s = 'demo'
print(str(s)) # demo
print(type(str({'demo': '1'}))) # "{'demo': '1'}" <class 'str'>
# eval() 用来执行一个字符串表达式,并返回表达式的值
# eval(expression[, globals[, locals]])
# expression -- 表达式 使用引号引起来
# globals -- 变量作用域, 全局命名空间, 如果被提供, 则必须是一个字典对象
# locals -- 变量作用域, 局部命名空间, 如果被提供, 可以是任何映射对象
x = 7
print(eval('3 * x')) # 21
print(eval('pow(2, 2)')) # 4
list1 = [1, 1, 2, 3]
print(tuple(list1)) |
e9ca860865168c9a2e13d498a1ba04864a2a4b0a | dohertym19/portfolio-stub | /python/ages.py | 111 | 3.9375 | 4 | if age > 0 and age<=2:
print("baby")
elif age >2 and age <18:
print("child")
else:
print(adult)
|
368ae546177730dc625f523d60798536d858e2a0 | mikaelgba/PythonDSA | /cap3/Condicionais.py | 2,103 | 4.25 | 4 | if( 3 < 5):
print("Saint Seiya!!")
if( 10 == 5):
print("true")
else:
print("false")
if True:
print("True")
#Condicionis Aninhadas
idade = 5
nome = "Yoda"
if(idade >= 5):
if(nome == "Yoda"):
print("Iti Malia, Baby Yoda!!")
else:
print("Você não é o Baby Yoda")
#Condicional logico AND
idade = 5
nome = "Yoda"
if(idade >= 5) and (nome == "Yoda"):
print("Iti Malia, Baby Yoda!!")
else:
print("Você não é o Baby Yoda")
#Condicional logico OR
idade = 4
if(idade >= 5) or (nome == "Yoda"):
print("Hum, talvez você não seja o Iti Malia, Baby Yoda!!")
#Condicional logico NOT
nome2 = "Yoda"
if not (nome2 == "Yoda"):
print("Você não é o Baby Yoda")
else:
print("Iti Malia, Baby Yoda!!")
#Condicinal Elif
cavaleiro = "Seiya"
if(cavaleiro == "Seiya"):
print(cavaleiro, "O motador de Deuses")
elif(cavaleiro == "Hades"):
print(cavaleiro, "Geral ai morrer!")
else:
print("Quem eis você?")
# -----
filme_premiado = "Coringa"
oscar = 4
if(filme_premiado == "Coringa") and (oscar == 4):
print(filme_premiado,"ganhou",oscar,"Oscars.")
else:
print("Irlandês ganhou alguns também.")
#Usando mais de uma condicição no If
filme_premiado2 = input("Filme? ")
oscar2 = int(input("Quantidade de Oscars? "))
if(filme_premiado2 == "Coringa") and (oscar2 == 4):
print(filme_premiado2,"ganhou",oscar2,"Oscars.")
else:
print("Irlandês ganhou",oscar2)
#Usando três condicições no If
oscar_melhor_ator = input("Melhor ator? ")
filme_premiado2 = input("Filme? ")
oscar2 = int(input("Quantidade de Oscars? "))
if(filme_premiado2 == "Coringa") and (oscar2 == 4) and (oscar_melhor_ator == "Joaquin Phoenix"):
print(filme_premiado2,"ganhou",oscar2,"Oscars, entre eles o de melhor ator para",oscar_melhor_ator)
else:
print("Irlandês ganhou",oscar2)
# -----
valor = float(input("Valor? "))
quant = int(input("Quantidade? "))
desconto = input("Há desconto? ")
total = valor * quant
if(total >= 500) and (desconto == "sim"):
total -= (total/25)
print("Total = %r"%(total))
else:
print("Total = %r"%(total))
|
4682bec9062b50c7a3c356398a56c1f4aa1ae725 | richardrtutor/Personal-Library | /main.py | 12,957 | 4.125 | 4 | import os
from typing import Optional, Dict
from dataclasses import dataclass
@dataclass
class Book:
title: str
author: str
genre: str
def log_sign() -> str:
log_action = input("[Log In] or [Sign Up]\n> ").title()
while not val_login(log_action):
print("invalid action")
log_action = input("[Log In] or [Sign Up]\n> ").title()
if val_login(log_action):
if log_action == "Log In":
user = login()
else:
user = signup()
return user
def val_login(log_action: str) -> bool:
return log_action == "Log In" or log_action == "Sign Up"
def signup() -> str:
name = input("Username: ")
line = find_user(name)
while line is not None:
print("This account already exists")
action = input("[sign up] or [log in]\n> ").title()
if action == "Sign Up":
name = input("Username: ")
line = find_user(name)
elif action == "Log In":
user = login()
return user
else:
print("Invalid action")
password = input("Password: ")
validate = input("Re-enter password: ")
while password != validate:
print("Passwords do not match.")
password = input("Password: ")
validate = input("Re-enter password: ")
with open("users.txt", "a") as users_file:
users_file.write(name + " " + password)
return name
def login() -> str:
line = None
name = input("Username: ")
password = input("Password: ")
line = find_user(name)
while line is None:
print("Invalid username or password")
print("[Try] again or [sign] up.")
action = input("> ").title()
if action == "Try":
name = input("Username: ")
password = input("Password: ")
line = find_user(name)
else:
user = signup()
return user
username, userpass = line.split()
while password != userpass:
print("Invalid password")
password = input("Password: ")
return username
def find_user(name: str) -> Optional[str]:
with open("users.txt", "r") as users_file:
lines = users_file.readlines()
for line in lines:
a, b = line.split()
if name == a:
return line
return None
def genre_inp() -> str:
genre = input(
"\nChoose a Genre:\nFiction\nNon-Fiction\nHorror\nAction\nRomance\nSci-Fi\nDrama\nComedy\n\nInput Book Genre: "
).title()
while not val_genre(genre):
print("Invalid genre")
genre = input("> ").title()
return genre
def val_genre(genre: str) -> bool:
genres = [
"Horror",
"Non-Fiction",
"Fiction",
"Action",
"Romance",
"Drama",
"Comedy",
"Sci-Fi",
]
if genre in genres:
return True
return False
def add(books: Dict[str, Book]):
title = input("Input Book Title or [back] to cancel: ")
if title != "back":
author = input("Author Name: ")
books_file = open("books.txt")
lines = books_file.readlines()
for line in lines:
a, b, c = line.split(" - ")
while title == a and author == b:
print("This book is already in the system.")
title = input("Input Book Title: ")
author = input("Author Name: ")
genre = genre_inp()
with open("books.txt", "a+") as books_file:
books_file.write(f"\n{title} - {author} - {genre}")
books[title] = Book(title, author, genre)
def all_books() -> None:
try:
with open("books.txt") as books_file:
print("\n")
for line in books_file:
print(line.strip())
print("\n")
except FileNotFoundError:
print("No books in system")
def view(user: str, books: Dict[str, Book]) -> None:
by = input(
"View by [all], view by [author], view by [genre], view by [title], view by [tag], or go [back]\n> "
).title()
while by != "Back":
if by == "All":
all_books()
elif by == "Author":
author()
elif by == "Genre":
by_genre()
elif by == "Title":
title()
elif by == "Tag":
view_tag(user)
else:
print("Invalid action")
by = input(
"View by [all], view by [author], view by [genre], view by [title], view by [tag], or go [back]\n> "
).title()
def view_tag(user):
tag = input("What tag would you like to view? [back] to cancel\n> ")
if tag != "back":
try:
with open(f"{user}/{tag}.txt", "r") as tag_file:
for line in tag_file:
print(line)
except FileNotFoundError:
print("This tag does not exist... Yet")
def author():
author = input("Which author are you looking for? [back] to cancel\n> ")
if author != "back":
is_books = False
with open("books.txt") as books_file:
print("\n")
for line in books_file:
if author in line:
print(line.strip())
is_books = True
if is_books == False:
print("There are no books with this author listed")
print("\n")
def by_genre() -> None:
genre = input("Genre: ")
is_genre = False
with open("books.txt") as books_file:
print("\n")
for line in books_file:
if genre in line:
print(line.strip())
is_genre = True
if is_genre == False:
print("There are no books with this genre listed")
print("\n")
def title() -> None:
title = input("Book Title or [back] to cancel: ")
if title != "back":
is_title = False
with open("books.txt") as books_file:
print("\n")
for line in books_file:
if title in line:
print(line.strip())
is_title = True
if is_title == False:
print("There are no books with this title listed")
print("\n")
def opts() -> str:
while True:
action = input(
"What would you like to do? [add] a book, [delete] a book, [view] by, add a [tag], [Log Out], or [quit]\n> "
).title()
if val_act(action):
return action
else:
print("This is not a valid action!")
def val_act(action: str) -> bool:
actions = [
"Add", "All", "View", "Tag", "Delete", "Update", "Log Out", "Quit"
]
if action in actions:
return True
return False
def tag(user: str, books: Dict[str, Book]) -> None:
try:
os.mkdir(user)
except FileExistsError:
pass
action = input(
"Would you like to [create] a tag, [delete] a tag, [edit] a tag, or [add] to a tag, or go [back]?\n> "
).title()
while action != "Back":
if action == "Create":
create_tag(user, books)
elif action == "Add":
add_tag(user, books)
elif action == "Delete":
delete_tag(user, books)
elif action == "Edit":
edit_tag(user, books)
else:
print("Invalid action")
action = input(
"Would you like to [create] a tag, [delete] a tag, [edit] a tag, or [add] to a tag?\n> "
).title()
def delete_tag(user: str, books: Dict[str, Book]) -> None:
tag = input("Which tag would you like to remove? [back] to cancel\n> ")
if tag != "back":
try:
with open(f"{user}/{tag}.txt"):
pass
final = input(f"Are you sure you want to delete {tag} [Y/N]?\n> ")
if final == "Y":
os.remove(f"{user}/{tag}.txt")
else:
print(f"{tag} tag was not deleted.")
except FileNotFoundError:
print("This tag list does not exist.")
def edit_tag(user: str, books: Dict[str, Book]) -> None:
action = input(
"Would you like to [rename] the file or edit the [list]?\n> ").title()
if val_edit(action):
if action == "Rename":
edit_tag_name(user, books)
elif action == "List":
edit_tag_list(user, books)
else:
print("This is not a valid action!")
def edit_tag_list(user: str, books: Dict[str, Book]) -> None:
tag = input("Which tag's list are you editing?\n> ")
if os.path.exists(f"{user}/{tag}.txt"):
with open(f"{user}/{tag}.txt", "r") as tfile:
lines = tfile.readlines()
for book in lines:
print(book)
which_book = input(
"Which Book are you removing from this tag's list?\n> ").title()
file = open(f"{user}/{tag}.txt", "w")
file.close()
with open(f"{user}/{tag}.txt", "a+") as tag_file:
for line in lines:
a, b, c = line.split(" - ")
if which_book == a:
lines.remove(line)
else:
tag_file.write(line)
print(line)
else:
print("This tag does not exist!")
def edit_tag_name(user: str, books: Dict[str, Book]):
tag = input("What tag are you renaming?\n> ")
if os.path.exists(f"{user}/{tag}.txt"):
new = input("New tag name?\n> ")
os.rename(fr"{user}/{tag}.txt", fr"{user}/{new}.txt")
else:
print("This tag does not exist!")
def val_edit(action: str) -> bool:
acts = ["Rename", "List"]
if action in acts:
return True
else:
return False
def create_tag(user: str, books: Dict[str, Book]) -> None:
tag = input("Name the tag: ")
with open(f"{user}/{tag}.txt", "a+") as tfile:
tfile.write("")
add_to_tag(user, books, tag)
print("\n")
def add_tag(user: str, books: Dict[str, Book]) -> None:
tag = input("Which tag would you like to add to? [back] to cancel.\n> ")
while True:
if os.path.exists(f"{user}/{tag}.txt"):
add_to_tag(user, books, tag)
break
elif tag == "back":
break
else:
print("This tag does not exist yet!")
tag = input("Which tag would you like to add to?\n> ")
def add_to_tag(user: str, books: Dict[str, Book], tag: str) -> None:
adding = input("Type a book title or [Q]uit.\n> ")
while adding != "Q":
if val_add(adding, user, tag, books):
with open(f"{user}/{tag}.txt", "a+") as tfile:
tfile.write(books[adding].title + " - " +
books[adding].author + " - " + books[adding].genre)
else:
if adding not in books:
print("This book is not in the system.")
else:
print("This book already exists in this tag!")
adding = input("Type a book title or [Q]uit.\n> ")
def val_add(adding: str, user: str, tag: str, books: Dict[str, Book]) -> bool:
file = open(f"{user}/{tag}.txt", "r")
lines = file.readlines()
file.close()
if adding in books:
double = False
for line in lines:
a, b, c = line.split(" - ")
if adding == a:
double = True
if double == True:
return False
else:
return True
return False
def delete_book(books: Dict[str, Book]) -> None:
books_file = open("books.txt")
lines = books_file.readlines()
title = input("Which book would you like to delete? [back] to cancel\n> ")
if title != "back":
is_valid = False
for line in lines:
a, b, c = line.split(" - ")
if title == a:
with open("books.txt", "a+"):
lines.remove(line)
is_valid = True
del books[title]
with open("books.txt", "w") as books_file:
for line in lines:
books_file.write(line)
if is_valid == False:
print("This book does not exist")
def main() -> None:
books: Dict[str, Book] = {}
with open("books.txt", "r") as books_file:
lines = books_file.readlines()
for line in lines:
a, b, c = line.split(" - ")
books[a] = Book(a, b, c)
user = log_sign()
while True:
action = opts()
if action == "Add":
add(books)
elif action == "View":
view(user, books)
elif action == "Tag":
tag(user, books)
elif action == "Delete":
delete_book(books)
elif action == "Log Out":
print("\nYou have successfuly logged out!\n")
user = log_sign()
elif action == "Quit":
break
else:
print("Invalid action")
if __name__ == "__main__":
main() |
f8cb8818e2994ca488745e897db6ff05b64bda72 | anumoshsad/Interactive-Python-Programming-Coursera | /Project_5_memory.py | 1,785 | 3.59375 | 4 | # http://www.codeskulptor.org/#user42_ZmJ4LHyjgQ_1.py
# implementation of card game - Memory
import simplegui
import random
turn = 0
# helper function to initialize globals
def new_game():
global state, cards, exposed, prev
prev = [-1,-1]
turn = 0
state = 0
cards = list(range(8)) + list(range(8))
random.shuffle(cards)
exposed = [False]*16
# define event handlers
def mouseclick(pos):
global state,turn
# add game state logic here
idx = pos[0]/50
if not exposed[idx]:
exposed[idx]=True
if state == 0:
state = 1
turn+=1
elif state == 1:
state = 2
else:
if cards[prev[0]]!=cards[prev[1]]:
exposed[prev[0]]=False
exposed[prev[1]]=False
state = 1
turn+=1
prev[state-1] = idx
label.set_text("Turns = "+str(turn))
# cards are logically 50x100 pixels in size
def draw(canvas):
for card_index in range(len(cards)):
card_pos = [50 * card_index+10, 70]
if exposed[card_index]:
canvas.draw_text(str(cards[card_index]), card_pos, 70, 'White')
else:
canvas.draw_polygon([(50 * card_index,0),(50 * card_index+50,0),(50 * card_index+50,100),(50 * card_index,100)],2,'black', 'green')
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", 800, 100)
frame.add_button("Reset", new_game)
label = frame.add_label("Turns = "+str(turn))
# register event handlers
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)
# get things rolling
new_game()
frame.start()
# Always remember to review the grading rubric |
e730fc2bb32283d132269f53201a6c52d0625b4a | xloso/m02_preboot | /factorialhechopormiconFor.py | 458 | 4.03125 | 4 | def factorial (x):
total = 1
for num in range(2, x+1):
total = total * num
return total
def factorialRecursivo(n):
if n>0:
return n * factorialRecursivo(n-1)
else:
return 1
numero = int(input("introduce número factorial: "))
print("el factorial con for de {}, es {}".format(numero, factorial(numero)))
print("el factorial recursivo de {}, es {}".format(numero, factorialRecursivo(numero))) |
db5b6322896b4d7fda85c1da7fc0dcaf27948195 | nebel-dev/leetcode | /位运算/137. 只出现一次的数字 II.py | 2,831 | 3.984375 | 4 | """
给你一个整数数组nums ,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 。请你找出并返回那个只出现了一次的元素。
示例 1:
输入:nums = [2,2,3,2]
输出:3
示例 2:
输入:nums = [0,1,0,1,0,1,99]
输出:99
提示:
1 <= nums.length <= 3 * 10^4
-2^31 <= nums[i] <= 2^31 - 1
nums 中,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次
进阶:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
import collections
from typing import List
l1 = [0, 1, 0, 1, 0, 1, 99]
l2 = [-2, -2, 1, 1, -3, 1, -3, -3, -4, -2]
# 哈希表
class Solution:
def single_number(self, nums: List[int]) -> int:
freq = collections.Counter(nums)
ans = [num for num, occ in freq.items() if occ == 1][0]
return ans
solution = Solution()
res1 = solution.single_number(l1)
res2 = solution.single_number(l2)
# 位运算
"""
python负数的存储方式是补码,但是想要以2进制输入-5,
要以-0b101形式,因为python整数没有位数限制,无法识别符号位,
所以-5的补码 0b11111011 会被当作正整数,
ans -= (1 << i)的目的是将负数的补码转换为 ”负号+原码” 的形式,这样python就可以正常识别2进制下的负数
"""
class Solution2:
def single_number(self, nums: List[int]) -> int:
ans = 0
for i in range(32):
total = sum((num >> i) & 1 for num in nums)
if total % 3:
if i == 31:
ans -= (1 << i)
else:
ans |= (1 << i)
return ans
s2 = Solution2()
r2 = s2.single_number(l2)
# 位运算
"""
因为python整数不限制位数,负数以补码形式存储
8位情况下-1的补码 0b11111111 不会被python识别为-1,而是识别为127
可以认为python的符号位在无限远处,而-1的补码应该是111...1111(无限多的1)
所以要执行 ~(res ^ 0xffffffff) 将0b11111111以外的位转换为1,这样才是在python内部的补码存储格式,
这样才能正确识别负数
"""
class Solution3:
def single_number(self, nums: List[int]) -> int:
counts = [0] * 32
for num in nums:
for j in range(32):
counts[j] += num & 1
num >>= 1
res, m = 0, 3
for i in range(32):
res <<= 1
res |= counts[31-i] % m
return res if counts[31] % m == 0 else ~(res ^ 0xffffffff)
s3 = Solution3()
r4 = s3.single_number(l2)
if __name__ == "__main__":
print("result =", res1, res2, r2, r4)
|
995874c43ae255b35aefe9c88c9064c77bb24426 | Damoy/AlgoTraining | /LeetCode/BinarySearchTreeFromPreorder.py | 573 | 3.5625 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def bstFromPreorder(preorder):
if not preorder or not len(preorder):
return None
return util(0, len(preorder) - 1, preorder)
def util(start, end, preorder):
if start > end:
return None
node = TreeNode(preorder[start])
i = start
while i <= end:
if preorder[i] > node.val:
break
i += 1
node.left = util(start + 1, i - 1, preorder)
node.right = util(i, end, preorder)
return node |
4cc08077aaba1910a4935c84e3bd2b4af5cbec46 | shankar7791/MI-10-DevOps | /Personel/AATIF/Python/03-MAR/palinOrSym.py | 838 | 4.1875 | 4 | def palin(string):
st = 0
end = len(string)-1
f = 0
while(st<end):
if (string[st]== string[end]):
st += 1
end -= 1
else:
f = 1
break;
if f == 0:
print("The entered string is palindrome")
else:
print("The entered string is not palindrome")
def symm(string):
l = len(string)
f1 = 0
if l%2 == 0:
mid = l//2
else:
mid = l//2 + 1
s1 = 0
s2 = mid
while(s1 < mid and s2 < l):
if (string[s1] == string[s2]):
s1 = s1 + 1
s2 = s2 + 1
else:
f1 = 1
break
if f1 == 0:
print("The entered string is symmetrical")
else:
print("The entered string is not symmetrical")
string = input("Enter the string: ")
palin(string)
symm(string) |
0939885322d9a139e117d9ab92e7e008fe254a1f | KiD21606/HackerRank | /python/Strings/Text_Wrap.py | 353 | 3.75 | 4 | import textwrap
def wrap(string, n):
result = ''
k = len(string)//n
for i in range(k):
result += string[n*i:n*(i+1)]+'\n'
if len(string)%n != 0:
result += string[n*k:]+'\n'
return result
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
|
3c513e57d09c1b86e19ef3e57423b3b0d96069f6 | Princecodes4115/myalgorithms | /BST/nextNode.py | 3,271 | 3.890625 | 4 | class TreeNode:
def __init__(self,val):
self.val = val
self.left = None
self.right = None
class Tree:
def __init__(self,root):
self.root = root
def NextNode(root,val):
q = Queue()
print ("enqueuing root")
q.enqueue(root)
currentlevel = 1
nextlevel = 0
while(not q.isEmpty()):
#print ("Queue Size", q.size())
#print ("Size is", q.size())
Temp = q.dequeue()
print ("temp val", Temp.val)
print ("currentlevel", currentlevel)
currentlevel = currentlevel - 1
print ("currentlevel after decrementing", currentlevel)
if(Temp.val == val):
if(currentlevel != 0):
return q.dequeue().val
else:
return None
if(Temp.left != None):
q.enqueue(Temp.left)
nextlevel += 1
if(Temp.right != None):
q.enqueue(Temp.right)
nextlevel += 1
#print(Temp.val)
if(currentlevel == 0):
currentlevel = nextlevel
nextlevel = 0
#print ("Size", q.size())
#break
class QueueNode:
def __init__(self, val):
self.val = val
self.next = None
class Queue:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def enqueue(self, val):
newmember = QueueNode(val)
if (self.tail is None):
print ("Adding new val")
self.head = newmember
self.tail = newmember
else:
oldtail = self.tail
oldtail.next = newmember
self.tail = newmember
self.length = self.length + 1
#self.printQueue()
def dequeue(self):
head = self.head
tail = self.tail
if (self.head is None):
return None
self.length = self.length - 1
if (self.head == self.tail):
remmember = self.head
self.head = None
self.tail = None
return remmember.val
else:
remmember = self.head
self.head = self.head.next
return remmember.val
def size(self):
return self.length
def isEmpty(self):
if self.length == 0:
return True
return False
# if(not self.head):
# self.length = 0
# return self.length
# runner = self.head
# print(runner.val)
# while(runner is not None):
# self.length += 1
# runner = runner.next
# return self.length
def printQueue(self):
r = self.head
#print(r.val)
while (r is not None):
print(r.val)
r = r.next
if __name__ == "__main__":
print ("welcome to python")
n1 = TreeNode(1)
n2 = TreeNode(2)
n3 = TreeNode(3)
n4 = TreeNode(4)
n5 = TreeNode(5)
n6 = TreeNode(6)
n7 = TreeNode(7)
n8 = TreeNode(8)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
n3.left = n6
n6.left = n7
n6.right = n8
# n3.right = n4
t = Tree(n1)
print (NextNode(n1,3))
# q = Queue()
# q.enqueue(1)
# q.enqueue(2)
# q.enqueue(3)
# #print (q.dequeue())
# q.printQueue() |
5e735b97b62fbb85a86ddc7bc7c9360313fa9025 | bkruszewski/iSAPython3 | /day4/indeksy_kolekcji.py | 460 | 3.5 | 4 | # czasem chcemy wiedziec, z którym elemeentem mamy doczynienia
# chcemy znać jego indeks
imie = "Hermenegilda"
# tworzymy licznik zawierający indeks aktualnego elementu
indeks = 0
for c in imie:
print(indeks, c)
# musimy pamiętać o aktualizacji indeksu!
indeks += 1
# enumerate zwraca dwie wartości:
# indeks elementu w kolekcji oraz
# wartość elementu pod tym indeksem
for (indeks, litera) in enumerate(imie):
print(indeks, litera) |
52aff37ce4867baa08efb00e40f89c36e8ec4034 | pauloesantos/EstudoPython | /PythonParaZumbis/Lista1/questao8.py | 270 | 4.09375 | 4 | # Paulo Eduardo Faundes dos Santos
# Curso Python para Zumbis
# Lista de Exercício 1
# Questão 8
# Converta um temperatura digitada em Fahrenheit para Celsius. C=(F-32)*5/9
F = float(input("Qual a temperatura em Fahrenheit: "))
C = (F - 32) * 5 / 9
print("A temperatura em Celsius é: %.2f" %C) |
a33d73821bbfa1bd9d97ff9530bae223acdd8436 | shriharshs/AlgoDaily | /leetcode/52-n-queens-ii/main.py | 2,182 | 3.5625 | 4 | """
1st approach: backtracking
- - similar to lc37, lc51
- https://www.youtube.com/watch?v=5v6zdfkImms
- basically try every possisbilities within the safe region
- for each coordinate, we need to check the whole board to see if it is safe to place a queen
Time O(n^4) for each coordinate, we need to check if safe
Space O(n^2)
340 ms, faster than 5.46%
"""
class Solution(object):
def __init__(self):
self.result = set()
def totalNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
b = Board(n)
self.backtracking(b, 0, n)
return len(self.result)
def backtracking(self, b, row, n):
if row == n:
self.result.add(b.stringify())
return
for i in range(n):
if b.isSafe(row, i):
b.place(row, i)
self.backtracking(b, row+1, n)
b.remove(row, i)
class Board(object):
def __init__(self, n):
temp = []
for i in range(n):
temp.append(n*".")
self.m = temp
self.n = n
def place(self, row, col):
# basically it is self.m[row][col] = "Q"
self.m[row] = self.m[row][:col]+"Q"+self.m[row][col+1:]
def remove(self, row, col):
# basically it is self.m[row][col] = "."
self.m[row] = self.m[row][:col]+"."+self.m[row][col+1:]
def isSafe(self, row, col):
# check row and col O(n)
for i in range(self.n):
if self.m[i][col] == "Q":
return False
if self.m[row][i] == "Q":
return False
# check diagonal O(n^2)
for i in range(self.n):
for j in range(self.n):
if i+j == row+col or i-j == row-col:
if i != row and j != col and self.m[i][j] == "Q":
return False
return True
def stringify(self):
# O(n)
temp = ""
for i in range(self.n):
temp += self.m[i]
return temp
print(Solution().totalNQueens(4))
print(Solution().totalNQueens(5))
print(Solution().totalNQueens(8))
|
8147797c57ac771efb7afc854690ec3ae0991c5e | doraemon1293/Leetcode | /archive/794ValidTic-Tac-ToeState.py | 1,277 | 3.53125 | 4 | # coding=utf-8
class Solution:
def validTicTacToe(self, board):
"""
:type board: List[str]
:rtype: bool
"""
import itertools
nx=no=0
for ch in itertools.chain(*board):
if ch=="X":
nx+=1
if ch=="O":
no+=1
if nx-no>1 or nx-no<0:
return False
wx=wo=False
for row in board:
if tuple(row)==("X","X","X"):
wx=True
if tuple(row)==("O","O","O"):
wo=True
for col in zip(*board):
if col==("X","X","X"):
wx=True
if col==("O","O","O"):
wo=True
if board[0][0]==board[1][1]==board[2][2]=="X":
wx=True
if board[0][0]==board[1][1]==board[2][2]=="O":
wo=True
if board[0][2]==board[1][1]==board[2][0]=="X":
wx=True
if board[0][2]==board[1][1]==board[2][0]=="O":
wo=True
#print(wx,wo,nx,no)
if wx==wo==True:
return False
if wx and nx!=no+1:
return False
if wo and no!=nx:
return False
return True
board=["XOX","O O","XOX"]
print(Solution().validTicTacToe(board))
|
12496c6e969bffd6ecc770ad6804b1626a645286 | KevinVega-afk/Matracas13 | /NumeroDeVueltas.py | 499 | 4 | 4 | #Programa capaz de calcular el número de vueltas de una llanta en 1 km
print("Programa que calcula el número de vueltas de una llanta en 1Km")
print("Primero debemos calcular cuantas vueltas dara la llanta en un diametro de 50cm")
V = 3.1416 * 50
print("La llanta da", V ,"vueltas")
print("Ahora debemos homologar las medidas")
M = (V/100000)
print(M)
print("Por ultimo hallar la cantidad de vueltas que da la llanta")
Vu = (1/M)
print("La cantidad de vueltas que da la llanta son:", Vu) |
f27a2596b6aa2c969f2993812e554c092df3040c | aliyahyaaamir/practice | /microsoft/fair_indexes.py | 642 | 3.640625 | 4 |
def fair_indexes(A: list, B: list) -> int:
# Find the number of fair indexes
num_fair_indexes = 0
arr_length = len(A)
for i in range(1, arr_length):
if sum(A[0:i]) == sum(A[i:]) == sum(B[0:i]) == sum(B[i:]):
num_fair_indexes += 1
return num_fair_indexes
if __name__ == "__main__":
"""
k = 2, 3
A[0] -> A[k-1] A[k] -> A[N-1]
"""
A = [4, -1, 0, 3]
B = [-2, 5, 0, 3]
A = [2, -2, -3, 3]
B = [0, 0, 4, -4]
A = [4, -1, 0, 3]
B = [-2, 6, 0, 4]
A = [3, 2, 6]
B = [4, 1, 6]
A = [1, 4, 2, -2, 5]
B = [7, -2, -2, 2, 5]
k = fair_indexes(A, B) |
0e3e3015b609abac4518f30111613d6d50844a87 | phyupyarko/python-exercises | /ex34.py | 227 | 3.890625 | 4 | animals = ['bear','python3.6', 'peacock', 'kangaroo', 'whale','platypus']
i=0
numbers = []
while i<6:
for name in animals:
print(f"The first animal is at {i} and is a animals{i}" )
numbers.append(i)
i = i + 1
|
6f2a1d6127c93b6d788d62778f2b703024b43b48 | Gurnur/Practice_problems | /remove_element/remove_element.py | 1,069 | 3.953125 | 4 | '''
Leetcode 27. Remove Element
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example 1:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length.
'''
from sys import stdin
class Solution:
def remove_element(self, nums, val):
if len(nums) == 0:
return 0
j = 0
for i in range(len(nums)):
if nums[i] != val:
nums[j], nums[i] = nums[i], nums[j]
j += 1
return j
input = stdin.readline
print('Input the array: ')
arr = list(map(int, input().split()))
print('Input the num to be removed: ')
val = int(input())
obj = Solution()
newlen = obj.remove_element(arr, val)
print(arr) |
6c2bfcdab26c28c204b9e247201b531ccebd4ba6 | ankitath/python_scripts | /practice13.py | 184 | 3.53125 | 4 | import re
name = input("Enter file:")
hand = open(name)
x=list()
for line in hand:
y = re.findall('[0-9]+',line)
x = x+y
sum=0
for z in x:
sum = sum + int(z)
print(sum) |
2ea96ca8ae387081f3d74555c06d9e1db7a32025 | ealarap/saturdays-ai | /src/week3-exe/listsintersection.py | 571 | 4.03125 | 4 | #!/usr/bin/python
class ListsIntersection:
def __init__(self, list1, list2):
self.list1 = list1
self.list2 = list2
def getListsIntersection(self):
return list ( set( self.list1) & set( self.list2) )
def main():
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
lIntersection = ListsIntersection(a,b)
intersec = lIntersection.getListsIntersection()
print("Intersection of list a= {}, and b = {}, is: {}".format(a, b, intersec))
if __name__ == '__main__':
main()
|
8909a072bde54baccd77d170a7c0956e27df2f02 | njlopes/Atividade-Sem03-T2 | /Preço.py | 189 | 3.546875 | 4 | preco=float(input("Digite o preço:"))
preco_com_desconto=preco * 0.90
preco_com_desconto=round(preco_com_desconto, 2)
print("Preço com desconto:", preco_com_desconto)
|
0bfb93912f43ff416b5e22805efee48f6fd33068 | jackle98/Deque-Code- | /quiz.py | 466 | 3.90625 | 4 | from Deque_Generator import get_deque
def rec_palindrome(dq):
if dq.pop_front()==dq.pop_back() and len(dq)>1:
return rec_palindrome(dq)
else:
if len(dq)<=1:
return True
else:
return False
def is_palindrome(character_string):
dq = get_deque()
for c in character_string:
dq.push_back(c)
return rec_palindrome(dq)
print(is_palindrome(input("Enter a phrase of lowercase characters only: ")))
|
9baa5be30bbfa11a9c4ffe07b3fac05d5e91a742 | dzsnowings/girlswhocode | /Python/draw_shapes.py | 2,468 | 4.3125 | 4 | from turtle import *
import math
# Name your Turtle.
t = Turtle()
# Set Up your screen and starting position.
setup(600, 600)
goto(0,0)
### Write your code below:
sides = int(input("Enter the number of sides: "))
color = input("Enter the color of your shape: ")
print("Your shape will be", color, "and have", sides, "sides.")
def drawShapeRight():
for i in range(sides):
fillcolor(color)
pencolor(color)
begin_fill()
pensize(10)
pendown()
forward(100)
right(360/sides)
penup()
end_fill()
def drawShapeBackwardRight():
for i in range(sides):
fillcolor(color)
pencolor(color)
begin_fill()
pensize(10)
pendown()
back(100)
right(360/sides)
penup()
end_fill()
def drawShapeLeft():
for i in range(sides):
fillcolor(color)
pencolor(color)
begin_fill()
pensize(10)
pendown()
forward(100)
left(360/sides)
penup()
end_fill()
def drawShapeBackwardLeft():
for i in range(sides):
fillcolor(color)
pencolor(color)
begin_fill()
pensize(10)
pendown()
back(100)
left(360/sides)
penup()
end_fill()
def tessTri():
for i in range(4):
drawShapeRight()
drawShapeBackwardRight()
drawShapeLeft()
drawShapeBackwardLeft()
forward(200)
def tessHex():
for i in range(4):
drawShapeRight()
drawShapeBackwardRight()
forward(200)
speed(0)
drawShapeRight()
print("Here is your shape!")
yes = input("Do you want to draw a tessellation? ")
if yes == "yes":
tessellation = input("Do you want your tessellation to be made with triangles or hexagons? ")
if tessellation == "triangles":
clear()
sides = 3
speed(0)
pensize(1)
goto(-300, -200)
tessTri()
goto(-350, -100)
tessTri()
goto(-300, 0)
tessTri()
goto(-350, 100)
tessTri()
goto(-300, 200)
tessTri()
print("Here is your tessellation of triangles!")
if tessellation == "hexagons":
clear()
sides = 6
speed(0)
pensize(1)
goto(-300, -200)
tessHex()
goto(-300, 150)
tessHex()
print("Here is your tessellation of hexagons!")
# Close window on click.
exitonclick()
|
fd409c2161d42bf199553f0768d9e5355ffd64fa | niavivek/Python_programs | /all_files/hw9/lab_10_exercises.py | 2,110 | 3.9375 | 4 | from functools import reduce
####
Take a list of numbers, square each element
my_nums = [1, 2, 3, 4, 5]
### Imperatively
squared_nums = []
for num in my_nums:
squared_nums.append(num * num)
### Functionally
squared_nums = map(lambda x: x * x, range(1, 6))
### Functionally convert this list to a list of strings, not ints
squared_strings = map(str, squared_nums)
### Functionally flip the digits on all of the strings
squared_strings_reversed = map(reversed, squared_strings)
### Take your list of squared numbers and make a list of only the even ones
### Imperatively
even_squared_nums = []
for squared_num in squared_nums:
if squared_num % 2 == 0:
even_squared_nums.append(squared_num)
### Functionally
even_squared_nums = filter(lambda x: x % 2 == 0, squared_nums)
### Combine the answers from the first two to create a list of even squares in one line
even_squared_nums = filter(lambda x: x % 2 == 0,
map(lambda x: x * x, range(1, 10)))
### Sum the list of even squares
### Imperatively
sum = 0
for esn in even_squared_nums:
sum += esn
### Functionally
sum = reduce(lambda a, x: a + x, even_squared_nums)
### Functionally find the length of the list of even squares
count = reduce(lambda a, x: a + 1, even_squared_nums)
### Consider the following list of dictionaries (looks like JSON)
people = [{'name': 'Mary', 'height': 160},
{'name': 'Isla', 'height': 80},
{'name': 'Sam'}]
### What is the total height of those with heights provided
### Imperatively
total_height = 0
for person in people:
if 'height' in person:
total_height += person['height']
### Functionally
total_height = reduce(lambda a, x: a + x,
map(lambda x: x.get('height', 0), people))
# With a comprehension
total_height = sum([x.get('height', 0) for x in people])
### How would we do this if this were a list of tuples instead?
people_tuples = [('Mary', 160), ('Isla', 80), ('Sam',)]
total_height = reduce(lambda a, x: a + x,
map(lambda x: x[1] if len(x) > 1 else 0, people_tuples)) |
3e8e5685d1388e245d056d28dbffc5977e410016 | d3ming/hackerrank-solutions | /sherlock-and-watson/solution.py | 612 | 3.59375 | 4 | # https://www.hackerrank.com/challenges/sherlock-and-watson/submissions/code/17974688
nkq = input().strip().split(" ")
n = int(nkq[0]) # size of arr
k = int(nkq[1]) # num of ops
q = int(nkq[2]) # num of queries
arr = [int(i) for i in input().strip().split(" ")]
queries = []
for i in range(0, q):
queries.append(int(input().strip()))
def rotate(arr, n, k):
rotatedArr = [-1] * n
for oldIndex in range(0, n):
newIndex = (oldIndex + k % n) % n
rotatedArr[newIndex] = arr[oldIndex]
return rotatedArr
arr_rotated = rotate(arr, n, k)
for q in queries:
print(arr_rotated[q])
|
e44051a1ea99c5de4231519f95760fb30a8d59d9 | siddhant3030/depotruby | /linked_list/single_linked_list.py | 6,431 | 3.953125 | 4 | from operator import truediv
class Node:
def __init__(self, data):
self.data = data
self.next_element = None
class Solution:
def __init__(self):
self.head_node = None
def get_head(self):
return self.head_node
def is_empty(self):
if(self.head_node is None): # Check whether the head is None
return True
else:
return False
def insert_at_tail(lst, value):
# Creating a new node
new_node = Node(value)
# Check if the list is empty, if it is simply point head to new node
if lst.get_head() is None:
lst.head_node = new_node
return
# if list not empty, traverse the list to the last node
temp = lst.get_head()
while temp.next_element:
temp = temp.next_element
# Set the nextElement of the previous node to new node
temp.next_element = new_node
return
def search_value(self, value):
current_node = self.head
while current_node:
if current_node == value:
return True
current_node = current_node.next_element
return False # if value not found
def insert_at_head(self, dt):
temp_node = Node(dt)
temp_node.next_element = self.head_node
self.head_node = temp_node
return self.head_node
def delete_at_head(lst):
# Get Head and firstElement of List
first_element = lst.get_head()
# if List is not empty then link head to the
# nextElement of firstElement.
if first_element is not None:
lst.head_node = first_element.next_element
first_element.next_element = None
return
def delete_by_value(self, value):
if lst.is_empty(): # Check if list is empty -> Return False
print("List is Empty")
return deleted
current_node = lst.get_head() # Get current node
previous_node = None # Get previous node
if current_node.data is value:
lst.delete_at_head() # Use the previous function
deleted = True
return deleted
while current_node is not None:
# Node to delete is found
if value is current_node.data:
# previous node now points to next node
previous_node.next_element = current_node.next_element
current_node.next_element = None
deleted = True
break
previous_node = current_node
current_node = current_node.next_element
if deleted is False:
print(str(value) + " is not in list!")
else:
print(str(value) + " deleted!")
return deleted
def print_list(self):
if(self.is_empty()):
print("List is Empty")
return False
temp = self.head_node
while temp.next_element is not None:
print(temp.data, end=" -> ")
temp = temp.next_element
print(temp.data, "-> None")
return True
def reverse(lst):
# To reverse linked, we need to keep track of three things
previous = None # Maintain track of the previous node
current = lst.get_head() # The current node
next = None # The next node in the list
#Reversal
while current:
next = current.next_element
current.next_element = previous
previous = current
current = next
#Set the last element as the new head node
lst.head_node = previous
return lst
# Python3 program to detect loop
# in the linked list
# Node class
class Node:
# Constructor to initialize
# the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new
# node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Utility function to print it
# the linked LinkedList
def printList(self):
temp = self.head
while(temp):
print(temp.data, end=" ")
temp = temp.next
def detectLoop(self):
s = set()
temp = self.head
while (temp):
# If we have already has
# this node in hashmap it
# means their is a cycle
# (Because you we encountering
# the node second time).
if (temp in s):
return True
# If we are seeing the node for
# the first time, insert it in hash
s.add(temp)
temp = temp.next
return False
def printMiddle(self):
# Initialize two pointers, one will go one step a time (slow), another two at a time (fast)
slow = self.head
fast = self.head
# Iterate till fast's next is null (fast reaches end)
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# return the slow's data, which would be the middle element.
print("The middle element is ", slow.data)
def duplicate_value(self):
s = set()
temp = self.head
while(temp):
if (temp in s):
return True
s.add(temp)
temp = temp.next
return False
lst = Solution()
for i in range(11):
lst.insert_at_head(i)
lst.print_list()
a = lst.delete_at_head(lst)
print(a)
lst.print_list()
# class LinkedList:
# def __init__(self):
# self.head_node = None
# def get_head(self):
# return self.head_node
# def is_empty(self):
# if(self.head_node is None): # Check whether the head is None
# return True
# else:
# return False
# # Supplementary print function
# def print_list(self):
# if(self.is_empty()):
# print("List is Empty")
# return False
# temp = self.head_node
# while temp.next_element is not None:
# print(temp.data, end=" -> ")
# temp = temp.next_element
# print(temp.data, "-> None")
# return True
|
942d9e4b1306d7f795e9399e75a487492674ab17 | BerilBBJ/scraperwiki-scraper-vault | /Users/D/D/csa2.py | 5,312 | 3.5625 | 4 | import scraperwiki
from BeautifulSoup import BeautifulSoup
import re
url = "http://info.csa.com/political/classcodes.shtml"
html = scraperwiki.scrape(url)
# scrape_table function: gets passed an individual page to scrape
def scrape_table(soup):
data_table = soup.find('table',width="84%")
#print data_table
trows = data_table.findAll("tr")
for trow in trows:
#record = {}
#print trow
# Set up our data record - we'll need it later
rows = trow.findAll("td")
for row in rows:
#print row
record = {}
table_cells = row.findAll("span",{"class":"style42"})
if table_cells:
text = table_cells[0].text
record['Code'] = text[0:4]
record['Title']= text[4:]
broader= text[0:4]
table_cells = row.findAll("span",{"class":"style43"})
if table_cells:
cells=table_cells
for cell in cells:
text = table_cells[0].text
print text
subs=[]
#while (re.search("(\d){4}", text)):
# if (re.search("(\d){4}", text)):
t=re.search("((\d){4})+", text)
print t.roup(1), t.group(2), t.group(3)
#subs.append(text[:t.start()])
#print subs
#subs.append(text)
#for sub in subs:
# record['Code'] = sub[0:4]
# record['Title']= sub[4:]
#record['Code']= text[0:4]
#record['Title']= text[4:]
#broader= table_cells[0].text
#record['Broader'] = broader
#record['Code'] = cell.text
# print sp
# rows2 = row.findAll("td")
# for column in columns:
# rows = data_table.findAll("span", { "class" : "style42"} )
# for row2 in rows2:
# print row2
# if table_cells:
# record['Code'] = table_cells[0].text
# record['Code1'] = table_cells[0].text
# record['Code2'] = table_cells[1].text
#print record, '------------'
# Finally, save the record to the datastore - 'Artist' is our unique key
#scraperwiki.datastore.save(["Code"], record)
# define the order our columns are displayed in the datastore
scraperwiki.metadata.save('data_columns', ['Code','Title','Broader'])
soup = BeautifulSoup(html)
scrape_table(soup)
import scraperwiki
from BeautifulSoup import BeautifulSoup
import re
url = "http://info.csa.com/political/classcodes.shtml"
html = scraperwiki.scrape(url)
# scrape_table function: gets passed an individual page to scrape
def scrape_table(soup):
data_table = soup.find('table',width="84%")
#print data_table
trows = data_table.findAll("tr")
for trow in trows:
#record = {}
#print trow
# Set up our data record - we'll need it later
rows = trow.findAll("td")
for row in rows:
#print row
record = {}
table_cells = row.findAll("span",{"class":"style42"})
if table_cells:
text = table_cells[0].text
record['Code'] = text[0:4]
record['Title']= text[4:]
broader= text[0:4]
table_cells = row.findAll("span",{"class":"style43"})
if table_cells:
cells=table_cells
for cell in cells:
text = table_cells[0].text
print text
subs=[]
#while (re.search("(\d){4}", text)):
# if (re.search("(\d){4}", text)):
t=re.search("((\d){4})+", text)
print t.roup(1), t.group(2), t.group(3)
#subs.append(text[:t.start()])
#print subs
#subs.append(text)
#for sub in subs:
# record['Code'] = sub[0:4]
# record['Title']= sub[4:]
#record['Code']= text[0:4]
#record['Title']= text[4:]
#broader= table_cells[0].text
#record['Broader'] = broader
#record['Code'] = cell.text
# print sp
# rows2 = row.findAll("td")
# for column in columns:
# rows = data_table.findAll("span", { "class" : "style42"} )
# for row2 in rows2:
# print row2
# if table_cells:
# record['Code'] = table_cells[0].text
# record['Code1'] = table_cells[0].text
# record['Code2'] = table_cells[1].text
#print record, '------------'
# Finally, save the record to the datastore - 'Artist' is our unique key
#scraperwiki.datastore.save(["Code"], record)
# define the order our columns are displayed in the datastore
scraperwiki.metadata.save('data_columns', ['Code','Title','Broader'])
soup = BeautifulSoup(html)
scrape_table(soup)
|
c72ed2fbfe965e98459c0abee6fbbd259d730857 | fenglihanxiao/Python | /Module01_CZ/day3_loop_func/04-代码/day3/48_回文数.py | 645 | 4.125 | 4 | """
案例:回文数
要求:打印所有3位回文数
回文数:如果一个数字从左侧读和从右侧读是同一个数,则该数字即为。例如121,777
"""
# 分析
# 1. 3位回文数从100到999
# 2.回文数特征,百位数字和个位的数字相同
# 3.打印满足特征的数字
# # 求一个数字的百位数字
# x = 789
# print(x // 100)
# # 求一个数字的个位数字
# print(x % 10)
i = 100
while i <= 999 :
# 取出数字的百位和个位进行比较,如果相同就打印
a = i // 100
b = i % 10
# 判断a和b是否相同,如果相同打印
if a == b :
print(i)
i += 1
|
6b2f03fc27c5bb2fbdf5673347719e284b165463 | bradchoate/flyingcow | /flyingcow/properties.py | 991 | 3.75 | 4 | class Property(object):
"""
A way to denote a database property inside a model. Raw value of property is
stored in the instance of the Model w/ the property name prefixed with _.
"""
def __init__(self, name=None, default=None):
self.name = name
self.default = default
def __get__(self, model_instance, type):
if model_instance is None:
return self
try:
return getattr(model_instance, self._raw_value_name())
except AttributeError:
return self.default
def __set__(self, model_instance, value):
setattr(model_instance, self._raw_value_name(), value)
def _raw_value_name(self):
return '_' + self.name
def contribute_to_class(self, cls, name):
"""
We use this hook when we're building the Model class to
pass in the name of the attribute this Property is attached to.
"""
if not self.name:
self.name = name |
58cd8cc7de89aa129a4d2a0e135f653786930b9c | tdavchev/algorithms | /Trees/iterative_inorder.py | 1,307 | 3.640625 | 4 | class TreeNode():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def set_left(self, data):
self.left = data
def set_right(self, data):
self.right = data
def iterative_inorder(root):
if root == None:
return None
stack = []
while len(stack) > 0 or root != None:
if root != None:
stack.append(root)
root = root.left
continue
print(stack[-1].data)
root = stack.pop().right
def find_inorder_successor(root, node):
if root == None:
return None
stack = []
prev = False
while len(stack) != 0 or root != None:
if root != None:
stack.append(root)
root = root.left
continue
if prev:
print(stack[-1].data)
return
if stack[-1].data == node.data:
prev = True
root = stack.pop().right
root = TreeNode(100)
ele1 = TreeNode(50)
ele2 = TreeNode(25)
ele3 = TreeNode(75)
ele4 = TreeNode(200)
ele5 = TreeNode(125)
ele6 = TreeNode(350)
root.set_left(ele1)
root.set_right(ele4)
ele1.set_left(ele2)
ele1.set_right(ele3)
ele4.set_left(ele5)
ele4.set_right(ele6)
find_inorder_successor(root, ele6) |
0456a80011c10aecd39b13536c8ea8e1f71c7b7c | AngelLiang/programming-in-python3-2nd-edition | /source/ch01/average1_ans.py | 1,226 | 3.71875 | 4 | #!/usr/bin/env python3
# Copyright (c) 2008-11 Qtrac Ltd. All rights reserved.
# This program or module is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. It is provided for educational
# purposes and is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
numbers = []
total = 0
lowest = None
highest = None
while True:
try:
line = input("enter a number or Enter to finish: ")
if not line:
break
number = int(line)
numbers.append(number)
total += number
if lowest is None or lowest > number:
lowest = number
if highest is None or highest < number:
highest = number
except ValueError as err:
print(err)
print("numbers:", numbers)
print("count =", len(numbers), "sum =", total,
"lowest =", lowest, "highest =", highest,
"mean =", total / len(numbers))
|
b74a713408aefee074e4a9a91ccb1e88510edabe | Sandesh-Thapa/Assignment-II-Control-Structure | /q10.py | 1,247 | 4.34375 | 4 | # Write a function that takes camel-cased strings (i.e. ThisIsCamelCased), and converts them to snake case (i.e. this_is_camel_cased). Modify the function by adding an argument, separator, so it will also convert to the kebab case (i.e.this-is-camel-case) as well.
def convertStringCase(camel, separator):
output = ''
if separator == None:
if camel[0].isupper():
output += camel[0].lower()
for i in range(1, len(camel)):
if camel[i].isupper():
output += f'_{camel[i].lower()}'
else:
output += camel[i]
print(output)
else:
print('Enter string in camel-cased format !!')
elif separator == '-':
if camel[0].isupper():
output += camel[0].lower()
for i in range(1, len(camel)):
if camel[i].isupper():
output += f'{separator}{camel[i].lower()}'
else:
output += camel[i]
print(output)
else:
print('Enter string in camel-case format !!')
string = input("Enter string in camel-case format: ")
convertStringCase(string, None)
convertStringCase(string, '-') |
1a1d50cc7ec8ddcd43ae681bd83eafe35b6b8480 | Jigar710/Python_Programs | /magic_method/var1.py | 189 | 3.546875 | 4 | class Emp:
def __init__(self):
self.var1 = "value1"
self._var2 = "value2"
self.__var3 = "value3"
e1 = Emp()
print(e1.__dict__)
print(e1.var1)
print(e1._var2)
print(e1._Emp__var3) |
ab7ac9f721ee6a9f7bea1fc512cbd7d5c7dc037e | Muscularbeaver301/WebdevelopmentSmartNinja201703 | /Kursprojekte/Kursprogramm/Class10-Lottogenerator-Hauptstadtspiel/lottozahlen.py | 423 | 3.9375 | 4 | """Lottozahlen"""
import random
def lottozahlengenerator(zahlen):
Lottozahlenlist = []
zahlen = min([zahlen,49])
zahlen = zahlen if zahlen <= 49 else 49
while len(Lottozahlenlist) < zahlen:
zahl = random.randint(1, 49)
if zahl not in Lottozahlenlist:
Lottozahlenlist.append(zahl)
return Lottozahlenlist
if __name__ == '__main__':
print sorted(lottozahlengenerator(-1))
|
c1337ac1ecf3f799734ca77be17b89138568845b | Jansten/Training | /Python/LinuxAcademy/Python 3 For System Administrators/03 - Strings/hello.py | 1,063 | 4.5625 | 5 | #!/usr/bin/env python3.6
# This is a program that prints "Hello World!"
print("Hello World!")
# These are some string examples
"pass" + "word"
# Will print out "password"
"Ha" * 4
# Will print out "HaHaHaHa"
"double".find('s')
# Reutnrs "-1", which means it wasn't found
>>> "double".find('u')
# Returns "2"
>>> "double".find('bl')
# Returns "4"
# Lower converts all of the characters in a string to their lowercase versions (if they have one). This function returns a new string without changing the original, and this becomes important later:
"TeStInG".lower()
# 'testing'
>>> "another".lower()
# 'another'
>>> "PassWord123".lower()
# 'password123'
# Lastly, if we need to use quotes or special characters in a string we can do that using the '’' character:
>>> print("Tab\tDelimited")
# Tab Delimited
>>> print("New\nLine")
# New
# Line
>>> print("Slash\\Character")
# Slash\Character
>>> print("'Single' in Double")
# 'Single' in Double
>>> print('"Double" in Single')
# "Double" in Single
>>> print("\"Double\" in Double")
# "Double" in Double |
37e5f6ebc022fccc7c04156f88d1a577023eafbe | leighMichaelForrest/problems | /payroll/payroll.py | 806 | 4.03125 | 4 | import sys
OVERTIME_FACTOR = 1.5
def payroll(wage, hours):
"""Determine the gross pay. Hours over 40 pay time and a half plus 40 hours
regular time.
wage: The hourly wage of employee.
hours: The number of hours worked."""
try:
wage = float(wage); hours = float(hours)
regular = 0; overtime = 0
if hours <= 40:
regular = hours
else:
regular = 40
overtime = hours - 40
except ValueError:
print("ValueError")
wage = 0; hours = 0
return (regular * wage) + (overtime * wage * OVERTIME_FACTOR)\
if __name__ == '__main__':
wage, hours = float(sys.argv[1]), float(sys.argv[2])
print(f"The gross pay of ${'%5.2f' % wage} and {'%5.2f' % hours} hours is ${'%5.2f' % payroll(wage, hours)}")
|
bebf69bfbd74b543b94a2c15f8a6e7eea4b62946 | Paalar/TDT4110 | /Øving 9/genomdic.py | 629 | 3.890625 | 4 | my_family = {}
def add_family_member(role, name):
for i in my_family:
if i == role:
my_family[role].append(name)
return my_family
my_family[role] = []
my_family[role].append(name)
return my_family
print("Når du er ferdig med å legge til navn, skriv ferdig.")
while True:
navn = input("Hva er navnet til familie medlemmet?\n")
if navn.lower() == "ferdig":
print(my_family)
break
rolle = input("Hva er rollen til dette familie medlemmet?\n")
if rolle.lower() == "ferdig":
print(my_family)
break
add_family_member(rolle, navn)
|
2593aeaf239015183c48861a96af3d1feb21d6d3 | Laurensvaldez/PythonCrashCourse | /CH9: Classes/9-5_login_attempts.py | 2,622 | 4.46875 | 4 | # Add an attribute called login_attempts to your User class from Exercise 9-3
class User:
"""A class to describe a user"""
# Create two attributes called first_name and last_name
# and then create several other attributes that are typically stored in a user profile
def __init__(self, first_name, last_name, age, birthplace, relationship_status):
"""Initialize the first name and last name"""
self.first_name = first_name.title()
self.last_name = last_name.title()
self.age = age
self.birthplace = birthplace.title()
self.relationship_status = relationship_status
self.login_attempts = 0
def describe_user(self):
"""This method prints a summary of the user"""
msg_1 = "The user's first name is " + self.first_name + " and his/her last name is " + \
self.last_name
msg_2 = self.first_name + " " + self.last_name + " age is " + str(self.age) + \
" and lives in " + self.birthplace + "."
msg_3 = self.first_name + " " + self.last_name + " is currently " + self.relationship_status + \
"."
print("\n" + msg_1)
print(msg_2)
print(msg_3)
def greet_user(self):
"""This method provides a personalized greeting to the user."""
# print a personalized greeting to the user
greeting = "Hello " + self.first_name + ", I hope you have a wonderful day!"
print(greeting)
def increment_login_attempts(self):
"""Increment the value of login by 1."""
self.login_attempts += 1
# Write another method called reset_login_attempts() that resets the value of login_attempts to 0
def reset_login_attempts(self):
self.login_attempts = 0
# Make an instance of the User class and call increment_login_attempts() several times, and call reset_login_attempts()
laurens = User("Laurens", "Salcedo Valdez", 29, "Rotterdam", "in a relationship")
laurens.describe_user()
laurens.greet_user()
laurens.increment_login_attempts()
print("Login attempts are: " + str(laurens.login_attempts))
laurens.increment_login_attempts()
print("Login attempts are: " + str(laurens.login_attempts))
laurens.increment_login_attempts()
print("Login attempts are: " + str(laurens.login_attempts))
laurens.increment_login_attempts()
print("Login attempts are: " + str(laurens.login_attempts))
laurens.reset_login_attempts()
print("Login attempts are reset to: " + str(laurens.login_attempts))
# Print login_attempts again to make sure it was reset to 0
print("Login attempts are reset to: " + str(laurens.login_attempts))
|
211d6d5dfb2401d0ef5ac3fce1b5eb2a0514935f | GeorgiyDemo/FA | /Course_II/ПП/part1/pract2/task1.py | 2,530 | 3.84375 | 4 | """
Практика 2 Суперэллипс
Деменчук Георгий ПИ19-4
"""
import tkinter as tk
from math import sin, cos, pi
# Начальные позиции
width = 600
height = 600
root = tk.Tk()
# Основной канвас
c = tk.Canvas(root, width=width, heigh=height)
# Текущие точки, которые отрисованы
points_list = []
def drawer(canvas, x, y, a, b):
"""Создание точки"""
# Смещение, чтоб относительно центра
x = a + x
y = b + y
x1, y1 = (x - 1), (y - 1)
x2, y2 = (x + 1), (y + 1)
point = canvas.create_oval(x1, y1, x2, y2, fill="white", outline="white")
# Добавляем точку в список точек
points_list.append(point)
def sign(x):
"""Отдача знака для processing"""
return ((x > 0) - (x < 0)) * 1
def processing(canvas, n):
"""Метод отрисовки суперэллипса"""
a, b = width // 2, height // 2
na = 2 / n
# шаг отрисовки точек-овалов. если лагает - исправить на меньший коэфф
step = 1000
piece = (pi * 2) / step
xp = []
yp = []
t = 0
for _ in range(step + 1):
# т.к sin ^ n(x) математически это то же самое, что (sin(x))^n...
x = (abs((cos(t))) ** na) * a * sign(cos(t))
y = (abs((sin(t))) ** na) * b * sign(sin(t))
xp.append(x)
yp.append(y)
t += piece
if len(xp) == len(yp):
for i in range(len(xp)):
drawer(canvas, xp[i], yp[i], a, b)
else:
raise ValueError("Точки x и y не совпадают")
def scale_processing(number):
"""Обработка ползунка"""
# Удаляем предыдущие точки, если они есть
if len(points_list) != 0:
for point in points_list:
c.delete(point)
# Отрисовываем эллипс
processing(c, float(number))
def main():
root.title("Суперэллипс")
# Распаковка канваса
c.configure(bg="black")
c.pack(fill=tk.BOTH, expand=1)
# Распаковка ползунка
scale = tk.Scale(
root,
from_=0.01,
to=3.75,
digits=3,
resolution=0.01,
command=scale_processing,
orient=tk.HORIZONTAL,
)
scale.pack(side=tk.LEFT, padx=5)
root.mainloop()
if __name__ == "__main__":
main()
|
70e0da8f49445c528f53960aa4c9d6a593218b87 | tenhobi/BI-PYT | /homeworks/02-random-walk/__main__.py | 1,049 | 3.53125 | 4 | #!/usr/bin/env python3
from random import randint
import os
from time import sleep
# clear window
print('\033[2J')
# get dimension and center
cols, rows = os.get_terminal_size()
x = cols // 2
y = rows // 2
print(f'\033[{y};{x}H', end='', flush=True)
# initialize data
matrix = [[0] * (cols + 1) for i in range(rows + 1)]
directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
while True:
direction = randint(0, 7)
# cycle through steps in the direction
for _ in range(0, randint(1, 5)):
x += directions[direction][0]
y += directions[direction][1]
# change visual level of current cell
if matrix[y][x] < 7:
matrix[y][x] += 1
# draw visual level of current cell
print(f'\033[{y};{x}H\033[4{matrix[y][x]}m \033[0m', end='', flush=True)
sleep(0.02)
if not ((1 < y < rows) and (1 < x < cols)):
break
if not ((1 < y < rows) and (1 < x < cols)):
break
print(f'\033[0m\033[{rows};0H', end='', flush=True)
|
23f2c01dd3ae65b9b1f2d4bfb05515cc45f6fedb | conglb/Hackerank-practice | /reverse-a-linked-list.py | 439 | 3.921875 | 4 | # Complete the reverse function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def reverse(head):
""" Return head of link list reversed """
if head == None:
return None
before = None
cur = head
while True:
newCur = cur.next
cur.next = before
before = cur
cur = newCur
if cur == None:
return before |
b54ed9a030b6bfc9e2c9f3b4ba3ecd9fa7e70e68 | Jocelyn9090/CS1301xiiii | /AlignRight.py | 1,671 | 4.75 | 5 | #-----------------------------------------------------------
#Write a function called align_right. align_right should
#take two parameters: a string (a_string) and an integer
#(string_length), in that order.
#
#The function should return the same string with spaces
#added to the left so that the text is "right aligned" in a
#string. The number of spaces added should make the total
#string length equal string_length.
#
#For example: align_right("CS1301", 10) would return the
#string " CS1301". Four spaces are added to the left so
#"CS1301" is right-aligned and the total string length is
#10.
#
#HINT: Remember, len(a_string) will give you the number of
#characters currently in a_string.
#Add your function here!
def align_right(a_string,string_length):
space = " "
result = len(a_string)*space + a_string
return result
#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print: " CS1301"
print(align_right("CS1301", 10))
sample answer
#First, we define the function with the given parameters:
def align_right(a_string, string_length):
#Next, we need to figure out how many spaces we need to
#add. We want the total length to be string_length, and
#the current length is the length of a_string. So, our
#number of spaces to add is the differences:
num_spaces = string_length - len(a_string)
#So, we return that many spaces, plus the original
#string:
return " " * num_spaces + a_string
print(align_right("CS1301", 10))
|
4efadde2b15d71ce730050414d235c477270fd90 | dbdennot8/bc-18-project | /test_cases.py | 3,608 | 3.828125 | 4 | import unittest
from dojo import DojoRoomAllocator
class TestsForDojoClassMethods(unittest.TestCase):
def setUp(self):
"""sets up an instance of the class Dojo, for use in the tests below"""
self.demo = DojoRoomAllocator()
def test_can_create_office_and_append_to_appropriate_lists(self):
"""Test whether create_room method can create an office and append as required"""
self.demo.create_room("office", "NinjaSpace")
self.assertEqual(len(self.demo.all_offices), 1)
def test_can_create_living_spaces_and_append_to_appropriate_list(self):
"""Test whether create_room method can create a living space and append as required"""
self.demo.create_room("livingspace", "NinjaSpace")
self.assertEqual(len(self.demo.all_living_spaces), 1)
def test_create_room_takes_only_office_or_living_space_for_room_type(self):
"""Tests that method returns error if room type is not either office, or living space"""
self.demo.create_room("kitchen", "ya_kwanza")
self.assertNotEqual(len(self.demo.all_living_spaces), 1)
self.assertNotEqual(len(self.demo.all_offices), 1)
def test_create_room_increases_count_of_number_of_rooms(self):
"""Checks that calling the create_room method adds to number of rooms available"""
initial_room_count = len(self.demo.all_offices)
self.demo.create_room("office", "ya_kwanza")
new_room_count = len(self.demo.all_offices)
self.assertEqual((new_room_count - initial_room_count), 1)
def test_create_room_does_not_duplicate_room_names_offices(self):
"""Checks that multiple offices are not created having the same name"""
initial_room_count = len(self.demo.all_office_names)
self.demo.create_room("office", "ya_kwanza")
self.demo.create_room("office", "ya_kwanza")
new_room_count = len(self.demo.all_office_names)
self.assertNotEqual((new_room_count - initial_room_count), 2)
def test_create_room_does_not_duplicate_room_names_living_spaces(self):
"""Checks that multiple living spaces are not created having the same name"""
initial_room_count = len(self.demo.all_living_space_names)
self.demo.create_room("livingspace", "ya_kwanza")
self.demo.create_room("livingspace", "ya_kwanza")
new_room_count = len(self.demo.all_living_space_names)
self.assertNotEqual((new_room_count - initial_room_count), 2)
def test_add_person_person_type_only_if_specified_as_either_fellow_or_staff(self):
"""Checks that person_type is specified as either fellow or staff"""
self.demo.add_person("Kenyan", "Denno", "UleMsee", "Yes")
self.assertNotEqual(len(self.fellows), 1)
self.assertNotEqual(len(self.staff), 1)
def test_add_person_appends_new_person_to_appropriate_list_fellows(self):
"""Check whether fellow is appended to list of fellows"""
initial_fellows_count = len(self.demo.fellows)
self.demo.add_person("fellow", "UleMsee", "Denno", "Yes")
new_fellows_count = len(self.demo.fellows)
self.assertEqual((new_fellows_count - initial_fellows_count), 1)
def test_add_person_appends_new_person_to_appropriate_list_staff(self):
"""Check whether staff is appended to list of staff"""
initial_staff_count = len(self.demo.staff)
self.demo.add_person("staff", "Ann", "Dela", "N")
new_staff_count = len(self.demo.staff)
self.assertEqual((new_staff_count - initial_staff_count), 1)
if __name__ == "__main__":
unittest.main()
|
7e1e855ca3bc8d5d6a9609374fc250a70271cdaf | jsinoimeri/Gr11-Python | /Task 4/image_functions.py | 13,836 | 3.90625 | 4 | from ics_image_fast import *
from random import *
from math import *
def inverse(file_name):
'''
Takes the picture user inputs and inverses it by substracting each rgb value
from 255. For ex: red is 55, the inverse of that is 255-55 = 200
'''
load_image(file_name) #loads the image
for row in range(get_height()):
for col in range(get_width()):
pix = get_pixel(col, row)
pix[0] = 255 - pix[0] # this inverses the red value by subracting the red value from 255
pix[1] = 255 - pix[1] # this inverses the green value by subracting the green value from 255
pix[2] = 255 - pix[2] # this inverses the blue value by subracting the blue value from 255
set_pixel(col, row, pix)
save_image("inverse.bmp")
return
def flipped(file_name, flip_horizontal):
'''
Takes the picture user inputs it and flips it horizontal or vertical according
to the user. It gets two pixels from the first half and second half of the image
and swaps them around.
'''
load_image(file_name)
width = get_width()
height = get_height()
#flips it vertically
if flip_horizontal == False:
for col in range(width/2):
for row in range(height):
pix = get_pixel(col, row) # gets pixels in first half of picture
temp = pix # stores pixel in temp
pix = get_pixel(width-1-col, row) # gets pixels in second half of picture
set_pixel(col, row, pix) # sets pixels of second half to first half of picture
set_pixel(width-1-col, row, temp) # sets pixels of fist half to second half of picture
# flips it horizontally
elif flip_horizontal == True:
for col in range(width):
for row in range(height/2):
pix = get_pixel(col, row)
temp = pix
pix = get_pixel(col, height-1-row)
set_pixel(col, row, pix)
set_pixel(col, height-1-row, temp)
save_image("flipped.bmp")
return
def mirrored(file_name, horizontal):
'''
Exactly like flipped except instead of swapping, it replaces the pixel with
the same pixel but on the other half of the image. It mirrors horizontal and
vertical according to the user.
'''
load_image(file_name)
# mirrors the image vertically
if horizontal == False:
for col in range(get_width()/2):
for row in range(get_height()):
pix = get_pixel(col, row) # gets pixels in first half of picture
set_pixel(get_width()-1-col, row, pix) # sets pixels of fist half to second half of the picture
# mirrors the image horizontally
elif horizontal == True:
for col in range(get_width()):
for row in range(get_height()/2):
pix = get_pixel(col, row)
set_pixel(col, get_height()-1-row, pix)
save_image("mirored.bmp")
return
def greyscale(file_name):
'''
Takes an image, gets a pixel one at a time, adds the rgb values and divides
by 3. Sets the pixel at the same place but with the average as the rgb value.
'''
load_image(file_name)
for row in range(get_height()):
for col in range(get_width()):
pix = get_pixel(col, row)
avg = (pix[0]+ pix[1]+pix[2])/ 3 #finds the average pixel num
pix[0] = avg # replaces the red value with average num
pix[1] = avg # replaces the green value with average num
pix[2] = avg # replaces the blue value with average num
set_pixel(col, row, pix)
save_image("greyscale.bmp")
return
def blended(file_name, file_name2):
'''
Takes two images. Gets a pixel from the two images, adds the two rgb values
together and divides by two. Sets the new rgb value at that position in the
first image.
'''
load_more_images(file_name)
load_more_images(file_name2)
width1 = get_width(1)
height1 = get_height(1)
width2 = get_width(2)
height2 = get_height(2)
if width1 == width2 and height1 == height2: # makes sure that the two images are the same size
for col in range(width1):
for row in range(height1):
pix = get_pixel(col, row, 1) # gets pixels of first image
pix2 = get_pixel(col, row, 2) # gets pixels of second image
pix[0] = (pix[0]+pix2[0])/2 # adds the two red values and finds the average
pix[1] = (pix[1]+pix2[1])/2 # adds the two green values and finds the average
pix[2] = (pix[2]+pix2[2])/2 # adds the two blue values and finds the average
set_pixel(col, row, pix, 1) # sets the new pixels to the first image
save_image("blended.bmp", 1)
else:
print "The images are different sizes"
return
blended(r"C:\Users\Jeton\Pictures\Soccer\german flag.jpg", r"C:\Users\Jeton\Pictures\Cars\mercedes_slr.jpg" )
def message(message, width, height, font, num_times):
'''
Makes a new image, with the width and height provided. Each letter inside of
the message is add by randomly gernerated positons (x,y) and colours. The size
is 1/4 of the height and the font is inputed by the user, as well as the number
of times the message should appear in the image.
'''
new_image(width, height)
fonts = get_fonts() # gets all the fonts on computer
if fonts.__contains__(font): # makes sure the font user input is a valid font
font = font
else:
font = fonts[randint(0, len(fonts))] # if not randomly generates a font to use
size = height/4
for num in range(num_times):
for letter in message:
message_x = randint(0, width-size) # random position of letter on x-axis
message_y = randint(0, height-size) # random position of letter on y-axis
r_pix = randint(0, 255) # randomly generated red value
g_pix = randint(0, 255) # randomly generated green value
b_pix = randint(0, 255) # randomly generated blue value
add_text(letter, message_x, message_y, [r_pix, g_pix, b_pix], font, size)
save_image("message.bmp")
return
def random_walk(width, height, start_x, start_y):
'''
This function makes a new image with width and height provided by user. Places
a 9 by 9 green square at the starting x and y positions. Randomly generates
a number between 1 and 4, and adds or substracts 1 from the starting x and y
positions. Sets a black pixel at that newly calculated posion in the image.
It will only stop if the pixels touch one of the borders.
'''
new_image(width, height)
total_distance = 0
east_west = 0
north_south = 0
while start_x+north_south >= 0 and start_x+north_south < width-1 and start_y+east_west >= 0 and start_y+east_west < height-1:
random_num = randrange(1,5)
if random_num == 1:
east_west += 1 # adds 1 if moving east
elif random_num == 2:
east_west -= 1 # substracts 1 if moving west
elif random_num == 3:
north_south += 1 # adds 1 if moving north
elif random_num == 4:
north_south -= 1 # substracts 1 if moving south
total_distance += 1
if start_x+north_south > 0 and start_x+north_south < width-1 and start_y+east_west > 0 and start_y+east_west < height-1: # makes sure the the pixel is not at border
set_pixel(start_x+north_south, start_y+east_west, [0,0,0])
for col in range(10):
for row in range(10):
if start_x+col-4 > 0 and start_y+row-4 >0 and start_x+col-4 < width-1 and start_y+row-4 < height-1: # puts a 9*9 square on the start point
set_pixel(start_x+col-4, start_y+row-4, [0,255,0]) # makes the start-point the center of the square
save_image("radom_walk.bmp")
return total_distance
def gradient(width, height, starting_colour, ending_colour, vertical_horizontal):
'''
A colour transition between two colours that user inputs. The transition will
occur horizontal or vertical according to the user input.
'''
new_image(width, height)
r_grad = (ending_colour[0] - starting_colour[0])/(width*1.0) # finds how much red value should increase
g_grad = (ending_colour[1] - starting_colour[1])/(width*1.0) # finds how much green value should increase
b_grad = (ending_colour[2] - starting_colour[2])/(width*1.0) # finds how much blue value should increase
# vertical
if vertical_horizontal == False:
for col in range(width):
for row in range(height):
# sets the pixel at col, row with the newly calculated rgb value
set_pixel(col, row, [int(starting_colour[0]+r_grad*col), int(starting_colour[1]+g_grad*col), int(starting_colour[2]+b_grad*col)])
# horizontal
elif vertical_horizontal == True:
for row in range(height):
for col in range(width):
set_pixel(row, col, [int(starting_colour[0]+r_grad*col), int(starting_colour[1]+g_grad*col), int(starting_colour[2]+b_grad*col)])
save_image("gradient.bmp")
return
# my own functions
# new image functions
def random_pixels(width, height):
'''
Makes a new image with width and height provided by user. Randomly generates
the rgb values and puts them inside the image, covering the image with multi
coloured pixels.
'''
new_image(width, height)
for col in range(width):
for row in range(height):
set_pixel(col, row, [randint(0, 255), randint(0, 255), randint(0, 255)]) # set pixels at col, row with randomly generated rgb values
save_image("random_pixels.bmp")
return
def sorted_pixels(file_name, width, height):
'''
Loads an image, gets all the pixels from the image and sorts them. Makes a
new image according to user input and sets the sorted pixels in the new image.
The image created is a type of water fall with different colours.
'''
load_more_images(file_name)
w = get_width(1)
h = get_height(1)
load_more_images([[width, height]])
if w == width and h == height:
pixels = []
for col in range(w):
for row in range(h):
pixels += [get_pixel(col, row, 1)] # gets all pixels from first image
pixels.sort()
pos = 0
for col in range(w):
for row in range(h):
set_pixel(col, row, pixels[pos], 2) # sets all pixels after sorting
if pos < len(pixels)-1:
pos +=1
save_image("sorted_pixels.bmp", 2)
else:
print "The two images have to be the same height and width"
return
#image modifiers
def pattern(file_name):
'''
Loads an image. Creates a new image with the max width and height of the loaded
image. Converts the coordinates of the pixels in the loaded image to cartesian
plane coordinates, rotates it 60 degrees and converts the new coordinates to
coordinates for an image. Sets the pixel in the new image with the newly
calculated coordinates. User will notice the new image with a pattern of white
pixels on it.
'''
load_more_images(file_name)
w = get_width(1)
h = get_height(1)
angle = radians(60)
new_width = hypot(w,h)
new_height = hypot(w,h)
load_more_images([[new_width, new_height]])
for col in range(w):
for row in range(h):
c1 = col-w/2 # converts col,row to cartesian plane coordinates
r1 = -row+h/2
c2 = c1*cos(angle)-r1*sin(angle) # rotates the image
r2 = c1*sin(angle)+r1*cos(angle)
col2 = int(c2+new_width/2) # finds the new image coordinates
row2 = int(-r2+new_height/2)
pix = get_pixel(col, row,1)
set_pixel(col2, row2, pix,2)
save_image("Patterns.bmp", 2)
return
def rotation(file_name, angle):
'''
Loads an image. Creates a new image with the max width and height of the loaded
image. Converts the coordinates of the pixels in the loaded image to cartesian
plane coordinates, rotates it x-amount of degree and converts the new coordinates
to coordinates for an image. Sets the pixel in the new image with the newly
calculated coordinates. User will notice the new image rotated that many
degrees as he/she inputed.
'''
load_more_images(file_name)
w = get_width(1)
h = get_height(1)
angle = radians(angle)
new_width = int(hypot(w,h))
new_height = int(hypot(w,h))
load_more_images([[new_width, new_height]])
angle = -angle # rotates it backwards
for col in range(new_width):
for row in range(new_height):
c1=col-new_width/2 # converts col,row to cartesian plane coordinates
r1=-row+new_height/2
c2=c1*cos(angle)-r1*sin(angle) # rotates the image
r2=c1*sin(angle)+r1*cos(angle)
col2=int(c2+w/2) # finds the new image coordinates
row2=int(-r2+h/2)
if col2 >= 0 and col2 < w and row2 >= 0 and row2 < h:
pix = get_pixel(col2, row2,1)
set_pixel(col, row, pix,2)
save_image("rotation.bmp", 2)
return
|
3f94f29adfd7d61aec077dd6664a5643bf5b4531 | Bl4ky113/clasesHaiko2021 | /camaraMultas.py | 2,592 | 4 | 4 | '''
Codigo de Cámara Multas
Debe hacer:
- Ingresar varios carros:
- Distancia entre ambas cámaras
- Velocidad maxima de la calle
- El tiempo que se demoro el auto en pasar de una a otra cámara
- Placa del Carro
- Determinar cuales de estos se merecen multa, curso & ok
'''
from lineasBonitas import lineasBonitas as LB
''' Clase Carros '''
class infoCarros:
def __init__ (self, tiempoRecorrido, placa):
self.tiempoRecorrido = tiempoRecorrido
self.placa = placa
def info (self):
return [self.tiempoRecorrido, self.placa]
''' Intput de Datos '''
def verificarNumLogico(mensaje):
while True:
var = input(mensaje)
try:
var = float(var)
except ValueError:
print(var, "No es una Distancia, velocidad o tiempo lógico")
else:
if var > 0:
return var
else:
return "ERROR"
distanciaCamaras = verificarNumLogico("Distancia entre Cámaras (m): ") # (m) Metros
velocidadMax = verificarNumLogico("Velocidad Máxima (km/h): ") # (km/h) KiloMetros / Hora
condicionalError = distanciaCamaras == "ERROR" or velocidadMax == "ERROR"
arrCarros = []
distanciasCarros = []
placasCarros = []
cantidadCarros = 3
for i in range(cantidadCarros):
print(LB(100))
print("Carro N°" + str(i + 1))
arrCarros.append(infoCarros(
tiempoRecorrido = verificarNumLogico("Tiempo en Recorrer Distancia (seg): "),
placa = input("Placa del Carro: ").upper()
))
distanciasCarros.append(arrCarros[i].info()[0])
placasCarros.append(arrCarros[i].info()[1])
if condicionalError:
print("ERROR")
else:
def convertirVelocidad (valor):
valor = (valor * 1000) / 3600
return valor
carrosMultados = []
carrosCursos = []
carrosOk = []
velocidadMax = convertirVelocidad(velocidadMax)
print(velocidadMax)
print(velocidadMax * 1.2)
for i in range(cantidadCarros):
velocidadAuto = distanciaCamaras / arrCarros[i].info()[0]
print(str(distanciaCamaras), " / " , str(arrCarros[i].info()[0]))
print(velocidadAuto)
if velocidadAuto >= (velocidadMax * 1.2):
carrosMultados.append(arrCarros[i].info()[1])
elif velocidadAuto < (velocidadMax * 1.2) and velocidadAuto > velocidadMax:
carrosCursos.append(arrCarros[i].info()[1])
elif velocidadAuto <= velocidadMax:
carrosOk.append(arrCarros[i].info()[1])
''' Output de Datos '''
print(LB(100) + "\n")
print("Carros con Multas: ", str(carrosMultados))
print("Carros que deben ir a Cursos de Sensibilación: ", str(carrosCursos))
print("Carros ok: ", str(carrosOk))
print("\n" + LB(100)) |
a49b03671632b5b99f099d0be8e39c969c4a0398 | innovatorved/python-recall | /py45-ObjectInclapsuation-check-any-object-type.py | 771 | 3.671875 | 4 | # What is Object Introspection ?
# find information about any Object
class nump:
def __init__(self , start , end):
self.start = start
self.end = end
@property
def full(self):
return f"{self.start} {self.end}"
@full.setter
def full(self , startend):
start = startend[0:3]
end = startend[3:]
self.start = start
self.end = end
@full.deleter
def full(self):
self.start = None
self.end = None
print("Delete Done")
# nump is a Class
ab = nump(2,3)
print(type(ab))
print(id(ab)) # give id of any object or anything savee in memory
# and id is alwways unique
print(dir(ab)) # return all directory information
|
cbb846583a576fcd44b702e32f4d7d066b9db98c | DariaKnyazeva/project_euler | /problems/p058.py | 1,542 | 4.25 | 4 | # SPIRAL PRIMES
"""
Starting with 1 and spiralling anticlockwise in the following way,
a square spiral with side length 7 is formed.
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49 50
It is interesting to note that the odd squares lie along the bottom
right diagonal, but what is more interesting is that 8 out of the 13
numbers lying along both diagonals are prime; that is,
a ratio of 8/13 ≈ 62%.
If one complete new layer is wrapped around the spiral above,
a square spiral with side length 9 will be formed. If this process
is continued, what is the side length of the square spiral for which
the ratio of primes along both diagonals first falls below 10%?
"""
from utils.prime_numbers import is_prime
def _additional(diagonal: int, square_side: int):
result = []
for add in range(square_side - 1, square_side, 2):
for i in range(4):
diagonal += add
result.append(diagonal)
return result
if __name__ == "__main__":
print(__doc__)
print('*' * 65)
diagonal = 49
square_side = 9
total_count = 13
prime_count = 8
while True:
result = _additional(diagonal, square_side)
diagonal = result[-1]
total_count += 4
prime_count += len([x for x in result if is_prime(x)])
percentage = prime_count / total_count
print(f"{square_side}: {percentage}")
square_side += 2
if percentage < 0.1:
break
|
3197ff7d892b0d81f45522de61ea2e58c51069b9 | fvgm-spec/python_repo | /convert_seconds.py | 186 | 3.734375 | 4 | def convert_seconds(seconds):
hours=seconds//3600
minutes=(seconds-hours*3600)//60
remaining_seconds=seconds-hours*3600-minutes*60
return hours,minutes,remaining_seconds
|
3f423794a202d378c065fc3e0e24c7f14bb04ab8 | moemaair/Problems | /strings/python/first_unique_char.py | 1,597 | 3.75 | 4 | """
[FindFirstUniqueChar]
Return the first non-repeated character in a string.
If not found, return null. Assume the string is NOT sorted.
"""
#Cases
"""
1) Empty or None
2) No repeats
3) Single repeat
4) Multiple repeats (return first found?)
5) 1,2,3 length strings
"""
#Approaches
"""
1) Sort string O(n log n), then loop O(n) and check if str1[i] == str1[i+1] (Won't work for first unique)
2) HashMap to store unique chars. Loop O(n) check if in HashMap, if not, store.
3) Naive Double Loop O(n^2), For each, for each, see if another exists. Return first found.
4) Can we do linear time?
"""
def get_first_unique_char_loops(str1):
i = 0
while i < len(str1):
j = i+1
while j < len(str1):
if str1[i] == str1[j]:
return str1[i]
j+=1
i+=1
return None
def get_first_unique_char_dict(str1):
chars = {}
for s in str1:
if chars.get(s) != None:
return s
chars[s] = s
return None
#Tests
def test_get_first_unique_char_loops():
assert get_first_unique_char_loops("ABCBD") == "B"
assert get_first_unique_char_loops("") == None
assert get_first_unique_char_loops("A") == None
assert get_first_unique_char_loops("AB") == None
assert get_first_unique_char_loops("ABCC") == "C"
def test_get_first_unique_char_dict():
assert get_first_unique_char_dict("ABCBD") == "B"
assert get_first_unique_char_dict("") == None
assert get_first_unique_char_dict("A") == None
assert get_first_unique_char_dict("AB") == None
assert get_first_unique_char_dict("ABCC") == "C"
if __name__ == "__main__":
test_get_first_unique_char_loops()
test_get_first_unique_char_dict()
|
57c1dc1452b209af72ec0a7aad7fbbcc8dab5189 | moxwel/utfsm-smoj | /Certamen2/Nuevo/cifradoCesar.py | 1,186 | 3.8125 | 4 | entrada = input()
mover = int(input())
mover = mover % 26 #
s = []
for x in entrada:
s.append(ord(x))
# print(s)
strin = ""
for x in s:
# ASCII, ASCII movido, Es mayuscula?
# print(x, x+mover, (x >= 65 and x <= 90))
if (x >= 97 and x <= 122): # Si la letra es minuscula
# ASCII movido, se pasa del limite de las letras?
# print(x+mover, x+mover > 122)
if (x + mover > 122): # Si se pasa de los ASCII de letras
# print(chr(x + mover - 26))
strin += chr(x + mover - 26) # Agregar letra al string
else:
# print(chr(x+mover))
strin += chr(x+mover)
elif (x >= 65 and x <= 90): # Si la letra es mayuscula
# ASCII movido, se pasa del limite de las letras?
# print(x+mover, x+mover > 90)
if (x + mover > 90): # Si se pasa de los ASCII de letras
# print(chr(x + mover - 26))
strin += chr(x + mover - 26)
else:
# print(chr(x+mover))
strin += chr(x+mover)
else: # Si es otro simbolo que no sea una letra
strin += chr(x) # Agreega el simbolo sin modificar
print(strin)
|
4a1e8e95cc56d569b3a413c35507e55e61cfafd1 | qmnguyenw/python_py4e | /geeksforgeeks/python/medium/22_6.py | 6,141 | 4.53125 | 5 | Applying Convolutional Neural Network on mnist dataset
**CNN** is basically a model known to be **Convolutional Neural Network** and
in the recent time it has gained a lot of popularity because of it’s
usefullness. CNN uses multilayer perceptrons to do computational works. CNNs
use relatively little pre-processing compared to other image classification
algorithms. This means the network learns through filters that in traditional
algorithms were hand-engineered. So, for image processing task CNNs are the
best-suited option.
**MNIST dataset:**
mnist dataset is a dataset of handwritten images as shown below in image.

We can get 99.06% accuracy by using CNN(Convolutionary neural Network) with
functional model. The reason of using functional model is maintaining easiness
while connecting the layers.
* #### Firstly, include all necessary libraries
__
__
__
__
__
__
__
import numpy as np
import keras
from keras.datasets import mnist
from keras.models import Model
from keras.layers import Dense, Input
from keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten
from keras import backend as k
---
__
__
* #### Create the train data and test data
**Test data:** Used for testing the model that how are model has been
trained.
**Train data:** Used to train our model.
__
__
__
__
__
__
__
(x_train, y_train), (x_test, y_test)= mnist.load_data()
---
__
__
While proceeding further, **img_rows** and **img_cols** are used as the image
dimensions. In mnist dataset, it is 28 and 28. We also need to check the data
format i.e. ‘channels_first’ or ‘channels_last’. In CNN, we can normalize data
before hands such that large terms of the calculations can be reduced to
smaller terms. Like, we can normalize the x_train and x_test data by dividing
it with 255.
**Checking data-format:**
__
__
__
__
__
__
__
img_rows, img_cols=28, 28
if k.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows,
img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows,
img_cols)
inpx = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols,
1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols,
1)
inpx = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
---
__
__
* #### Description of the output classes:
Since output of the model can comprise of any of the digits between 0 to 9.so,
we need 10 classes in output. To make output for 10 classes, use
keras.utils.to_categorical function, which will provide with the 10 columns.
Out of these 10 columns only one value will be one and rest 9 will be zero and
this one value of the output will denote the class of the digit.
__
__
__
__
__
__
__
y_train= keras.utils.to_categorical(y_train)
y_test = keras.utils.to_categorical(y_test)
---
__
__
Now, dataset is ready so let’s move towards the cnn model :
__
__
__
__
__
__
__
inpx= Input(shape=inpx)
layer1 = Conv2D(32, kernel_size=(3, 3),
activation='relu')(inpx)
layer2 = Conv2D(64, (3, 3), activation='relu')(layer1)
layer3 = MaxPooling2D(pool_size=(3, 3))(layer2)
layer4 = Dropout(0.5)(layer3)
layer5 = Flatten()(layer4)
layer6 = Dense(250, activation='sigmoid')(layer5)
layer7 = Dense(10, activation='softmax')(layer6)
---
__
__
* **Explanation of the working of each layer in CNN model:**
layer1 is Conv2d layer which convolves the image using 32 filters each of size
(3*3).
layer2 is again a Conv2D layer which is also used to convolve the image and is
using 64 filters each of size (3*3).
layer3 is MaxPooling2D layer which picks the max value out of a matrix of size
(3*3).
layer4 is showing Dropout at a rate of 0.5.
layer5 is flattening the output obtained from layer4 and this flatten output
is passed to layer6.
layer6 is a hidden layer of neural network containng 250 neurons.
layer7 is the output layer having 10 neurons for 10 classes of output that is
using the softmax function.
* **Calling compile and fit function:**
__
__
__
__
__
__
__
model= Model([inpx], layer7)
model.compile(optimizer=keras.optimizers.Adadelta(),
loss=keras.losses.categorical_crossentropy,
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=12, batch_size=500)
---
__
__

Firstly, we made an object of the model as shown in the above given lines,
where [inpx] is the input in the model and layer7 is the output of the model.
We compiled the model using required optimizer, loss function and printed the
accuracy and at the last model.fit was called along with parameters like
x_train(means image vectors), y_train(means the label), number of epochs and
the batch size. Using fit function x_train, y_train dataset is fed to model in
a particular batch size.
* **Evaluate function:**
model.evaluate provides the score for the test data i.e. provided the test
data to the model. Now, model will predict class of the data and predicted
class will be matched with y_test label to give us the accuracy.
__
__
__
__
__
__
__
score= model.evaluate(x_test, y_test, verbose=0)
print('loss=', score[0])
print('accuracy=', score[1])
---
__
__
**Output:**


My Personal Notes _arrow_drop_up_
Save
|
5119e1cf8d5c1e7bf2f8e8fbe61fa5d71d2c6c9f | ManavGuru/Portfolio | /Python Stuff/string_sort.py | 187 | 3.828125 | 4 | import re
def sort_string(phrase):
words = phrase.split(" ")
words.sort(key = lambda s: s.casefold())
return words
input_1 = input("Enter a phrase: ")
print(sort_string(input_1))
|
dfbf6d642c2b05f643bc8199bcb1e8a2ba685dcf | owaishanif786/python | /intro/funcs.py | 562 | 3.65625 | 4 | def contact_card(name, age, car_model):
return f"{name} is {age} and drives a {car_model}"
#calling args in sequence
contact_card("owais", 28, "bonusCar")
#if calling out of order then you have to specify name and value
contact_card(age=28, car_model="f1", name="owais")
#Positional argument follows keyword argument
contact_card(age=28, "keith", car_model="civic")
#File "<stdin>", line 1
#SyntaxError: positional argument follows keyword argument
#default arguments
def can_drive(age, drive_age=16):
return age >= drive_age
can_drive(15) #False
|
0d79021f33f26f7285df71f4928be8cd8de2d8bf | junyechen/PAT-Advanced-Level-Practice | /1048 Find Coins.py | 2,644 | 3.828125 | 4 | """
Eva loves to collect coins from all over the universe, including some other planets like Mars. One day she visited a universal shopping mall which could accept all kinds of coins as payments. However, there was a special requirement of the payment: for each bill, she could only use exactly two coins to pay the exact amount. Since she has as many as 105 coins with her, she definitely needs your help. You are supposed to tell her, for any given amount of money, whether or not she can find two coins to pay for it.
Input Specification:
Each input file contains one test case. For each case, the first line contains 2 positive numbers: N (≤105, the total number of coins) and M (≤103, the amount of money Eva has to pay). The second line contains N face values of the coins, which are all positive numbers no more than 500. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the two face values V1 and V2 (separated by a space) such that V1+V2=M and V1≤V2. If such a solution is not unique, output the one with the smallest V1. If there is no solution, output No Solution instead.
Sample Input 1:
8 15
1 2 8 7 2 4 11 15
Sample Output 1:
4 11
Sample Input 2:
7 14
1 8 7 2 4 11 15
Sample Output 2:
No Solution
"""
#############################################
"""
非常简单,一次通过
有两种方法,一种就是从小到大依次遍历,另一种是用桶排序的方法
但需注意测试点3的钱币数值是大于500的!不符合题意!
本题其实考察的也是排序,桶排的速度比前一快多了
"""
#############################################
n, m = map(int, input().split())
coin = [0] * m
for i in map(int, input().split()):
if i < m:
coin[i] += 1
for i in range(1, m // 2):
if coin[i] != 0 and coin[m - i] != 0:
print(i, m - i)
exit(0)
if m % 2 == 0:
if coin[m // 2] >= 2:
print(m // 2, m // 2)
exit(0)
else:
if coin[m//2] != 0 and coin[m//2+1] != 0:
print(m//2, m//2 + 1)
exit(0)
print("No Solution")
"""
n, m = map(int, input().split())
coin = sorted(map(int, input().split()))
i, j = 0, len(coin)-1
while i < j:
if coin[i] + coin[j] == m:
print(coin[i], coin[j])
exit(0)
else:
while coin[i] + coin[j] > m:
j -= 1
if i == j:
print("No Solution")
exit(0)
if coin[i] + coin[j] == m:
print(coin[i], coin[j])
exit(0)
i += 1
print("No Solution")
"""
|
379d346cfe6ccfc2c587a1ba89042c5c0fa996af | Gendo90/HackerRank | /Linked Lists/compare_lists.py | 1,799 | 3.5 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
class SinglyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def print_singly_linked_list(node, sep, fptr):
while node:
fptr.write(str(node.data))
node = node.next
if node:
fptr.write(sep)
# Complete the insertNodeAtTail function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def compare_lists(llist1, llist2):
current_1 = llist1
current_2 = llist2
if(current_1==current_2==None):
return 1
while(current_1 or current_2):
if(current_1==None or current_2==None):
return 0
if(current_1.data!=current_2.data):
return 0
current_1 = current_1.next
current_2 = current_2.next
return 1
# if __name__ == '__main__':
# # n = int(input())
# fileHandler = open("insertTailNode_test_case.txt", "r")
#
# # Get list of all lines in file
# listOfLines = fileHandler.readlines()
#
# # Close file
# fileHandler.close()
#
# llist = SinglyLinkedList()
#
# gb = []
# for i, line in enumerate(listOfLines):
# if(i==0):
# continue
# gb.append(int(line))
#
# print(sys.getrecursionlimit())
# #note had to change the recursion limit here to get it to work!
# sys.setrecursionlimit(5000)
#
# for i in range(len(gb)):
# llist_item = gb[i]
# llist_head = insertNodeAtTail(llist.head, llist_item)
# llist.head = llist_head
#
# node = llist.head
# while(node):
# print(node.data)
# node = node.next
|
1e826c9ac86e3f33059a42898b565801f89ea114 | huyngopt1994/python-Algorithm | /green/green-09-recursive/count_numbers.py | 462 | 3.6875 | 4 | # Using recursion to calculate the numbers, 475 => return 3 , 1242 => 4
# stack for input 345 => (345,0) => (345,0) (34,1) => (345,0) (34,1) (3,2) =>(345,0) (34,1) (3,2) (0,3)(!Ping we got this)
def count_number(number,counting):
if number == 0:
return counting
else:
return count_number(number//10, counting+1)
my_input = int(input())
if my_input == 0:
print (1)
else:
result = count_number(abs(my_input),0)
print(result) |
5564d154d391e7679efc4204a031f9cc6cb62e52 | sirasjad/DCS3101 | /vigenere_cipher/vigenere_doublekey.py | 2,644 | 3.828125 | 4 | import string
class vigenereCipher():
def __init__(self, key1, key2):
self.alphabet = []
self.fillAlphabet()
self.key = [key1.upper(), key2.upper()]
def fillAlphabet(self):
for i in range(26):
self.alphabet.append(string.ascii_uppercase[i])
def increaseKeySize(self, message, key):
if len(message) >= len(key):
tempKey = ""
for i in range(len(message)):
tempKey += key[i % len(key)]
return tempKey
def encrypt(self, message):
for x in range(2):
self.key[x] = self.increaseKeySize(message, self.key[x])
message = message.upper()
encryptedCipher = ""
keyPos = 0
for i in range(len(message)):
if message[i] == " ":
encryptedCipher += " "
elif message[i] == ".":
encryptedCipher += "."
else:
letterIndex = (self.alphabet.index(message[i]) + self.alphabet.index(self.key[x][keyPos])) % 26
encryptedCipher += self.alphabet[letterIndex]
keyPos += 1
print("----- Encryption Round %i (using Key-%i) -----" % (x+1, x+1))
print("Key: %s" % self.key[x])
print("Plaintext: %s" % message)
print("Ciphertext: %s\n" % encryptedCipher)
message = encryptedCipher
def decrypt(self, message):
for x in range(2):
self.key[x] = self.increaseKeySize(message, self.key[x])
message = message.upper()
decryptedText = ""
keyPos = 0
for i in range(len(message)):
if message[i] == " ":
decryptedText += " "
elif message[i] == ".":
decryptedText += "."
else:
letterIndex = (self.alphabet.index(message[i]) - self.alphabet.index(self.key[x][keyPos])) % 26
decryptedText += self.alphabet[letterIndex]
keyPos += 1
print("----- Decryption Round %i (using Key-%i) -----" % (x+1, x+1))
print("Key: %s" % self.key[x])
print("Plaintext: %s" % message)
print("Ciphertext: %s\n" % decryptedText)
message = decryptedText
# Initiate an object, setting key-1 = "Green" and key-2 = "Watermelon"
vigenere = vigenereCipher("Green", "Watermelon")
vigenere.encrypt("The quick brown fox jumps over the lazy dog.")
vigenere.decrypt("VYB YYAXZ TRQNK NSP EJEPU FSMV LCT DABP AWK.")
|
1639721e64ffaf30ce946cfed8e64f6aa876536f | seanchen513/leetcode | /math/0296_best_meeting_point.py | 9,059 | 4.28125 | 4 | """
296. Best Meeting Point
Hard
A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.
Example:
Input:
1 - 0 - 0 - 0 - 1
| | | | |
0 - 0 - 0 - 0 - 0
| | | | |
0 - 0 - 1 - 0 - 0
Output: 6
Explanation: Given three people living at (0,0), (0,4), and (2,2):
The point (0,2) is an ideal meeting point, as the total travel distance
of 2+2+2=6 is minimal. So return 6.
"""
from typing import List
import collections
### Assume there's at least one home.
###############################################################################
"""
Solution: brute force.
O(mnk) time if there are k houses.
O(m^2 n^2) time: nested loops for i, j, and within that a nested loop over
bases, which might iterate as many as m*n times.
O(mn) extra space: for "bases".
TLE
"""
class Solution:
def minTotalDistance(self, grid: List[List[int]]) -> int:
n_rows = len(grid)
n_cols = len(grid[0])
bases = []
for i in range(n_rows):
for j in range(n_cols):
if grid[i][j] == 1:
bases.append((i, j))
min_d = float('inf')
#min_pt = (0, 0)
for i in range(n_rows):
for j in range(n_cols):
# Don't use condition "if grid[i][j] == 0" since the people
# can meet at one of their homes.
d = 0
for i0, j0 in bases:
d += abs(i - i0) + abs(j - j0)
if d < min_d:
min_d = d
#min_pt = (i, j)
return min_d
###############################################################################
"""
Solution 2: Solve for the min distance in each dimension separately using
brute force. Then add these min distances.
O(mn + n^2 + m^2) time
O(m + n) extra space
Runtime: 72 ms, faster than 27.18% of Python3 online submissions
Memory Usage: 13 MB, less than 100.00% of Python3 online submissions
"""
class Solution2:
def minTotalDistance(self, grid: List[List[int]]) -> int:
def min_dist(arr):
n = len(arr)
#bases = {i: arr[i] for i in range(n) if arr[i] > 0}
bases = {i: x for i, x in enumerate(arr) if arr[i] > 0}
min_d = float('inf')
for i in range(n):
d = 0
for i0, weight in bases.items():
d += abs(i - i0) * weight
if d < min_d:
min_d = d
return min_d
# These comprehensions are faster
row_sums = [sum(row) for row in grid]
col_sums = [sum(row) for row in zip(*grid)]
#row_sums = [0] * n_rows
#col_sums = [0] * n_cols
#for i in range(n_rows):
# for j in range(n_cols):
# row_sums[i] += grid[i][j]
# col_sums[j] += grid[i][j]
return min_dist(row_sums) + min_dist(col_sums)
###############################################################################
"""
Solution 3: Solve for the min distance in each dimension separately by using
sorting to find the median coordinate.
O(mn log mn) time: each of "rows" and "cols" may contain up to mn elements,
and they are sorted.
O(mn) extra space: "rows" and "cols" can hold up to mn elements.
Runtime: 60 ms, faster than 88.89% of Python3 online submissions
Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions
"""
class Solution3:
def minTotalDistance(self, grid: List[List[int]]) -> int:
n_rows = len(grid)
n_cols = len(grid[0])
rows = []
cols = []
for i in range(n_rows):
for j in range(n_cols):
if grid[i][j] == 1:
rows.append(i)
cols.append(j)
rows.sort()
cols.sort()
r = rows[len(rows) // 2]
c = cols[len(cols) // 2]
return sum(abs(r - i) + abs(c - j) \
for i in range(n_rows) for j in range(n_cols) if grid[i][j] == 1)
###############################################################################
"""
Solution 4: Solve each dimension separately. Find coordinates of homes in
sorted order, and then calculate their medians.
O(mn) time
O(mn) extra space
Runtime: 64 ms, faster than 69.57% of Python3 online submissions
Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions
"""
class Solution4:
def minTotalDistance(self, grid: List[List[int]]) -> int:
n_rows = len(grid)
n_cols = len(grid[0])
rows = []
cols = []
for i in range(n_rows):
for j in range(n_cols):
if grid[i][j] == 1:
rows.append(i)
for j in range(n_cols):
for i in range(n_rows):
if grid[i][j] == 1:
cols.append(j)
r = rows[len(rows) // 2]
c = cols[len(cols) // 2]
return sum(abs(r - i) + abs(c - j) \
for i in range(n_rows) for j in range(n_cols) if grid[i][j] == 1)
###############################################################################
""" BEST SOLUTION
Solution 5: Solve each dimension separately. Find coordinates of homes in
sorted order with frequencies, and then calculate their medians.
For large grids, the calculation of medians can be improved by starting from
the middle or using bisection.
O(mn) time
O(n + m) extra space
Runtime: 52 ms, faster than 99.03% of Python3 online submissions
Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions
"""
class Solution5:
def minTotalDistance(self, grid: List[List[int]]) -> int:
n_rows = len(grid)
n_cols = len(grid[0])
# These comprehensions are faster than nested loops
row_sums = [sum(row) for row in grid]
col_sums = [sum(row) for row in zip(*grid)]
mid = sum(row_sums) // 2
s = 0
for i in range(n_rows):
s += row_sums[i]
if s > mid:
r = i
break
s = 0
for j in range(n_cols):
s += col_sums[j]
if s > mid:
c = j
break
### This is O(m + n)
return sum(abs(r - i)*row_sums[i] for i in range(n_rows)) + \
sum(abs(c - j)*col_sums[j] for j in range(n_cols))
### This is O(mn)
# return sum(abs(r - i) + abs(c - j) \
# for i in range(n_rows) for j in range(n_cols) if grid[i][j] == 1)
###############################################################################
"""
Solution 5b: same as sol #5, but more concise.
"""
class Solution5b:
def minTotalDistance(self, grid: List[List[int]]) -> int:
res = 0
for grid in (grid, zip(*grid)):
row_sums = [sum(row) for row in grid]
mid = sum(row_sums) // 2
n_rows = len(row_sums)
s = 0
for i in range(n_rows):
s += row_sums[i]
if s > mid:
r = i
break
res += sum(abs(r - i)*row_sums[i] for i in range(n_rows))
return res
###############################################################################
if __name__ == "__main__":
def test(grid, comment=None):
print("="*80)
if comment:
print(comment, "\n")
for row in grid:
print(row)
res = sol.minTotalDistance(grid)
print(f"\nSolution: {res}\n")
#sol = Solution() # brute force
#sol = Solution2() # combine 1-d solutions
#sol = Solution3() # find coordinates oh homes, sort, then use medians
#sol = Solution4() # find coordinates in sorted order, then use medians
#sol = Solution5() # BEST SOL; find coords in sorted order w/ freqs
sol = Solution5b() # same as sol #5b but more concise
comment = "LC example; answer = 6"
grid = [
[1,0,0,0,1],
[0,0,0,0,0],
[0,0,1,0,0]
]
test(grid, comment)
comment = "LC test case; answer = 1"
grid = [
[1,1]
]
test(grid, comment)
comment = "Trivial case; answer = 0"
grid = [
[1]
]
test(grid, comment)
comment = "LC test case; answer = 19"
grid = [
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,1,0,0,1,0],
[1,1,0,0,0,0,1,0,0],
[0,0,0,1,1,1,0,0,0]]
test(grid, comment)
comment = "LC test case; answer = 49"
grid = [
[0,1],
[0,1],
[0,1],
[1,1],
[0,0],
[0,1],
[0,0],
[0,0],
[0,0],
[0,0],
[1,0],
[1,0],
[0,0],
[0,0],
[1,1],
[0,0]]
test(grid, comment)
|
fafb1c9b847bed98b78a8d2bc6d5c2f18a0dc3ef | AKASHDEEP-ROY/sem-2-assignment-2-computation | /prob13.py | 1,024 | 3.5 | 4 | '''
Use Euler's method in a Python code to solve the initial value problem
t^2y"-2ty'+2y=t^3ln(t) with 1<t<2, y(1) = 1, and y'(1) = 0 with step size h = 0.001. Plot the solution
together with the known exact solution y(t) = 7t/4 + ((t^3)/2)ln(t) - (3/4)t^3
'''
#Akashdeep Roy
import numpy as np
import matplotlib.pyplot as plt
h=0.001
def f(y,ydot,t):
return ((t**3)*np.log(t) - 2*y + 2*t*ydot)/(t**2)
def sol(t):
return (7*t/4)+((t**3)/2)*np.log(t)-(3/4)*(t**3)
t=np.arange(1,2+h,h)
y=np.ones(len(t),dtype=float)
ydot=np.zeros(len(t),dtype=float)
ydot[0]=0.00
for i in range(len(t)-1):
ydot[i+1]=ydot[i]+(h*f(y[i],ydot[i],t[i]))
y[i+1]=y[i]+h*ydot[i]
plt.plot(t,y,label='numerical solution')
plt.plot(t,sol(t),label='analytical solution')
plt.xlabel('t')
plt.ylabel('y')
plt.title('prob-13')
plt.legend()
plt.show()
plt.plot(t,abs((sol(t)-y)/sol(t)))
plt.xlabel('t',size=18)
plt.ylabel('relative error',size=18)
plt.title('prob-13')
plt.show()
'''
Comment : Relative error makes an interesting curve with t.
''' |
93dc561e83363c0223b408587368a0e63c7480b7 | MrHamdulay/csc3-capstone | /examples/data/Assignment_2/msmona001/question3.py | 361 | 4.25 | 4 | #Assignment 2
#Question 3
#Onalerona Mosimege
import math
area = 0
pi = 2
constant = math.sqrt(2)
x = 2/constant
while x != 1:
pi = pi * x
constant = math.sqrt(2 + constant)
x = 2/ constant
print("Approximation of pi:", str(round(pi,3)))
radius = eval(input("Enter the radius:\n"))
area = ((radius)**2) * pi
print("Area:", str(round(area,3))) |
649deaf1f486228612ba2f5c5fcdc7f147c48d7c | mattsuri/unit3 | /dotDemo.py | 339 | 3.671875 | 4 | #Matthew Suriawinata
#3/1/18
#dotDemo.py - how to use loops with graphics
from ggame import *
RADIUS = 10
red = Color("0xFF000", 1)
dot = CircleAsset(RADIUS, LineStyle(1, red), red)
for i in range(12 * 2*RADIUS+10): #place row of dots
for j in range(12):
Sprite(dot, (10 + i*(2*RADIUS+10) ,10+(2*RADIUS+10)*j))
App().run()
|
22b08dd29baec46ca9ac3ae9feb5999163e4290c | ahmedsabie/cifar-object-recognition | /convex_optimization.py | 1,007 | 3.6875 | 4 | from copy import deepcopy
class GradientDescent:
ALPHA_MIN = 0.0000001
ALPHA_MAX = 1.0
ITERATIONS = 100
def __init__(self, model):
self.model = deepcopy(model)
def find_min(self):
print ('Iteration: Cost')
model = deepcopy(self.model)
theta = model.get_theta()
for i in xrange(self.ITERATIONS):
alpha = self.ALPHA_MAX
updated = False
while alpha >= self.ALPHA_MIN and not updated:
previous_cost = model.cost_function()
try_theta = theta - alpha*model.cost_function_gradient()
model.set_theta(try_theta)
new_cost = model.cost_function()
if new_cost < previous_cost:
theta = try_theta
updated = True
else:
model.set_theta(theta)
alpha /= 2
print ('Iteration %d: %.2f' % (i+1, model.cost_function()))
return theta
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.