blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
9702aa5c42159a682572f88aee7dc4594e7cae94 | meoclark/Data-Science-DropBox | /Build Chatbots/Search&Find.py | 456 | 4.15625 | 4 | import re
# import L. Frank Baum's The Wonderful Wizard of Oz
oz_text = open("the_wizard_of_oz_text.txt",encoding='utf-8').read().lower()
# search oz_text for an occurrence of 'wizard' here
found_wizard = re.search("wizard",oz_text)
print(found_wizard)
# find all the occurrences of 'lion' in oz_text here
all_lions = re.findall("lion",oz_text)
print(all_lions)
# store and print the length of all_lions here
number_lions = len(all_lions)
print(number_lions)
|
acb53bfe77024fe322a74f220475f7ec3a397637 | Flexime/Python | /test.py | 245 | 3.671875 | 4 | import random as rand
rows, cols = (5, 5)
arr=[]
for i in range(rows):
col = []
for j in range(cols):
col.append(rand.randrange(7)) # 0 если надо 2д масс из нулей
arr.append(col)
print(arr)
print(arr[1:]) |
0c7427837a4994839f2e95fbab138c83d3bf6889 | sleevewind/practice | /day02/operator.py | 1,177 | 4.3125 | 4 | # 在python3里,整数除法的结果是浮点数
# 在python2里,整数除法的结果是整数
print(6 / 2) # 3.0
print(10 / 3) # 3.3333333333333335
print(10 // 3) # 整除运算,向下取整 3
# 幂运算
print(3 ** 3)
print(81 ** 0.5)
a = b = c = d = 10
print(a, b, c, d)
o, *p, q = 1, 2, 3, 4, 5, 6 # *p 代表可变长度
print(o, p, q) # 1 [2, 3, 4, 5] 6
# 比较运算符在字符串里的使用
# 根据各个字符的编码值逐位比较
print('a' > 'b') # False
print('abc' > 'b') # False
# 逻辑运算符:and or not
print((3 > 2 and 5 > 4)) # True
print((3 > 2 or 5 > 3)) # True
print(not 3 > 2) # false
# 逻辑与运算做取值时,取第一个为 False 的值;
# 如果所有运算数都是True,取最后一个值
a = 3 and 5 and 0 and 'hello' # 0
b = 'good' and 'yes' and 'ok' and 100 # 100
print(a, b)
# 逻辑或运算做取值时,取第一个为 True 的值;
# 如果所有运算数都是False,取最后一个值
a = 0 or 0 or 3 or 'hello' # 3
b = 0 or [] or {} or () # ()
print(a, b)
# 位运算符
# &(与) |(或) ^(异或) <<(左移) >>(右移) ~(取反)
a = 23
b= 14
print(a&b)
print(a|b)
print(a^b)
print(~a)
|
c244d4afcf121047a50b8b2c9ed1cbd7f982396e | MatthewKosloski/starting-out-with-python | /chapters/06/12.py | 447 | 3.859375 | 4 | # Program 6-12
# Reads the values in video_times.txt
# file and calculates their totals.
def main():
video_file = open('video_times.txt', 'r')
total = 0.0
count = 0
print('Here are the running times for each video:')
for line in video_file:
run_time = float(line)
count += 1
print('Video #', count, ': ', run_time, sep='')
total += run_time
video_file.close()
print('The total running time is', total, 'seconds.')
main() |
ef661218988bbcbbe410015bb700b768661a1cc4 | kapilbhudhia/python | /PGP-AI/SavingsAccount.py | 611 | 3.53125 | 4 | from Account import Account
class SavingsAccount(Account):
def __init__(self, minimumBalance, **accountArgs):
self.MinimumBalance = minimumBalance
super().__init__(**accountArgs)
def AccountInfo(self):
accountInfo = super().AccountInfo()
savingsInfo = "\tMinimum Balance: %s" % (str(self.MinimumBalance))
return accountInfo + "\n" + savingsInfo
def Withdraw(self, amount):
if self.Balance - amount <= self.MinimumBalance:
raise "Not sufficient balance"
else:
self.Balance -= amount
return self.Balance
|
ee5a4f30b98a31942e0a61d16899cbbcdc9960e8 | lucasportella/learning-python | /python-codes/m2_curso_em_video_estruturas_de_controle/ex060.2.py | 130 | 3.875 | 4 | from math import factorial
num = int(input('Diga o valor p/ saber o fatorial: '))
print('Calculando... {}'.format(factorial(num))) |
6d979408158136f2c86686d3c4288ff7d8ebde73 | bopopescu/TelPractice1 | /22_BreakContinuePass.py | 336 | 3.859375 | 4 | x=int(input("How many candies you want"))
available=10
i=1
while i<=x:
if i>available:
print("Out of stock")
break
print("candy",i)
i+=1
for k in range(1,101):
if k%3==0 or k%5==0:
continue
print(k)
print("Bye")
for j in range(1,101):
if j%2==0:
pass
else:
print(j)
|
8b7c0dbbdbae4f3f7ad833921d82e7c6af360f58 | nikolaouyiannis/Python-School-App | /moduleCourses.py | 2,555 | 4.4375 | 4 | class Courses:
"""This class represents a language course"""
coursesInfo = []
dummyCoursesInfo = []
#these lists will be filled with class objects
def __init__(self, c_title, c_language, c_description, c_type):
self.c_title = c_title
self.c_language = c_language
self.c_description = c_description
self.c_type = c_type
def __str__(self):
return f"{self.c_title}: {self.c_language}, {self.c_description}, {self.c_type}"
def addCourses():
"""This method asks for user input info, creates a class object, appends it to a list
and finally returns a list with all class objects"""
print("\n", " Courses information section ".upper().center(100,'-'), "\n")
availableLanguages = ('C#', 'Java', 'Javascript', 'Python')
while True:
c_language = input(f"Select a language {availableLanguages} to add language course information or press 'q' to quit: ")
if c_language in availableLanguages:
print(f"\nFor {c_language} enter the following: Course Title, Course Description, Course Type.")
c_title = input("Course Title: ")
c_description = input("Course Descrpition: ")
c_type = input("Course Type: ")
x = Courses(c_title, c_language, c_description, c_type)
Courses.coursesInfo.append(x)
print("\n", ">New course: ", x, "\n")
elif c_language == 'q':
break
else:
print("\n", " Enter one of the available languages or check for typos. ".center(85,'*'), "\n")
return Courses.coursesInfo
def dummyCourses():
"""This method creates dummy courses, simultaneously appends them to a list and finally returns it"""
Courses.dummyCoursesInfo.append(Courses('CB13FTCS', 'C#', '12 weeks', 'Full Time'))
Courses.dummyCoursesInfo.append(Courses('CB13PTCS', 'C#', '24 weeks', 'Part Time'))
Courses.dummyCoursesInfo.append(Courses('CB13FTJA', 'Java', '12 weeks', 'Full Time'))
Courses.dummyCoursesInfo.append(Courses('CB13PTJA', 'Java', '24 weeks', 'Part Time'))
Courses.dummyCoursesInfo.append(Courses('CB13FTJS', 'Javascript', '12 weeks', 'Full Time'))
Courses.dummyCoursesInfo.append(Courses('CB13PTJS', 'Javascript', '24 weeks', 'Part Time'))
Courses.dummyCoursesInfo.append(Courses('CB13FTPY', 'Python', '12 weeks', 'Full Time'))
Courses.dummyCoursesInfo.append(Courses('CB13PTPY', 'Python', '24 weeks', 'Part Time'))
return Courses.dummyCoursesInfo
|
2b818acf8faf1f3e04aaa449a14fb31c8d25ba9d | lucas-ferreira1/PythonExercises | /POO/biblioteca.py | 2,377 | 4 | 4 | from livros_class import livros_class #import the class that was created
#Book's definition
livro_0 = livros_class("Scott Pilgrim")
livro_1 = livros_class ("Maus")
livro_2 = livros_class("Pilulas Azuis")
livro_3 = livros_class("Tintin no mundo sovietico")
livro_4 = livros_class("Alice no pais das maravilhas")
livro_5 = livros_class("Misto Quente")
livro_6 = livros_class("Viagem ao mundo em 80 dias")
livro_7 = livros_class("Arabe do Futuro")
livro_8 = livros_class("Percy Jackson")
livro_9 = livros_class("Memorias Postumas de Bras Cubas")
livro_10 = livros_class("HeartStopper")
#Edition's definition
edicao = [[1,2,3],[1,2],[3],[5],[1,3,4],[1,2,3],[3],[5],[3],[1,2]]
#Interaction w/ the user
print("Bem vindo a Biblioteca do Lucas! Insira seu nome e o seu livro preferido")
cliente = input("Insira seu nome")
print(f"{cliente}, agora escolha o livro de interesse:"
'''
(0) Scott Pilgrim
(1) Maus
(2) Pilulas Azuis
(3) Tintin no mundo sovietico
(4) Alice no pais das maravilhas
(5) Misto Quente
(6) Viagem ao mundo em 80 dias
(7) Arabe do Futuro
(8) Percy Jackson
(9) Memorias Postumas de Bras Cubas
(10)HeartStopper
''')
#Exception
while True:
try:
selecao = int(input("Digite aqui o livro de interesse :"))
break
except TypeError:
print("Escolha novamente um livro")
lista_livro = [livro_0,livro_1,livro_2,livro_3,livro_4,livro_5,livro_6,livro_7,livro_8,livro_9]
opcao_selecionada = int(selecao)
#Editions' choice
print(edicao[selecao])
while True:
try:
edicao = int(input(f"{cliente}, agora escolha a edicao do livro :"))
break
except TypeError:
print("Escolha novamente a edicao")
edicao_selecionada = int(edicao)
#Attributes the book for the edition
lista_livro[opcao_selecionada].edition = edicao_selecionada
#Final interation w/ the user
for books in lista_livro:
if opcao_selecionada > 10 :
print("Numero incorreto de livro, tente novamente")
break
if opcao_selecionada <= 10:
if edicao != edicao_selecionada:
print("Numero incorreto de horario, tente novamente")
else:
print(f"{cliente}, seu livro {lista_livro[opcao_selecionada].nome} com a edicao {lista_livro[opcao_selecionada].edition} esta reservado.")
print("Volte Sempre!")
break
break
break |
4326e8da1c32e07197cf7cec167b52b6aab5e706 | Koemyy/Projetos-Python | /PYTHON/Python Exercícios/2 lista de exercicios/ex45.py | 88 | 3.828125 | 4 | n=2
c = int(input())
while(n<=c):
z=n**2
print(f"{n}^{2} = {z}")
n+=2 |
f27b5127b91e176f5b411b00886bff6f3aac0246 | blhelias/dataStructure | /Heap/Heap.py | 3,267 | 4.28125 | 4 | import math
class Heap:
""" Tas complexite moyennne d'une opération: O(log(n))
complexité dans le pire cas: O(n) -> a cause
du dictionnaire.
"""
def __init__(self, items) -> None:
self.n = 0
self.heap = [] # index 0 will be ignored
# len(self.heap) = 1
for x in items:
self.push(x)
def __len__(self):
"""get length of the heap
"""
return len(self.heap)
def push(self, x):
"""push a new element in the heap
"""
i = len(self)
self.heap.append(x) # ajout d'une nouvelle feuille
self.sift_up() # maintenir l'ordre du tas
def pop(self):
"""Remmove an element from the heap
"""
root = self.heap[0]
x = self.heap.pop() # Enlever la derniere feuille
if self: # si le tas n'est pas vide
self.heap[0] = x # et la mettre à la racine
self.sift_down() # maintenir l'ordre du tas
print(self)
return root
def sift_up(self):
k = len(self) - 1
while k > 0:
p = math.floor((k - 1) / 2)
item = self.heap[k]
parent = self.heap[p]
if item > parent:
# swap
self.heap[p], self.heap[k] = self.heap[k], self.heap[p]
k = p
else:
break
def sift_down(self):
"""La methode up permet de remonter un noeud en effectuant une suite d'echange
entre le noeud et son pere. Le noeud remonte jusqu'a ce que le tas soit dans le bon
ordre"""
#TODO
# lorsqu'un element est retire:
# faire descendre le premier element tant quil est plus
# grand que l'un des 2 enfants
p = 1
k = 0
item = self.heap[k]
left_child = self.heap[p]
right_child = self.heap[p+1]
if item < left_child or item < right_child:
if left_child > right_child:
# swap with left
self.heap[p], self.heap[k] = self.heap[k], self.heap[p]
k = p
else:
# swap to the right
self.heap[p+1], self.heap[k] = self.heap[k], self.heap[p+1]
k = p + 1
else:
return
while k < len(self) - 1:
item = self.heap[k - 1]
p = (k * 2) - 1
left_child = self.heap[p]
right_child = self.heap[p+1]
if item < left_child or item < right_child:
if left_child > right_child:
# swap with left
self.heap[p], self.heap[k] = self.heap[k], self.heap[p]
k = p
else:
# swap with right
self.heap[p+1], self.heap[k] = self.heap[k], self.heap[p+1]
k = p + 1
else:
break
def update(self, old, new):
"""changer la valeur d'un element du tas"""
raise NotImplementedError()
def __repr__(self):
heap_print = ""
for elements in self.heap:
heap_print += str(elements) + ", "
return "[ {}]".format(heap_print)
|
f66d8af86c8eda29800b419718de0930c972e39d | Armanchik74/practicum-1 | /38.py | 1,053 | 4.09375 | 4 | """
Имя проекта: practicum-1
Номер версии: 1.0
Имя файла: Задание 38.py
Автор: 2020 © А.С. Манукян, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 17/12/2020
Дата последней модификации: 17/12/2020
Описание: Решение задачи № 38
#версия Python:3.9
"""
Дан одномерный массив числовых значений, насчитывающий N элементов.Исключить из него M элементов, начиная с позиции K.
""
import numpy as np
import array
import random
N = int(input("Введите количество элементов массива "))
K = int(input("Позиция K "))
M = int(input("количество элементов для вычитания "))
A = [random.randint(0, 100) for i in range(0, N)]
print(A)
A.insert(K,M)
print(A)
A.delete(K,M)
|
f9edbe2de92f58ae039b2e14a485e67531d3b872 | robin-qu/Movie-Recommender | /dataOverview/frequent_appeared_genres_of_high_rated_movies.py | 927 | 3.8125 | 4 | """
Movie Recommender Project
Hongbin Qu
This program uses SQL query statement to find out
the top 20 frequent appeared genres in high rated movies(>4)
"""
import sqlite3
connection = sqlite3.connect("/Users/haofang/Desktop/546project/546Data.db")
cursor = connection.cursor()
cursor.execute("select count(a.movieId) as numvers_of_movie, a.genres as genres\
from (select movies.movieId, movies.genres\
from movies , meanrating \
where movies.movieId=meanrating.movieId and\
meanrating.mean_rating>4 group by movies.movieId, movies.genres) as a\
group by a.genres \
order by count(a.movieId) desc;")
countMovie_genres= cursor.fetchall()
cursor.close()
connection.close()
for v in range(20):
print(countMovie_genres[v]) |
a596ff0fa9f307fbeca97892f3bee348a7f5a8a1 | lakshyatyagi24/daily-coding-problems | /python/163.py | 1,479 | 4.40625 | 4 | # -------------------------
# Author: Tuan Nguyen
# Date created: 20191023
#!163.py
# -------------------------
"""
Given an arithmetic expression in Reverse Polish Notation, write a program to evaluate it.
The expression is given as a list of numbers and operands. For example: [5, 3, '+'] should return 5 + 3 = 8.
For example, [15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-'] should return 5,
since it is equivalent to ((15 / (7 - (1 + 1))) * 3) - (2 + (1 + 1)) = 5.
You can assume the given expression is always valid.
"""
def reverse_polish_expression(exp):
""" evaluate a list of numbers and operands in Reverse Polish Notation """
stack = [] # stack of numbers initialized
for e in exp: # go through expression in 1 scan ~> running time: O(n)
if not isinstance(e, str): # current element is numeric
stack.append(e)
else: # current element is operand
number1 = stack.pop()
number2 = stack.pop()
piece = eval(str(number2) + e + str(number1)) # calculate a small piece in arithmetic exp
stack.append(piece)
return stack.pop() # the only (and last) element in stack is final result
def test_reversePolishExpression():
assert reverse_polish_expression([15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']) == 5
if __name__ == "__main__":
test_reversePolishExpression() |
12a67445b769e5bbc41350ba855df7a4a2fdf6dd | panghanwu/matplotlib_demo | /17_animation.py | 618 | 3.703125 | 4 | from matplotlib import animation
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x)) # suffix "," means tuple
def action(t):
# update values of y at t
line.set_ydata(np.sin(x+t/50))
return line,
def init():
# update values of y at t
line.set_ydata(np.sin(x))
return line,
anm = animation.FuncAnimation(
fig = fig,
func = action,
frames = 500, # total frames
init_func = init, # the first frame
interval = 20, # per ms
blit = True # only update changed pixels
)
plt.show() |
b2dbb97b25e680d2d75a15d031671a813da14ab8 | ToWorkit/Python_base | /深度学习/one_day/BUG解决.py | 369 | 3.765625 | 4 | import numpy as np
# 随机5个高斯变量
# 秩为1 的数组
a = np.random.randn(5)
print(a)
# 矩阵的长度
print(a.shape)
# 转置
print(a.T)
print(np.dot(a, a.T))
# 1 * 5 的矩阵
a = np.random.randn(5, 1)
print(a)
# 注意看区别
print(a.T)
# 矩阵的乘积
print(np.dot(a, a.T))
# 与上面对比,写时不要省略 1
a = np.random.randn(1, 5)
print(a)
|
fa638f7a7978c213255b6c934c6adffc54a55cf8 | Amiao-miao/all-codes | /month01/day13/exercise01.py | 1,201 | 4.15625 | 4 | """
创建图形管理器
1. 记录多种图形(圆形、矩形....)
2. 提供计算总面积的方法.
满足:
开闭原则
测试:
创建图形管理器,存储多个图形对象。
通过图形管理器,调用计算总面积方法.
"""
class FigureManager:
def __init__(self):
self.__all_figure=[]
def add_figure(self,figure):
if isinstance(figure,Figure):
self.__all_figure.append(figure)
def get_total_acreage(self):
total_acreage=0
for item in self.__all_figure:
total_acreage+=item.calculate_acreage()
return total_acreage
class Figure:
def calculate_acreage(self):
pass
class Rotundity(Figure):
def __init__(self,r):
self.r=r
def calculate_acreage(self):
return 3.14*self.r**2
class Rectangle(Figure):
def __init__(self, height, width):
self.heihet=height
self.width=width
def calculate_acreage(self):
return self.heihet*self.width
manager=FigureManager()
manager.add_figure(Rotundity(10))
manager.add_figure(Rectangle(4,5))
manager.add_figure("三角")
print(manager.get_total_acreage())
|
4b844d1054c79e33866630e87c73e13228c02eef | ChristianR21/CS-490-Deep-Learning | /Lab 1 Q5.py | 3,062 | 4.28125 | 4 | #Chrisitan Rodas
#490-0003
#Question 5
#This is a management program that utililizes class
#The base class is the AMS and that sets basic information that can be inherited by other classes
#The Employee class sets the hourly wage and job position of an employee.
#The Passenger class uses the information from the AMS class and uses that to determince the seat size for passengers
#The Plane class uses the super call and is for the type of plane
#The Destination class calculates the cost for flight to the USA or Europe
#AMS = Airline Management System
class AMS:
def __init__(self):
self.name = ""
self.age = 0
def set_name(self):
self.name = input("Please enter your name: ")
def get_name(self):
return self.name
def set_age(self):
self.age = int(input("Please enter your age: "))
def get_age(self):
return self.age
class Employee:
def __init__(self):
self.hr_wg = 0.00
self.job_position = ""
def set_hr_wg(self):
self.hr_wg = float(input("Enter employee's salary hourly wage: "))
def get_hr_wg(self):
return self.hr_wg
def set_job_postion(self):
self.job_position = str(input("Enter employee's job position: "))
def get_hr_wg(self):
return self.hr_wg
class Passenger(AMS):
def __init__(self):
self.seat_size = ""
def get_seat_size(self, age):
if self.age < 12 :
self.seat_class = "Small Seat"
return self.seat_size
elif self.age >= 12 and self.age < 18:
self.seat_class = "Medium Seat"
return self.seat_size
elif self.age >= 18:
self.seat_class = "Large Seat"
return self.seat_size
else:
print("Invalid age. No seat assigned")
return self.seat_size
class Plane:
def __init__(self):
super(Plane, self).__init__()
self.plane_type = "Jet"
class Destination_Cost:
def __init__(self):
#Private Member
self._location = ""
def fly_cost(self):
location = str(input("Press 1 for USA and 2 for Europe"))
if location == "1":
return 500
elif location == "2":
return 1000
passenger_1 = Passenger()
passenger_1.set_name()
passenger_1.set_age()
#This utilizes the Passenger class, which inherites the AMS class
#This will ouput the age, name and seat size for the passenger
print("Passenger Information: ")
print("Name:", passenger_1.get_name(), "Age:", passenger_1.get_age(),)
print("Seat Size: ", passenger_1.get_seat_size(99))
#This is the Plane class and has the super call
Plane_1 = Plane()
#This utilizes the Desination Cost class and determines flight cost
destinations_1 = Destination_Cost
print("Travel Cost: ", destinations_1.fly_cost(1),"$")
#This utilizes the Employee Class and some basic functions
employee_1 = Employee()
employee_1.set_hr_wg(20.0)
employee_1.set_job_postion() |
4f33310e0bf526d108bf516c1036c8ac76f54b5c | mmoore410/holbertonschool-higher_level_programming | /divide_and_rule/h_reverse_str.py | 598 | 3.8125 | 4 | import threading
class ReverseStrThread(threading.Thread):
sentence = ""
total_count = 0
current_count = 0
def __init__(self, word):
threading.Thread.__init__(self)
self.__order = ReverseStrThread.total_count
ReverseStrThread.total_count += 1
if type(word) != str:
raise Exception("word is not a string")
self.__word = word[::-1] + " "
def run(self):
while ReverseStrThread.current_count < self.__order:
pass
ReverseStrThread.sentence += self.__word
ReverseStrThread.current_count += 1
|
7c0d5151345f9fdc4b313cbc3b52ab9032655826 | s-surineni/atice | /hacker_rank/greedy/max_min.py | 935 | 3.640625 | 4 | # https://www.hackerrank.com/challenges/angry-children/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=greedy-algorithms
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the maxMin function below.
def maxMin(k, arr):
arr.sort()
# print('arr', arr)
k -= 1
end = k
min_diff = sys.maxsize
while end < len(arr):
curr_diff = arr[end] - arr[end - k]
# print('curr_diff', curr_diff)
if curr_diff < min_diff:
min_diff = curr_diff
end += 1
return min_diff
if __name__ == '__main__':
# fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
k = int(input())
arr = []
for _ in range(n):
arr_item = int(input())
arr.append(arr_item)
result = maxMin(k, arr)
print(result)
# fptr.write(str(result) + '\n')
# fptr.close()
|
8f4b0565637f5c7ee21fd407d5e05a4af868631c | lyh-git/bookshop | /charrobot/DEMO01/CS1/client.py | 1,149 | 3.515625 | 4 | import socket # 导入 socket 模块
# 客户端
def client():
s = socket.socket() # 创建 socket 对象
s.connect(('127.0.0.1', 8715))
print("成功连接服务端,请选择服务")
while True:
print("1,聊天机器人,2.中文分词,3.情感分析,4.退出")
target=input()
if target=="4":
return
if target=="1":
while True:
print("请输一句话,输入quit结束聊天")
city=input()
if city=="quit":
break
target=target+"==="+city
s.send(target.encode('utf8'))
print(s.recv(1024).decode(encoding='utf8'))
target="1"
if target == "2":
print("请输入一句话")
data = input()
target = target + "===" + data
s.send(target.encode('utf8'))
print(s.recv(2048).decode(encoding='utf8'))
if target == "3":
s.send(target.encode('utf8'))
print(s.recv(1024).decode(encoding='utf8'))
if __name__ == '__main__':
client() |
178ad67e5678523a3be649cd8a4058456b140569 | Pratyaksh7/Dynamic-Programming | /Longest Common Subsequence/Problem5.py | 767 | 3.703125 | 4 | # 5. Program to find Minimum number of Insertions and deletions to convert 1st string to 2nd string
def lcs(X, Y, n, m):
for i in range(n+1):
for j in range(m+1):
if i==0 or j==0:
t[i][j] = 0
for i in range(1, n+1):
for j in range(1, m+1):
if X[i-1] == Y[j-1]:
# t[i][j] = 1+ lcs(X,Y,i-1,j-1)
t[i][j] = 1+ t[i-1][j-1]
else:
t[i][j] = max(t[i-1][j], t[i][j-1])
return t[n][m]
X = "heap"
Y = "pea"
n = len(X)
m = len(Y)
t = [[-1 for j in range(m+1)] for i in range(n+1)]
result = lcs(X, Y, n, m)
insertions = m - result
deletions = n - result
print("Number of insertions are:", insertions)
print("Number of deletions are:", deletions) |
e927a66967ae894e84226717a0048e66ffb844a8 | tsukumonasu/PythonLambda | /LambdaTest.py | 312 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2)
for i in range(1,11):
print "fibo引数%d=%d" % (i, fib(i))
# 読みやすく
for i in range(1,31):
print "FizzBuzz引数%d=%s" % (i, (lambda g:g(3,'Fizz') + g(5,'Buzz') or i)(lambda j,s:''if i%j else s)) |
35794755b5d481aabcdbffb23ed925484db07b28 | narru888/PythonWork-py37- | /進階/演算法/排序/Quick_Sort(快速排序).py | 1,113 | 4.09375 | 4 | def quick_sort(collection):
"""
快速排序法:
- 時間複雜度:Ο(n log n)
- 穩定性:不穩定
- 介紹:
是先在序列中找出一個元素作為支點(pivot),然後想辦法將比支點的元素移動到支點元素的左邊,比支點大的元素移動到支點元素的右邊,
接著再用同樣的方法繼續對支點的左邊子陣列和右邊子陣列進行排序。
"""
length = len(collection)
if length <= 1:
return collection
else:
# 使用最後一個元素作為支點
pivot = collection.pop()
# 以支點為分界,分出大小兩個陣列
greater, lesser = [], []
for element in collection:
if element > pivot:
greater.append(element)
else:
lesser.append(element)
# 以找到支點位置,而大小兩個陣列繼續做遞歸
return quick_sort(lesser) + [pivot] + quick_sort(greater)
if __name__ == "__main__":
unsorted = [5, 7, 45, 8, 9, 5, 1]
print(quick_sort(unsorted))
|
ec9de5a5538ccf1e2b2bac07bdad9346237470ee | whoiswentz/numerical-analysis | /numericalanalysis/vector.py | 596 | 3.546875 | 4 | class Vector:
def __init__(self, vector):
self._vector = vector
self._len = len(vector)
@property
def shape(self):
return self._shape
@property
def vector(self):
return self._vector
def __repr__(self):
return str(self._vector)
def __str__(self):
return str(self._vector)
def __getitem__(self, key):
return self._vector[key]
# def __setattr__(self, key, value):
# self._vector[key] = value
def __len__(self):
return len(self._vector)
def __eq__(self, other):
pass
|
12506e99de996782851437c2d397af32ed7df569 | sfcpeters/CTI110 | /M4T1_SalesPrediction_PetersM.py | 469 | 3.75 | 4 | #CTI 110
#M4T1-Sales Prediction
#Michael Peters
#13 November 2017
#projected annual profit
totalSales=float(input('Enter Projected Sales: '))
#projected annual profit is 23%
annualProfit = totalSales * .23
#projected profit is rounded to the second decimal place
print("Projected Annual Profit is:" ,format(annualProfit,'.2f'))
#this is another way to round a decimal to the second place
#print("Projected Annual Profit is:" ,round(annualProfit,2))
|
efb31c48ccc34b75ea02215922e32184dc3658f1 | lucas54neves/urionlinejudge | /src/1006.py | 200 | 3.96875 | 4 | # -*- coding: utf-8 -*-
A = float(input())
B = float(input())
C = float(input())
P1 = 2.0
P2 = 3.0
P3 = 5.0
MEDIA = (A * P1 + B * P2 + C * P3) / (P1 + P2 + P3)
print("MEDIA = {:.1f}".format(MEDIA))
|
afdf4a630ffbba7aa195961297135b598c4feab1 | italoohugo/Python | /1UNIDADE/Lista4/Q5.py | 217 | 3.9375 | 4 | print('Programa Calculo do ano bissexto')
ano = float(input('Digite o ano: '))
if (ano % 4 == 0) and (ano % 100 == 0) or (ano %400 == 0):
print('Este ano é bissexto')
else:
print('Este ano não é bissexto') |
4f9330b3e37d6a639622ce5c564c6d208b334b38 | jzferreira/algorithms | /algorithms/sort/python/selectionsort.py | 385 | 3.8125 | 4 | #!/bin/python3
from sort_tools import generate_random_list
def selection_sort(a):
for i in range(len(a)):
current = i
for j in range(i+1, len(a)):
if (a[current]) > a[j]:
current = j
a[i], a[current] = a[current], a[i]
return a
values = generate_random_list(10000)
print(selection_sort(values))
|
36bdfff9c89079a9675e119ffb2bce4f70c22d6c | Man1ish/derivativeinpython | /example17.py | 213 | 4.03125 | 4 | # Example 17: Find the derivative of the trigonometric function f(x) = sin2x using the limit definition
import sympy as sp
x = sp.symbols('x')
f = sp.sin(2*x)
der = sp.diff(f,x)
print(der)
# output : 2*cos(2*x) |
989d351bb9a4f9359df8f2c5c1ebe7f07dceb384 | razak02/python-challenge | /PyBank/main.py | 2,813 | 3.8125 | 4 | # Import the libraries
import csv
import os
# Initiatilize the variables used in the program. Initialize integers = 0 and strings = "".
# Initialize
current_value = 0
prior_value = 0
max_profit=0
max_profit_month = " "
max_loss = 0000000
average_PnL = 0
numRows =0
total = 0
numRows = 0
greatest_inc_pr=0
greatest_dec_pr=0
total_change =0
fin_analysis_txt =[]
msg=[]
print_msg=" "
# Identify path for print output file
fin_analysis_txt = os.path.join(".","Resources","financial_analysis.txt")
# capture the path of soure file
csvfile = os.path.join( "Resources", "budget_data.csv")
with open(csvfile, newline="") as csvfile:
# Create the file reader
# Reading the rows in the file
csvreader = csv.reader(csvfile)
# Remove the header
next(csvreader)
for row in csvreader:
# Assign the value of profit/loss for the first record into a current_value variable from the file reader.
current_value = int(row[1])
if int(row[1]) > max_profit:
max_profit = int(row[1])
max_profit_month = (row[0])
greatest_inc_pr= current_value - prior_value
#print(prior_value)
if int(row[1]) < max_loss:
max_loss = int(row[1])
max_loss_month = (row[0])
greatest_dec_pr = current_value - prior_value
#print("-----")
#print(prior_value)
total += int(row[1])
#print(row[0])
#'${:,.2f}'.format(total)
#total = '${}'.format(total)
if row[0]!="Jan-10":
total_change = total_change+ (current_value - prior_value)
numRows += 1
prior_value = current_value
# Formating the values for printing and exporting to file
average_PnL = total_change/(numRows-1)
average_PnL = '${:.2f}'.format(average_PnL)
total = '${}'.format(total)
greatest_inc_pr = '${}'.format(greatest_inc_pr)
greatest_dec_pr = '${}'.format(greatest_dec_pr )
msg.append(f' -------------------------')
msg.append(f' Financial Analysis ')
msg.append(f'------------------------')
msg.append(f' Total Months: {numRows}')
msg.append(f' Total : {total}')
msg.append(f' Average Change: '+ str(average_PnL) )
msg.append(f' Greatest Increase in Profits: '+ str(max_profit_month) + " (" + str(greatest_inc_pr)+")")
msg.append(f' Greatest Decrease in Profits: ' + str(max_loss_month) + " (" + str(greatest_dec_pr)+")")
msg.append(f'------------------------')
# loop to print out the messages to terminal and text file (financial_analysis.txt) in the 'Resources" directory
with open(fin_analysis_txt,'w') as textfile:
for print_msg in msg:
print(print_msg)
textfile.write(print_msg)
textfile.write("\n")
|
b8b4847e06fa41013762a1ab7185fbdd8e477c5d | hhe0/Leetcode | /Easy/0001-0099/0058/python/Solution.py | 456 | 3.5625 | 4 | class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
i = len(s) - 1
start = False
res = ''
while i >= 0:
if s[i] != ' ':
start = True
res += s[i]
elif start:
break
i -= 1
return len(res)
s = 'a 1 '
solution = Solution()
res = solution.lengthOfLastWord(s)
print(res)
|
f9fc335dc34c12745dec8e1ee212b022f9196aa8 | Inquizarus/pyroch | /src/uplink.py | 768 | 3.796875 | 4 | """
The uplink is the way robots communicate with satellites
"""
class Uplink(object):
satellite = None
override_missing_satellite = False
def __init__(self, satellite=None):
self.satellite = satellite
def is_position_clear(self, posX, posY):
if self.satellite is not None:
occupado = self.satellite.is_coordinates_occupied(posX, posY)
if occupado is False:
return True
return False if self.override_missing_satellite is not True else True
def is_position_out_of_bounds(self, posX, posY):
if self.satellite is not None:
return self.satellite.is_coordinates_out_of_bounds(posX, posY)
return True if self.override_missing_satellite is not True else False |
6bd632abe0953c859971e7e74ef853ee4bb7a910 | eduardogomezvidela/Summer-Intro | /10 Lists/Excersises/24.py | 470 | 3.8125 | 4 | #adder up to first even number
list = [1, 35, 7, 5, 11, 6, 7, 3, 4, 6, 8, 10, 11] #1 + 35 + 7 + 5 + 11 == 59
adder = 0
new_list = []
for num in list:
new_list.append(num%2)
up_to = (new_list.index(0)) #Gets up to what number we will add (even number)
counter = 0
answer = 0
for num in list: #Adds numbers up to even number
if counter < up_to:
answer = answer+num
counter += 1
print(answer)
|
7e87e838d3ed4ab27d76f4d1d359c290a198da28 | in6days/CodingBat-Python-Solutions | /Logic-2.py | 3,423 | 4.4375 | 4 | #Medium boolean logic puzzles -- if else and or not
#We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big
# bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks.
# This is a little harder than it looks and can be done without any loops. See also: Introduction to MakeBricks
def make_bricks(small, big, goal):
return (goal%5)<=small and (goal-(big*5))<=small
#Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values,
# it does not count towards the sum.
def lone_sum(a, b, c):
sum = a+b+c
if a==b==c:
return 0
elif a==b:
return c
elif a==c:
return b
elif b==c:
return a
else:
return sum
#Given 3 int values, a b c, return their sum. However, if one of the values is 13 then it does not count towards
# the sum and values to its right do not count. So for example, if b is 13, then both b and c do not count.
def lucky_sum(a, b, c):
if a==13:
return 0
elif b==13:
return a
elif c==13:
return a+b
else:
return a+b+c
#Given 3 int values, a b c, return their sum. However, if any of the values is a teen -- in the range 13..19 inclusive
# -- then that value counts as 0, except 15 and 16 do not count as a teens. Write a separate helper
# "def fix_teen(n):"that takes in an int value and returns that value fixed for the teen rule. In this way,
# you avoid repeating the teen code 3 times (i.e. "decomposition"). Define the helper below and at the same indent
# level as the main no_teen_sum().
def no_teen_sum(a, b, c):
def fix_teen(n):
if n in [13, 14, 17, 18, 19]:
return 0
else:
return n
return fix_teen(a) + fix_teen(b) + fix_teen(c)
#For this problem, we'll round an int value up to the next multiple of 10 if its rightmost digit is 5 or more,
# so 15 rounds up to 20. Alternately, round down to the previous multiple of 10 if its rightmost digit is less than 5,
# so 12 rounds down to 10. Given 3 ints, a b c, return the sum of their rounded values. To avoid code repetition,
# write a separate helper "def round10(num):" and call it 3 times. Write the helper entirely below and at the same
# indent level as round_sum().
def round_sum(a, b, c):
return round10(a) + round10(b) + round10(c)
def round10(num):
if num % 10 < 5:
return num - (num % 10)
else:
return num + (10 - num % 10)
#Given three ints, a b c, return True if one of b or c is "close" (differing from a by at most 1), while the other is
# "far", differing from both other values by 2 or more. Note: abs(num) computes the absolute value of a number.
def close_far(a, b, c):
if abs(a-b)<=1:
return(abs(a-c)>=2 and abs(c-b)>=2)
elif abs(a-c)<=1:
return(abs(a-b)>=2 and abs(c-b)>=2)
#We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each).
# Return the number of small bars to use, assuming we always use big bars before small bars. Return -1
# if it can't be done.
def make_chocolate(small, big, goal):
if goal >= 5 * big:
remainder = goal - 5 * big
else:
remainder = goal % 5
if remainder <= small:
return remainder
return -1
#In6days
|
8262cc64c430ce9e54c87066c2f9c1d87110bf31 | jokemanfire/test_for_python | /web_client/didianchaxun.py | 1,514 | 3.546875 | 4 | # -*- coding:utf-8 -*-
# 使用百度API查询吃饭地点
from urllib.request import urlopen
from urllib.parse import quote
import json
def APIlink(link):
APIresult = urlopen(link).read()
return APIresult
def main():
link = "http://api.map.baidu.com/place/v2/search?"
link3 = "http://api.map.baidu.com/place/v2/suggestion?"
print("该脚本查询所想查找的地点")
region = input ("想要查询的地点,例如重庆:")
print("你可以选择你想查询的种类和地点关键字")
print("种类请输入'1',关键字请输入‘2’:",end = '')
h = input("")
h = str(h)
if h == '2':
query = input("地点关键字,例如“南坪”:")
link3 = link3 + 'query=' + quote(query) + '®ion=' + quote(region)+'&city_limit=true&output=json&ak=Mh1B541b7aRy9RumVsnl4Tylq9gTnveE'
return link3
else:
q = input("种类关键字,例如“铁板烧”,“汽车站银行”:")
link2 = link + 'q=' + quote(q) + '®ion=' + quote(region)+ '&output=json&ak=Mh1B541b7aRy9RumVsnl4Tylq9gTnveE'
return link2
def deal():
message = json.loads(APIlink(main()))
little = message.get("results")
if little is not None:
for key in little:
print("名字:",key["name"],"地点:",key["address"])
else:
little2 = message.get("result")
for key in little2:
print("名字",key["name"],"地点",key["city"],key["district"])
if __name__=='__main__':
deal()
|
ed8662f10f2e3e8da4d06025447f8f45f21dcbc1 | molendzik/AdventOfCode2020Python | /Day 4/Solution 7/main.py | 2,055 | 3.59375 | 4 | #read file and convert content to a list of lines
with open("input.txt", "r") as file:
data = file.readlines()
#define function that will merge correct strings and remove empty ones
def merge_items(list):
first_index = list.index(" ")
list.remove(" ")
if first_index < len(list) - 1 and " " in list:
second_index = list.index(" ")
while second_index > first_index + 1:
list[first_index] = list[first_index] + list[first_index + 1]
list.pop(first_index + 1)
second_index -= 1
elif first_index == len(list) - 1:
list.pop(-1)
#remove \n from strings
for index, line in enumerate(data):
line = line.replace("\n", " ")
data[index] = line
#convert list to useable strings
data.append(" ") #marks the end of data for merge_items() and gets removed at the end
while " " in data:
merge_items(data)
#byr, iyr, eyr, hgt, hcl, ecl, pid, cid
template1 = [1, 1, 1, 1, 1, 1, 1, 0]
template2 = [1, 1, 1, 1, 1, 1, 1, 1]
valid_counter = 0
#split each document (passport) and check for correct field types
for document in data:
fields = document.split(" ")
fields.pop(-1) #remove whitespace at the end of each document (which was used to separate them)
print(fields)
type_counter = [0, 0, 0, 0, 0, 0, 0, 0]
for exact_field in fields:
type = exact_field.split(":", 8)
print(type)
if "byr" in type:
type_counter[0] = 1
if "iyr" in type:
type_counter[1] = 1
if "eyr" in type:
type_counter[2] = 1
if "hgt" in type:
type_counter[3] = 1
if "hcl" in type:
type_counter[4] = 1
if "ecl" in type:
type_counter[5] = 1
if "pid" in type:
type_counter[6] = 1
if "cid" in type:
type_counter[7] = 1
print(type_counter)
if type_counter == template1 or type_counter == template2:
print("Found a valid passport.")
valid_counter += 1
print("Solution:", valid_counter) |
3990466f9db63e85f9c63f55fb2fe6f754d91a39 | Ahead180-103/ubuntu | /python/shell.py/02_string.py | 349 | 4.0625 | 4 | #!/usr/bin/python3
'''
输入任意字符串,判断这个字符串是不是回文
回文是指中心对称的文字
如:
上海自来水来自海上
abcba
'''
s=input("请输入字符串:")
reverse_string = s[::-1] #把字符反过来
print(reverse_string)
if reverse_string == s:
print(s,"是回文")
else:
print(s,"不是回文")
|
f71095b64b8ab9df1cb036aa3a18ad1cc10ec4b9 | vaishali-khilari/COMPETITIVE-PROGRAMMING | /leetcode/Sorted matrix .py | 1,139 | 4.4375 | 4 | Given an NxN matrix Mat. Sort all elements of the matrix.
Example 1:
Input:
N=4
Mat=[[10,20,30,40],
[15,25,35,45]
[27,29,37,48]
[32,33,39,50]]
Output:
10 15 20 25
27 29 30 32
33 35 37 39
40 45 48 50
Explanation:
Sorting the matrix gives this result.
Example 2:
Input:
N=3
Mat=[[1,5,3],[2,8,7],[4,6,9]]
Output:
1 2 3
4 5 6
7 8 9
Explanation:
Sorting the matrix gives this result.
Your Task:
You don't need to read input or print anything. Your task is to complete the function sortedMatrix() which takes the integer N and the matrix Mat as input parameters and returns the sorted matrix.
code:-
class Solution:
def sortedMatrix(self,N,mat):
total=N *N
op=[]
for i in mat:
for j in i:
op.append(j)
op.sort()
res=[]
x=[]
p=0
q=N
while total:
for i in range(p,q):
res.append(op[i])
x.append(res)
res=[]
p+=N
q+=N
total-=N
return x
|
ff4ba374d423f15a1fc1cf541abdbd8b414fb7b3 | cmdbdu/little | /piglatin.py | 813 | 3.703125 | 4 | #coding:utf8
import string
# 接受输入的字符串
# 判断是否是单词
# 是否有辅音
# 组词
def piglatin():
self_sound = ['a', 'e', 'i', 'o', 'u']
s = raw_input('Input something please!\n')
words = s.split()
new_words = ''
for word in words:
tmp_word = word.lower()
position = []
for i in range(len(tmp_word)):
if tmp_word[i] in self_sound:
pass
#elif tmp_word[i].isdigit(): #TODO
# break
else:
position.append(i)
tmp_word = tmp_word[:position[0]] +\
tmp_word[position[0]+1:] +\
tmp_word[position[0]]+'ay'
new_words += tmp_word + ' '
print new_words
if __name__ == "__main__":
piglatin()
|
a52f62da1239defdfdf3bfc2c4816205ac9c7e34 | mintisan/dsp-examples | /machine-learning-with-signal-processing-techniques/auto-correlation_in_python.py | 1,308 | 3.640625 | 4 | # http://ataspinar.com/2018/04/04/machine-learning-with-signal-processing-techniques/
# The auto-correlation function calculates the correlation of a signal with a time-delayed version of itself.
# The idea behind it is that if a signal contain a pattern which repeats itself after a time-period of \tau seconds,
# there will be a high correlation between the signal and a \tau sec delayed version of the signal.
import numpy as np
import matplotlib.pyplot as plt
t_n = 10
N = 1000
T = t_n / N
f_s = 1 / T
x_value = np.linspace(0, t_n, N)
amplitudes = [4, 6, 8, 10, 14]
frequencies = [6.5, 5, 3, 1.5, 1]
y_values = [amplitudes[ii] * np.sin(2 * np.pi * frequencies[ii] * x_value) for ii in range(0, len(amplitudes))]
composite_y_value = np.sum(y_values, axis=0)
def autocorr(x):
result = np.correlate(x, x, mode='full')
return result[len(result)//2:]
def get_autocorr_values(y_values, T, N, f_s):
autocorr_values = autocorr(y_values)
x_values = np.array([T * jj for jj in range(0, N)])
return x_values, autocorr_values
t_n = 10
N = 1000
T = t_n / N
f_s = 1/T
t_values, autocorr_values = get_autocorr_values(composite_y_value, T, N, f_s)
plt.plot(t_values, autocorr_values, linestyle='-', color='blue')
plt.xlabel('time delay [s]')
plt.ylabel('Autocorrelation amplitude')
plt.show() |
61bef90211ffd18868427d3059e8ab8dee3fefde | kami71539/Python-programs-4 | /Program 25 Printing text after specific lines.py | 303 | 4.15625 | 4 | #Printing text after specific lines.
text=str(input("Enter Text: "))
text_number=int(input("Enter number of text you'd like to print; "))
line_number=1
for i in range(0,text_number):
print(text)
for j in range(0,line_number):
print("1")
line_number=line_number+1
print(text) |
4099fd2a5412344e11f6270d1c751d7d7cb4b7d1 | junyoung-o/PS-Python | /by date/2021.02.18/1874.py | 1,662 | 3.703125 | 4 | from typing import Sequence
n = int(input())
sequence = []
result = None
candidate = None
class Stack():
def __init__(self):
self.s = []
self.size = 0
def is_empty(self):
if(self.size == 0):
return True
return False
def push(self, target):
self.s.append(target)
self.size += 1
def pop(self):
if(self.is_empty()):
return -1
self.size -= 1
return self.s.pop()
def define_stack():
global result, candidate
result = Stack()
candidate = Stack()
def set_sequence():
global sequence
import sys
for _ in range(n):
sequence.append(int(sys.stdin.readline()))
def init():
define_stack()
set_sequence()
return
def get_result():
point = 0
result_list = []
for num in range(1, n+1):
candidate.push(num)
result_list.append("+")
if(num == sequence[point]):
while(True):
target = candidate.pop()
if(point < n and target == sequence[point]):
result.push(target)
result_list.append("-")
point += 1
else:
if(target != -1):
candidate.push(target)
break
if(candidate.size != 0):
return "NO"
return result_list
def print_result(result_list):
if(result_list == "NO"):
print(result_list)
else:
[print(r, end="\n") for r in result_list]
def main():
print_result(get_result())
return
if(__name__=="__main__"):
init()
main() |
4eb376be35f50b426d5c180f806e58d060ae7911 | Jingleolu/learn-python | /day3/triangle.py | 283 | 3.578125 | 4 | """
判断输入边长能否构成三角形,如果能则计算出三角形的周长和面积
"""
a, b, c = map(int, input('请输入三条边长:').split())
if a+b > c and a+c > b and b+c > a:
print('三角形的周长为%d' % (a+b+c))
else:
print('不能组成三角形') |
6e49f8327734e7d9ae784662a9fdf8bd827f34ae | coderlzy/python- | /比赛训练7天/day1字符串/批量替换字符串.py | 229 | 3.59375 | 4 | while True:
try:
str1=input("请输入一个字符串:")
#手动替换
list1=list(str1)
for i in range(len(list1)):
if list1[i] is " ":
list1[i]="%20"
print("".join(list1[i]),end="")
except EOFError:
break
|
af6181886e558f7277bc98cc2f655e40cddce358 | GuilhermeEsdras/Estrutura-de-Dados | /em C/Exercícios Resolvidos/Exercícios URI Resolvidos/Lista Uri 1 - Revisao de Algoritmos/2415 - Consecutivos.py | 378 | 3.515625 | 4 | # -*- coding: utf-8 -*-
N = int(input())
num = [int(x) for x in input().split()]
maior_cont = 0
cont = 0
numero_anterior = 0
for i, v in enumerate(num):
if v == numero_anterior or i == 0:
numero_anterior = v
cont += 1
if cont >= maior_cont:
maior_cont = cont
else:
numero_anterior = v
cont = 1
print(maior_cont)
|
bdfa7c4a9cb85fe1bd2bb4b073f9fb6de6ff85c0 | aleri-a/Artificial-Intelligence_MDH | /1.2 GBF Astar/main.py | 4,529 | 3.546875 | 4 | #A* abnd greedy-best first
# Malaga to Valladolid
'''
Implementation:Order the nodes in the stack in decreasing order of desirability
greedy best ->f(n) = h(n)
A*-> f(n) = g(n) + h(n)
pazi g(n) ti je duzina prethodnih puteva + duzina novi put
'''
from queue import PriorityQueue
import time
class MyPriorityQueue(PriorityQueue):
def _put(self, item):
return super()._put((self._get_priority(item), item))
def _get(self):
return super()._get()
def _get_priority(self, item):
return int(item.fja)
class MyPriorityQueue2:
def __init__(self):
self.queue=[]
def Put(self,element):
self.queue.append(element)
self.queue.sort(key=lambda x: int(x.fja), reverse=False)
def Get(self):
return self.queue.pop(0)
def Empty(self):
if(len(self.queue)==0):
return True
else:
return False
class Neighbord:
def __init__(self,parent,name,cost):
self.cost=cost
self.parrent=parent
self.name=name
def printDetails(self):
print (self.name)
class Node:
def __init__(self,parent,name,fja,cost):
self.name=name
self.parent=parent
self.fja=fja
self.cost=cost
def ReadFile():
graph={ }
heuristicTable ={ }
f=open('input.txt','r')
pomNum=-1
while(pomNum==-1 ):
pomStr=f.readline()
pomNum=pomStr.find("COMMENT:")
start=pomStr.find("COMMENT:")+len("COMMENT:")+1
end=pomStr.find(" ",start)
num=""
while(start<=end):
num=num+pomStr[start]
start+=1
num=int(num)
f.readline()
f.readline()
line=f.readline()
while line !='\n':
if 'Salamanca Caceres' in line:
print('here')
words=line.replace("\t",' ').split(' ')
words[2]=words[2][0:len(words[2])-1]#0:len(words[2])-1
neig=Neighbord(words[0],words[1],words[2])
if words[0] not in graph.keys():
graph.setdefault(words[0],[]).append(neig)
else:
graph[words[0]].append(neig)
neigThis=Neighbord(words[1],words[0],words[2])
if words[1] not in graph.keys():
graph.setdefault(words[1],[]).append(neigThis)
else:
graph[words[1]].append(neigThis)
line=f.readline()
f.readline()
f.readline()
line=f.readline()
while line !='':
words=line.split(' ')
if '\n' in words[1]:
words[1]=words[1][0:len(words[1])-1]
heuristicTable[words[0]]=words[1]
line=f.readline()
return graph,heuristicTable
def CheckRepetition(childsNode,parent): #da li ima prethodnike tj da se nevrti u krug
while(parent!=None):
for ch in childsNode:
if(parent.name==ch.name):
childsNode.remove(ch)
parent=parent.parent
return childsNode
def GBF(graph,hTable,start,end):
currNode=Node(None,start,int(hTable[start]),0)
q = MyPriorityQueue2()
q.Put(currNode)
while not q.Empty():
elNode=q.Get()
if elNode.name==end:
return elNode
childs=graph[elNode.name]
childs=CheckRepetition(childs,elNode)
for ch in childs:
child=Node(elNode,ch.name,int(hTable[ch.name]),int(ch.cost)+elNode.cost)
q.Put(child)
def Astar(graph,hTable,start,end):
currNode=Node(None,start,int(hTable[start]),0)
q = MyPriorityQueue2()
q.Put(currNode)
while not q.Empty():
elNode=q.Get()
if elNode.name==end:
return elNode
childs=graph[elNode.name]
childs=CheckRepetition(childs,elNode)
for ch in childs:
child=Node(elNode,ch.name,int(hTable[ch.name])+int(ch.cost)+elNode.cost,int(ch.cost)+elNode.cost)
q.Put(child)
print(q)
def printPath(start):
print("Real path= ",start.cost)
res=start.name
start=start.parent
while start != None :
res+=" "+start.name
start=start.parent
print(res)
graph, hTable=ReadFile()
print("_________GBF: ")
startT=time.time()
rez=GBF(graph,hTable,"Malaga","Valladolid")
endT=time.time()
gbfTime=endT-startT
print(gbfTime,"seconds")
printPath(rez)
print("_________ A* ")
startT=time.time()
rez=Astar(graph,hTable,"Malaga","Valladolid")
endT=time.time()
astTime=startT-endT
print(endT-startT,"seconds")
printPath(rez)
#print("A*/GBF =",float(astTime/gbfTime ))
|
c75ff5bce9ac25b82fdae6d6d568b3682a5c58b8 | Agnes-Wambui/ProjectEuler | /Project Euler/P14:Longest Collatz sequence.py | 704 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 27 16:14:45 2018
@author: thejumpingspider
"""
maximum_length = 0
for i in range (10,1000000):
j = i
collatz_sequence = []
while j > 1:
collatz_sequence.append(j)
if j%2 == 0:
j = j/2
collatz_sequence.append(j)
else:
j = 3*j+1
collatz_sequence.append(j)
length_of_sequence = len(collatz_sequence)
if length_of_sequence > maximum_length:
maximum_length = length_of_sequence
maximum_dict = {}
maximum_dict[i] = maximum_length
print (maximum_dict)
|
9d8889ea4a3c3568983cd986075c10bc214673a6 | kaczorrrro/CS231N-2017-Spring | /assignment1/cs231n/classifiers/softmax.py | 4,248 | 3.703125 | 4 | import numpy as np
import math
from random import shuffle
from past.builtins import xrange
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength
Returns a tuple of:
- loss as single float
- gradient with respect to weights W; an array of same shape as W
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
#############################################################################
# TODO: Compute the softmax loss and its gradient using explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
out = X@W
num_examples, num_classes = out.shape
for i in range(num_examples):
exped = np.exp(out[i])
exp_sum = np.sum(exped)
all_scores = exped/exp_sum
for j in range(num_classes):
dW[:, j]+=all_scores[j]*X[i]
if j==y[i]:
dW[:, j]-= X[i]
loss+= -np.log( all_scores[y[i]] );
loss/=num_examples
dW/=num_examples
loss += 0.5* reg * np.sum(W * W)
dW += reg*W
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorized version.
Inputs and outputs are the same as softmax_loss_naive.
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
#############################################################################
# TODO: Compute the softmax loss and its gradient using no explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
out = X@W
num_examples, num_classes = out.shape
exped = np.exp(out)
exp_sum = np.sum(exped, 1).reshape((-1,1))
all_scores = exped/exp_sum
right_class_scores = all_scores[np.arange(num_examples), y];
loss = -np.sum(np.log(right_class_scores))/num_examples
all_scores[np.arange(num_examples), y] -= 1
dW += X.T@all_scores/num_examples
loss += 0.5* reg * np.sum(W * W)
dW+=W*reg
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
class Softmax:
def __init__(self, W):
self.W = W
def train(self, X, y, epochs, lr, batch_size, reg, verbose):
num_examples = X.shape[0]
# p = np.random.permutation(num_examples)
# X = X[p]
# y = y[p]
for epoch in range(epochs):
avg_loss = 0
for i in range(0,num_examples, batch_size):
batch_start = i
batch_end = min(batch_start+batch_size, num_examples)
x_batch = X[batch_start:batch_end]
y_batch = y[batch_start:batch_end]
loss, dW = softmax_loss_vectorized(self.W, x_batch, y_batch, reg)
avg_loss+=loss
self.W -= lr*dW
avg_loss/= math.ceil(num_examples/batch_size)
if epoch%verbose==0:
print("Epoch {}, avg loss: {}".format(epoch, avg_loss))
def classify(self, X):
out = [email protected]
return out
def predict(self, X):
out = [email protected]
return np.argmax(out, axis=1)
|
ddb4d8fe8179c162014a5e7d2adc2739fe389f2b | changooman/HeyThatsMyFish | /version-three-tehuacana/Fish/Player/strategy.py | 7,351 | 4.125 | 4 | from Fish.Common.game_tree import GameTreeNode
class Strategy():
"""A Fish game-playing strategy that can place penguins
and make moves for any player in the game.
"""
def make_placement(self, state):
"""Places a penguin on the game board for the current player.
Attempts to place in the lowest numbered row, then in the lowest numbered column.
Assumes that the game board is large enough to accommodate all penguins.
Will do nothing if no open tile is available.
state: The game State to place the penguin in.
returns: The coordinates of an avatar placement (row, col), None if no placement can be made.
"""
color = state.whose_turn().get_color()
board = state.get_board()
for r in range(board.get_rows()):
for c in range(board.get_cols()):
if state.valid_placement((r, c), color):
return (r, c)
return None
def __get_path(self, node):
"""Debugging function to get the moves leading up to a GameTreeNode.
node: The GameTreeNode to print the path of.
returns: A string of moves.
"""
path = ""
while node.get_parent():
path = "<" + str(node.get_parent_move()) + ">, " + path
node = node.get_parent()
return path
def __minimax_val_helper(self, children, curr_color, n, is_max_turn):
"""Helper function to compute the minimax value. Will compute the minimax
value or either the maximizing player or one of the minimizing players,
depending on what is specified.
children (list): the a list of GameTreeNode that are the evaluated children
of the node we are calculating the minimax value for.
curr_color (str): the color of the player to perform minimax for.
n (int): the depth of the search tree to search.
is_max_turn (bool): True if the parent of the child nodes is the maximizing player,
False otherwise.
returns (int): the minimax value for the parent of the given child nodes
"""
if is_max_turn:
max_val = float('-inf')
for child in children:
val = self.__minimax_val(child, curr_color, n-1)
if val > max_val:
max_val = val
return max_val
else:
min_val = float('inf')
for child in children:
val = self.__minimax_val(child, curr_color, n)
if val < min_val:
min_val = val
return min_val
def __minimax_val(self, node, curr_color, n):
"""Compute the minimax value for this state in the game tree.
tree (GameTreeNode): the game tree node to start at
curr_color (str): the color of the player to perform minimax for.
n (int): the depth of the search tree to search.
returns (int): the minimax value for this state in the game tree.
"""
state = node.get_state()
if state.is_game_over() or n == 0:
players = state.get_players()
player = [p for p in players if p.get_color() == curr_color][0]
return player.get_score()
# the parent moves of these children are from players with the color of
# state.whose_turn().get_color()
children = node.get_children()
if len(children) == 0:
state.pass_turn_if_applicable()
new_node = GameTreeNode(state)
return self.__minimax_val(new_node, curr_color, n)
is_max_turn = state.whose_turn().get_color() == curr_color
return self.__minimax_val_helper(children, curr_color, n, is_max_turn)
def __minimax(self, tree, curr_color, n):
"""Perform minimax from the state in the given tree, for the player
of the given color. Search the game tree for a depth of `n`.
tree (GameTreeNode): the game tree node to start at
curr_color (str): the color of the player to perform minimax for.
n (int): the depth of the search tree to search.
"""
children = tree.get_children()
max_val = float('-inf')
best = []
for i, child in enumerate(children):
new_val = self.__minimax_val(child, curr_color, n-1)
if new_val > max_val:
max_val = new_val
best = [child.get_parent_move()]
elif new_val == max_val:
best.append(child.get_parent_move())
return best
@staticmethod
def __filter(moves, key):
"""Helper method to find the smallest value of a specific value of a move in the
list of moves.
moves (list): a list of moves in the form ((from_row, from_col), (to_row, to_col))
key (function): the function used to get the specific value from move. This function should
take in a move in the form ((from_row, from_col), (to_row, to_col)) and return an integer.
return (list): a list of moves with the lowest value specified by the given key
"""
lowest_by_key_num = key(min(moves, key=key))
lowest_by_key_pos = list(filter(lambda x: key(x) == lowest_by_key_num, moves))
return lowest_by_key_pos
def __break_tie(self, moves):
"""Iterate through the list of moves and find the move with:
* the smallest row value in the source coordinate.
* the smallest col value in the source coordinate.
* the smallest row value in the target corrdinate.
* the smallest col value in the target coordinate.
moves (list): a list of moves ((from_row, from_col), (to_row, to_col))
returns: The coordinates of a move ((from_row, from_col), (to_row, to_col))
"""
# filter by best 'from' tile
lowest_from_row = self.__filter(moves, lambda x: x[0][0])
if len(lowest_from_row) == 1:
return lowest_from_row[0]
lowest_from_col = self.__filter(lowest_from_row, lambda x: x[0][1])
if len(lowest_from_col) == 1:
return lowest_from_col[0]
# filter by best 'to' tile
lowest_to_row = self.__filter(lowest_from_col, lambda x: x[1][0])
if len(lowest_to_row) == 1:
return lowest_to_row[0]
lowest_to_col = self.__filter(lowest_to_row, lambda x: x[1][1])
return lowest_to_col[0]
def make_move(self, state, n):
"""Make a move based on the best possible gain after n turns of the current
player, assuming all opponents choose moves that minimize our gain.
state: The game State to make the move in.
n: The number of turns to look ahead, must be > 0.
returns: The coordinates of a move ((from_row, from_col), (to_row, to_col)), None if no move can be made
"""
if n <= 0:
raise ValueError("n must be > 0.")
p_color = state.whose_turn().get_color()
tree = GameTreeNode(state)
best = self.__minimax(tree, p_color, n)
if len(best) == 0:
return None
elif len(best) == 1:
return best[0]
else:
return self.__break_tie(best)
|
4cf77b7fd2d6f7dbce6630089dbda1fb98e07a70 | ChrisWaites/data-deletion | /src/desc_to_del/clean_data.py | 8,683 | 3.5625 | 4 | import numpy as np
import pandas as pd
# documentation
# output: clean data set, remove missing values and convert categorical values to binary, extract sensitive features
# for each data set 'name.csv' we create a function clean_name
# clean name takes parameter num_sens, which is the number of sensitive attributes to include
# clean_name returns pandas data frames X, X_prime, where:
# X is the full data set of X values
# X_prime is only the sensitive columns of X
# y are the binary outcomes
def l2_norm(col):
return np.sqrt(np.sum(np.power(col, 2)))
def center(X):
for col in X.columns:
X.loc[:, col] = X.loc[:, col]-np.mean(X.loc[:, col])
return X
def standardize(X):
for col in X.columns:
X.loc[:, col] = X.loc[:, col]/np.sqrt(np.var(X.loc[:, col]))
return X
def max_row_norm(X):
return np.max([l2_norm(row) for index, row in X.iterrows()])
def normalize_rows(X):
max_norm = max_row_norm(X)
return X/max_norm
def add_intercept(X):
"""Add all 1's column to predictor matrix"""
X['intercept'] = [1]*X.shape[0]
return X
def one_hot_code(df1, sens_dict):
cols = df1.columns
for c in cols:
if isinstance(df1[c][0], str):
column = df1[c]
df1 = df1.drop(c, 1)
unique_values = list(sorted(set(column)))
n = len(unique_values)
if n > 2:
for i in range(n):
col_name = '{}.{}'.format(c, i)
col_i = [1 if el == unique_values[i] else 0 for el in column]
df1[col_name] = col_i
sens_dict[col_name] = sens_dict[c]
del sens_dict[c]
else:
col_name = c
col = [1 if el == unique_values[0] else 0 for el in column]
df1[col_name] = col
return df1, sens_dict
def clean_mnist(d =16, scale_and_center=True, intercept=False, normalize=True, samprate = 1):
X = pd.read_csv('dataset/mnist_data/n=10000_d={}/X_test.csv'.format(d))
X = X.sample(frac=samprate)
sampled_indices = X.index
X = X.reset_index(drop = True)
y = pd.read_csv('dataset/mnist_data/n=10000_d={}/y_test.csv'.format(d))
y = y.iloc[sampled_indices,:]
y = pd.Series(2*y.iloc[:,0] - 1)
y = y.reset_index(drop=True)
if scale_and_center:
X = center(X)
X = standardize(X)
if intercept:
X = add_intercept(X)
if normalize:
X = normalize_rows(X)
return X, y
# center data frame columns for visual purposes
def clean_communities(scale_and_center=True, intercept=True, normalize=True):
"""Clean communities & crime data set."""
# Data Cleaning and Import
df = pd.read_csv('dataset/communities.csv')
df = df.fillna(0)
y = df['ViolentCrimesPerPop']
q_y = np.percentile(y, 70)
# convert y's to binary predictions on whether the neighborhood is
# especially violent
y = [np.sign(s - q_y) for s in y]
# hot code categorical variables
sens_df = pd.read_csv('dataset/communities_protected.csv')
sens_cols = [str(c) for c in sens_df.columns if sens_df[c][0] == 1]
print('sensitive features: {}'.format(sens_cols))
sens_dict = {c: 1 if c in sens_cols else 0 for c in df.columns}
df, _ = one_hot_code(df, sens_dict)
X = df.iloc[:, 0:122]
if scale_and_center:
X = center(X)
X = standardize(X)
if intercept:
X = add_intercept(X)
if normalize:
X = normalize_rows(X)
return X, pd.Series(y)
# num_sens in 1:17
def clean_lawschool(scale_and_center=True, intercept=True, normalize=True):
"""Clean law school data set."""
# Data Cleaning and Import
df = pd.read_csv('dataset/lawschool.csv')
df = df.dropna()
# convert categorical column variables to 0,1
df['gender'] = df['gender'].map({'female': 1, 'male': 0})
# remove y from df
df_y = df['bar1']
df = df.drop('bar1', 1)
y = [2*int(a == 'P')-1 for a in df_y]
y = pd.Series(y)
sens_df = pd.read_csv('dataset/lawschool_protected.csv')
sens_cols = [str(c) for c in sens_df.columns if sens_df[c][0] == 1]
sens_dict = {c: 1 if c in sens_cols else 0 for c in df.columns}
# one hot coding of race variable
for i in range(1, 9):
col_name = 'race{}'.format(i)
if 'race' in sens_cols:
sens_dict[col_name] = 1
else:
sens_dict[col_name] = 0
race_code = [np.int(r == i) for r in df['race']]
df[col_name] = race_code
sens_dict['race'] = 0
df = df.drop('race', 1)
sens_names = [key for key in sens_dict.keys() if sens_dict[key] == 1]
print('there are {} sensitive features including derivative features'.format(len(sens_names)))
x_prime = df[sens_names]
df.index = range(len(df))
x_prime.index = range(len(x_prime))
X = df
if scale_and_center:
X = center(X)
X = standardize(X)
if intercept:
X = add_intercept(X)
if normalize:
X = normalize_rows(X)
return X, pd.Series(y)
def clean_synthetic(num_sens):
"""Clean synthetic data set, all features sensitive, y value is last col."""
df = pd.read_csv('dataset/synthetic.csv')
df = df.dropna()
y_col = df.shape[1]-1
y = df.iloc[:, y_col]
df = df.iloc[:, 0:y_col]
x_prime = df.iloc[:, 0:num_sens]
return df, x_prime, y
def clean_adult_full(scale_and_center=True, intercept=True, normalize=True, samprate = 1.0):
df = pd.read_csv('dataset/adult_full.csv') #full adult data
df = df.sample(frac=samprate, random_state=0).reset_index(drop=True) #subsample
df = df.dropna()
# binarize and remove y value
df['income'] = df['income'].map({'<=50K': -1, '>50K': 1})
y = df['income']
df = df.drop('income', 1)
# hot code categorical variables
sens_df = pd.read_csv('dataset/adult_protected.csv')
sens_cols = [str(c) for c in sens_df.columns if sens_df[c][0] == 1]
sens_dict = {c: 1 if c in sens_cols else 0 for c in df.columns}
X, sens_dict = one_hot_code(df, sens_dict)
if scale_and_center:
X = center(X)
X = standardize(X)
if intercept:
X = add_intercept(X)
if normalize:
X = normalize_rows(X)
return X, pd.Series(y)
def clean_adult(scale_and_center=True, intercept=True, normalize=True):
df = pd.read_csv('dataset/adult.csv')
df = df.dropna()
# binarize and remove y value
df['income'] = df['income'].map({' <=50K': -1, ' >50K': 1})
y = df['income']
df = df.drop('income', 1)
# hot code categorical variables
sens_df = pd.read_csv('dataset/adult_protected.csv')
sens_cols = [str(c) for c in sens_df.columns if sens_df[c][0] == 1]
sens_dict = {c: 1 if c in sens_cols else 0 for c in df.columns}
X, sens_dict = one_hot_code(df, sens_dict)
if scale_and_center:
X = center(X)
X = standardize(X)
if intercept:
X = add_intercept(X)
if normalize:
X = normalize_rows(X)
return X, pd.Series(y)
def clean_adultshort():
df = pd.read_csv('dataset/adultshort.csv')
df = df.dropna()
# binarize and remove y value
df['income'] = df['income'].map({' <=50K': 0, ' >50K': 1})
y = df['income']
df = df.drop('income', 1)
# hot code categorical variables
sens_df = pd.read_csv('dataset/adultshort_protected.csv')
sens_cols = [str(c) for c in sens_df.columns if sens_df[c][0] == 1]
print('sensitive features: {}'.format(sens_cols))
sens_dict = {c: 1 if c in sens_cols else 0 for c in df.columns}
df, sens_dict = one_hot_code(df, sens_dict)
sens_names = [key for key in sens_dict.keys() if sens_dict[key] == 1]
print('there are {} sensitive features including derivative features'.format(len(sens_names)))
x_prime = df[sens_names]
x = center(df)
x_prime = center(x_prime)
return x, x_prime, y
# currently 6 sensitive attributes
def clean_student():
df = pd.read_csv('dataset/student-mat.csv', sep=';')
df = df.dropna()
y = df['G3']
y = [0 if y < 11 else 1 for y in y]
df = df.drop(['G3', 'G2', 'G1'], 1)
sens_df = pd.read_csv('dataset/student_protected.csv')
sens_cols = [str(c) for c in sens_df.columns if sens_df[c][0] == 1]
print('sensitive features: {}'.format(sens_cols))
sens_dict = {c: 1 if c in sens_cols else 0 for c in df.columns}
df, sens_dict = one_hot_code(df, sens_dict)
sens_names = [key for key in sens_dict.keys() if sens_dict[key] == 1]
print('there are {} sensitive features including derivative features'.format(len(sens_names)))
x_prime = df[sens_names]
return df, x_prime, pd.Series(y)
|
3d064e6585be43f39b01bc2b7ffcf7a32a08379b | Sleeither1234/t10-HUATAY.CHUNGA | /huatay/CLI2.py | 4,498 | 4.03125 | 4 | #ejercicio 02
# se muestra las funciones dependiendo la opcion elejida
def suma():
#asignacion de valores dentro de la funcion
primer_numero=libreria.validar_numero(input("Ingrese el primer valor "))
segundo_numero=libreria.validar_numero(input("Ingrese el segundo valor"))
#realizacion del calculo de los valores dados
suma=(int(primer_numero)+int(segundo_numero))
#se imprimer un mensaje con el resultado y se pregunta al usuario si desea guardar los datos
print("La suma de los valores dados es : "+str(suma))
print("Desea guardar este dato?")
valor=int(input("SI(1) o NO(0)"))
#condicional multiple
if valor==1:
#SE ABRE UN ARCHIVO , SE GUARDA EL DATO , SE IMPRIME UN MENSAJE EN EL CUAL SE GUARDA LOS DATOS Y SE CIERRA EL ARCHIVO
archivo=open("CLI2.txt","a")
archivo.write("el valor de la suma de los numeros "+primer_numero+" y "+segundo_numero+"es :"+str(suma))
print("se han guardado los datos correctamente")
archivo.close()
#SI EL VALOR ES IGUAL A 0 ENTONCES NO SE GUARDARA NINGUN DATO
elif valor==0:
print("OK, no se guardara nigun dato")
#SI EL VALOR ES DIFERENTE APARECERA UN MENSAJE QUE EL VALOR ES FALSA Y LO REGRESARA AL MENU
else:
print("EL VALOR INGRESADO ES FALSO")
#Y asi con las demas funciones tienen la misma estructura
def resta():
primer_valor=libreria.validar_numero(input("Ingrese el primer valor: "))
segundo_valor=libreria.validar_numero(input("Ingrese el segundo valor"))
resta=int(primer_valor)-int(segundo_valor)
print("La resta de los valores dados es: "+str(resta))
print("Desea guardar el resultado de la resta?")
valor=int(input("SI(1) O NO(0)"))
if valor==1:
archivo=open("CLI2.txt","a")
archivo.write("El valor de la resta de los valores "+primer_valor+" y "+segundo_valor+" es: "+str(resta))
print("se han guardado los datos correctamente")
archivo.close()
elif valor==0:
print("OK no se guardaran los datos")
else:
print("EL NUMERO INGRESADO ES FALSO")
def multiplicacion():
digit1=libreria.validar_numero(input("Ingrese el primer valor: "))
digit2=libreria.validar_numero(input("Irgrese el segundo valor: "))
multiplicacion=int(digit1)*int(digit2)
print("La multiplicacion de los valores dados: "+str(multiplicacion))
print("Desea guardar el resultado de la multiplicacion?")
ingrese=int(input("Si(1) o No(0)?"))
if ingrese==1:
archivo=open("CLI2.txt","a")
archivo.write("El valor de la multiplicacion de los valores "+digit1+" y "+digit2 +" es: "+str(multiplicacion))
print("Se han guardado los datos correctamente")
archivo.close()
elif ingrese==0:
print("Ok no se guardaran los datos")
else:
print("Se ha ingresado un valor invalido")
def division():
valor_1=libreria.validar_numero(input("Ingrese el primer valor: "))
valor_2=libreria.validar_numero(input("Ingrese el segundo valor: "))
division=int(valor_1)/int(valor_2)
print("La division de los valores dados es: "+str(division))
print("Desea guardar el resultado de la division?")
ingrese=int(input("Si(1) o No(0)?"))
if ingrese==1:
archivo=open("CLI2.txt","a")
archivo.write("EL valor de la division de los valores "+valor_1+" y "+valor_2+" es:"+str(division))
archivo.close()
elif ingrese==0:
print("OK no se guardaran los datos")
else:
print("Se ha ingresado un valor invalido")
#importacion de la libreria
import libreria
# asig asignacion de variables int
opc=0
max=5
while opc!=max: #se asigna la funcion mientras la opc se adiferente del max seguira en el bucle
print("################CALCULADORA#################")
print("#1. Suma:suma 2 numeros #")
print("#2. Resta:resta 2 numeros #")
print("#3. Multiplicaion: multiplica 2 numeros #")
print("#4. Division: divide 2 numeros #")
print("#5. SALIR #")
print("############################################")
#se asigna la variable opcion la cual sera llamada desde la libreria para su validacion
opc = libreria.validar_int(input("ingrese un valor"))
#se seleccionara la funcion segun la opcion elejida
if opc==1:
suma()
if opc==2:
resta()
if opc==3:
multiplicacion()
if opc==4:
division()
|
5c35aa45664aed8a1595adf8183c11b4d95580c7 | Mohit130422/python-code | /35 reverse.py | 229 | 3.625 | 4 | #value rverse
def main():
n=int(input("enter no"))
rev=0
rem=0
while (n>0):
rem=n%10
rev=rev*10+rem
n = n//10
print("Rverse=",rev)
if __name__=="__main__":
main()
#run
|
e69781477eeb9c745e6f8edd7d8a6c6688351c3d | imjoung/hongik_univ | /_WSpython/Python06_06_DictionaryEx03_최임정.py | 277 | 3.609375 | 4 | dic={'name':'imjoung','phone':'01089960000','birth':'1009'}
print("이름은 : %s 입니다."% dic['name'])
print("핸드폰 번호는 : %s 입니다."%dic['phone'])
print("생일은 : %s 입니다."%dic['birth'])
print("="*15)
a={1:'a',1:'b'}
print(a)
print("="*15) |
fddcf8759b274b5da713d52759c9b4894e3013d5 | JoachimIsaac/Interview-Preparation | /LinkedLists/23MergeKSortedLists.py | 1,587 | 4.34375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
"""
UMPIRE:
Understand:
--> So we are going to recieve an array of linked lists as our input?yes
--> Can we use extra space?
--> What do we return ? a sorted linked list that has all the values
--> what if the input is empty or it only has one list? return None or the list
Match:
--> we can use a heap(sorted list class)
--> then we can loop over it and create a linked list like that
Plan:
--> declare sortedcontainers class and import SortedList
--> iterate through the array and load all the values of each list into the array
--> create the list and then return it
[
1->4->5,
1->3->4,
2->6
]
[1,1,2,3,4,4,5,6]
Evaluate:
Time complexity: O(N * K) where N is the number of list and K is the number of values in each list
Space complexity O(K)
Still need to learn optimal solution with heap
"""
from sortedcontainers import SortedList
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if len(lists) == 0:
return None
if len(lists) == 1:
return lists[0]
numbers = SortedList([])
for curr_list in lists:
curr = curr_list
while curr:
numbers.add(curr.val)
curr = curr.next
dummy = ListNode(-1)
result = dummy
for number in numbers:
dummy.next = ListNode(number)
dummy = dummy.next
return result.next
|
9caba39d4ee9df48e75b4dfceb85774fbdd80e43 | bakunobu/exercise | /1400_basic_tasks/chap_7/7_84.py | 290 | 3.671875 | 4 | from main_funcs import get_input
def count_pos(n:int, p:int=5) -> bool:
pos_count = 0
for _ in range(n):
a = get_input('Введите число: ', False)
if a >= 0:
pos_count += 1
if pos_count > p:
break
print(pos_count <= p) |
5035cb2fc2f7e9c501ed776f72f5f47d8ff3e141 | n0skill/AVOSINT | /libs/icao_converter.py | 2,913 | 3.78125 | 4 | base9 = '123456789' # The first digit (after the "N") is always one of these.
base10 = '0123456789' # The possible second and third digits are one of these.
# Note that "I" and "O" are never used as letters, to prevent confusion with "1" and "0"
base34 = 'ABCDEFGHJKLMNPQRSTUVWXYZ0123456789'
icaooffset = 0xA00001 # The lowest possible number, N1, is this.
b1 = 101711 # basis between N1... and N2...
b2 = 10111 # basis between N10.... and N11....
def suffix(rem):
""" Produces the alpha(numeric) suffix from a number 0 - 950 """
if rem == 0:
suf = ''
else:
if rem <= 600: #Class A suffix -- only letters.
rem = rem - 1
suf = base34[rem // 25]
if rem % 25 > 0:
suf = suf + base34[rem % 25 - 1]# second class A letter, if present.
else: #rems > 600 : First digit of suffix is a number. Second digit may be blank, letter, or number.
rem = rem - 601
suf = base10[rem // 35]
if rem % 35 > 0:
suf = suf + base34[rem % 35 - 1]
return suf
def enc_suffix(suf):
""" Produces a remainder from a 0 - 2 digit suffix.
No error checking. Using illegal strings will have strange results."""
if len(suf) == 0:
return 0
r0 = base34.find(suf[0])
if len(suf) == 1:
r1 = 0
else:
r1 = base34.find(suf[1]) + 1
if r0 < 24: # first char is a letter, use base 25
return r0 * 25 + r1 + 1
else: # first is a number -- base 35.
return r0 * 35 + r1 - 239
def icao_to_tail(icao):
if (icao < 0) or (icao > 0xadf7c7):
return "Undefined"
icao = icao - icaooffset
d1 = icao // b1
nnum = 'N' + base9[d1]
r1 = icao % b1
if r1 < 601:
nnum = nnum + suffix(r1) # of the form N1ZZ
else:
d2 = (r1 - 601) // b2 # find second digit.
nnum = nnum + base10[d2]
r2 = (r1 - 601) % b2 # and residue after that
if r2 < 601: # No third digit. (form N12ZZ)
nnum = nnum + suffix(r2)
else:
d3 = (r2 - 601) // 951 # Three-digits have extended suffix.
r3 = (r2 - 601) % 951
nnum = nnum + base10[d3] + suffix(r3)
return nnum
def tail_to_icao(tail):
if tail[0] != 'N':
return -1
icao = icaooffset
icao = icao + base9.find(tail[1]) * b1
if len(tail) == 2: # simple 'N3' etc.
return icao
d2 = base10.find(tail[2])
if d2 == -1: # Form N1A
icao = icao + enc_suffix(tail[2:4])
return icao
else: # Form N11... or N111..
icao = icao + d2 * b2 + 601
d3 = base10.find(tail[3])
if d3 > -1: #Form N111 Suffix is base 35.
icao = icao + d3 * 951 + 601
icao = icao + enc_suffix(tail[4:6])
return icao
else: #Form N11A
icao = icao + enc_suffix(tail[3:5])
return icao
|
6ffe4602847aa9e88c13a41ba9fcba2d040ec53c | jfxugithub/python | /函数式编程/匿名函数.py | 679 | 4.15625 | 4 | #!/usr/bin/evn python3.5
# -*- coding: utf-8 -*-
#匿名函数访问每一个生成的0-9序列,将结果组合成一个list
print("匿名函数的使用:")
print("求取0-9的平方list:",list(map(lambda x:x*x,list(range(0,10)))))
'''
匿名函数的语法:
lambda 参数:表达式 #(表达式中的变量必须是参数中的,且表达式只能有一个)
lambda:表示匿名函数的关键字
x :表示入参
x*x :表示表达式
'''
#匿名函数也可以作为返回值赋值给变量
is_odd = lambda n : n % 2 == 1
print("匿名函数作为返回值的使用:")
print("提取0-10之间的奇数:",list(filter(is_odd,list(range(0,10)))))
|
68290a3beff7dd6825bea0d9aca023584c84ef84 | gslmota/Programs-PYTHON | /Exercícios/Mundo 2/ex060.py | 648 | 3.703125 | 4 | # Cadastro de Pessoas
tp = th = tm = 0
while True:
idade = int(input('Digite a sua idade:'))
sexo = ' '
while sexo not in 'FM':
sexo = str(input('Digite o seu sexo: ')).strip().upper()[0]
if idade >= 18:
tp += 1
if sexo == 'M':
th += 1
if sexo == 'F' and idade < 20:
tm += 1
resp = ' '
while resp not in 'SN':
resp = str(input('Quer Continuar? [S/N]')).strip().upper()[0]
if resp == 'N':
break
print('Acabou!!!')
print(f'Total de pessoas com mais de 18 anos: {tp}')
print(f'Total de homes cadastrados {th}')
print(f'Total de mulheres com menos de 20 anos {tm}')
|
fb113957ae9d3359c436c5a578fafde8210888ba | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/sttbar001/question2.py | 694 | 4.09375 | 4 | money =0
cost =0
cost = eval(input("Enter the cost (in cents): \n"))
while money < cost:
money = (eval(input("Deposit a coin or note (in cents): \n")))+money
change = money-cost
if change!= 0:
print("Your change is:")
doll1 = int(change/100)
if doll1 >0:
print(str(doll1)+" x $1")
change = change - (doll1*100)
doll2 = int(change/25)
if doll2 >0:
print(str(doll2)+" x 25c")
change = change - (doll2*25)
doll3 = int(change/10)
if doll3 >0:
print(str(doll3)+" x 10c")
change = change - (doll3*10)
doll4 = int(change/5)
if doll4 >0:
print(str(doll4)+" x 5c")
change = change - (doll4*5)
if change >0:
print(str(change)+ " x1c") |
61417cf678356138b1353b656347f8a137e139de | AKShaw/PyBot | /algorithms.py | 2,078 | 4.09375 | 4 | class check_sensors():
def __init__(self, sensor_distance):
self.sensor_distance = sensor_distance
#sensor_distance[0] = right sensor distance
#sensor_distance[1] = left sensor distance
#sensor_distance[2] = center sensor distance
"""def check_start(self):
if (self.sensor_distance[2] >= 0.15):
if (self.sensor_distance[0,1] < 0.15) or (self.sensor_distance[0,1] > 0.45): #trying to achieve checking both sensors for a case where they are outside of the ranges.
#dont know if this works or not though
return "CALC" #calcalate position method. using feedback from sensors
elif (0.15 <= self.sensor_distance[0,1] <= 0.45):
return "GOOD" #nothing needs to change. start program
elif (self.sensor_distance[2] < 0.15):
if (self.sensor_distance[0,1] < 0.15) or (self.sensor_distance[0,1] > 0.45):
return "REV_CALC"
elif (0.15 <= self.sensor_distance[0,1] <= 0.45):
return "REV"
"""
@property
def check_start(self):
if self.sensor_distance[2] < 0.15:
if (self.sensor_distance[0,1] < 0.15) or (self.sensor_distance[0,1] > 0.45):
return "REV_ONE" #rev_one being to only reverse on wheel, opposite one to the sensor.
elif (0.15 <= self.sensor_distance[0,1] <= 0.45):
return "REV"
else:
if (self.sensor_distance[0,1] < 0.15) or (self.sensor_distance[0,1] > 0.45): #trying to achieve checking both sensors for a case where they are outside of the ranges.
#dont know if this works or not though
return "CALC" #calcalate position method. using feedback from sensors
elif 0.15 <= self.sensor_distance[0, 1] <= 0.45:
return "GOOD" #nothing needs to change. start program |
2b76d634811db9cd14c071b1e816378ac6f47d65 | August1s/LeetCode | /Linked List/No21合并两个有序链表.py | 1,437 | 3.90625 | 4 |
'''
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
l3 = ListNode(None)
head = l3
while l2 != None and l1 != None:
if l1.value <= l2.value:
l3.next = ListNode(l1.value)
l3 = l3.next
l1 = l1.next
else:
l3.next = ListNode(l2.value)
l3 = l3.next
l2 = l2.next
if l2 == None:
l3.next = l1
else:
l3.next = l2
return head.next'''
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
# 递归解法
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
# 在改变原链表基础上的迭代法
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
start = ListNode()
start.next = l1
cur = start
while True:
if l1 and l2:
if l1.val >= l2.val:
cur.next = l2
cur = l2
l2 = l2.next
else:
cur.next = l1
cur = l1
l1 = l1.next
elif l1 and not l2:
cur.next = l1
return start.next
elif l2 and not l1:
cur.next = l2
return start.next
else:
return start.next
|
966e601e4ee55ac1bdceada3e3660e2cd0259a19 | Julian-Chu/leetcode_python | /lintcode/lintcode788.py | 3,371 | 4 | 4 | class Solution:
"""
@param maze: the maze
@param start: the start
@param destination: the destination
@return: the shortest distance for the ball to stop at the destination
"""
def shortestDistance(self, maze, start, destination):
if not maze:
return -1
start_x = start[0]
start_y = start[1]
end_x = destination[0]
end_y = destination[1]
minDist = float('inf')
queue = collections.deque([(start_x, start_y, 0)])
visited = {}
while queue:
for _ in range(len(queue)):
x, y, dist = queue.popleft()
if dist > minDist:
continue
if (x, y) == (end_x, end_y):
minDist = min(minDist, dist)
for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
next_x = x
next_y = y
next_dist = dist
while self.is_valid(maze, next_x + dx, next_y + dy):
next_x = next_x + dx
next_y = next_y + dy
next_dist += 1
if next_x == x and next_y == y:
continue
if (next_x, next_y) in visited and visited[(next_x, next_y)] < next_dist:
continue
queue.append((next_x, next_y, next_dist))
visited[(next_x, next_y)] = next_dist
if minDist == float('inf'):
return -1
return minDist
def is_valid(self, maze, x, y):
if not (0 <= x < len(maze) and 0 <= y < len(maze[0])):
return False
if maze[x][y] == 1:
return False
return True
"""
@param maze: the maze
@param start: the start
@param destination: the destination
@return: the shortest distance for the ball to stop at the destination
"""
import collections
def shortestDistance(self, maze, start, destination):
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
x_start = start[0]
y_start = start[1]
x_end = destination[0]
y_end = destination[1]
dist = 0
queue = collections.deque([(x_start, y_start, dist)])
min_dist = float('inf')
res = dict()
# res[(x_start, y_start)] = dist
while queue:
print(queue)
for _ in range(len(queue)):
(x, y, dist) = queue.popleft()
if dist >= min_dist:
continue
if (x, y) == (x_end, y_end):
print(min_dist)
min_dist = min(min_dist, dist)
if (x, y) in res and dist >= res[(x, y)]:
continue
res[(x, y)] = dist
for dx, dy in directions:
cur_x, cur_y, new_dist = x, y, dist
while self.is_valid(maze, cur_x, cur_y):
cur_x, cur_y = cur_x + dx, cur_y + dy
new_dist += 1
cur_x -= dx
cur_y -= dy
new_dist -= 1
queue.append((cur_x, cur_y, new_dist))
return -1 if min_dist == float('inf') else min_dist
def is_valid(self, maze, x, y):
if x < 0 or x >= len(maze):
return False
if y < 0 or y >= len(maze[0]):
return False
if maze[x][y] == 1:
return False
return True |
32a67dfff86a5bd3f0ad48a18d084678e5b47590 | CamiloCardonaArango/python_seti | /Reto_3/clases.py | 936 | 3.859375 | 4 | """ Módulo que contiene las clases utilizadas para el reto de la semana 3"""
class Compuerta:
""" Clase principal de las compuertas """
def __init__(self, entrada_a, entrada_b):
""" Inicializa la clase compuertas """
self.entrada_a = entrada_a
self.entrada_b = entrada_b
class CompuertaOR(Compuerta):
""" Compuerta OR """
def calcular_salida(self):
""" Calcula la salida de la compuerta OR """
salida_or = 1
if self.entrada_a == 0 and self.entrada_b == 0:
salida_or = 0
return "La salida de la compuerta OR es: " + str(salida_or)
class CompuertaAND(Compuerta):
""" Compuerta AND """
def calcular_salida(self):
""" Calcula la salida de la compuerta OR """
salida_and = 0
if self.entrada_a == 1 and self.entrada_b == 1:
salida_and = 1
return "La salida de la compuerta AND es: " + str(salida_and)
|
a231ca976ee3feace2a2f184663a35ae470d70d3 | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/patchcarrier/Lesson03/list_lab.py | 2,401 | 4.375 | 4 | #!/usr/bin/env python3
### Series 1 ###
print("\n-----------Beginning Series 1-----------")
fruit_list = ["Apples","Pears","Oranges","Peaches"]
print(fruit_list)
# Add a user specified fruit to the list
another_fruit = input("Specify another fruit: ")
fruit_list.append(another_fruit)
print(fruit_list)
# Print the fruit at a user specified (1-based) index
prompt = "Specify an integer in the range [{:d},{:d}] for the desired fruit: "
item_number = input(prompt.format(1,len(fruit_list)))
item_number = int(item_number)
print("The fruit at index {:d} is {}".format(
item_number, fruit_list[item_number - 1]))
# Add Blueberries and Kiwi to the front of the list
fruit_list = ["Blueberries"] + fruit_list
print(fruit_list)
fruit_list.insert(0,"Kiwi")
print(fruit_list)
# Display fruits in the list that start with the character 'p'
p_fruits = []
for fruits in fruit_list:
if fruits[0].lower() == 'p':
p_fruits.append(fruits)
print("Fruits that start with a 'P': " + ",".join(p_fruits))
### Series 2 ####
print("\n-----------Beginning Series 2-----------")
# Delete the last fruit in the list
print(fruit_list)
del fruit_list[-1]
print(fruit_list)
# Delete a fruit specified by the user from the list
# (after multiplying the list by 2, every occurance is deleted)
fruit_list *= 2
delete_fruit = input("Specify the name of a fruit to delete: ")
while delete_fruit not in fruit_list:
delete_fruit = input("Specify the name of a fruit to delete: ")
print("Before delete:\n",fruit_list)
n_delete_fruits = fruit_list.count(delete_fruit)
for _ in range(n_delete_fruits):
fruit_list.remove(delete_fruit)
print("After delete:\n",fruit_list)
### Series 3 ###
print("\n-----------Beginning Series 3-----------")
for fruit in fruit_list[:]:
like_fruit = input("Do you like {}?: ".format(fruit))
while not (like_fruit.lower() == 'no' or like_fruit.lower() == 'yes'):
like_fruit = input("Do you like {}?. Specify 'yes' or 'no' :".format(
fruit))
if like_fruit.lower() == 'no':
fruit_list.remove(fruit)
print(fruit_list)
### Series 4 ###
print("\n-----------Beginning Series 4-----------")
fruit_copy = fruit_list[:]
for k in range(len(fruit_copy)):
string_k = fruit_copy[k]
fruit_copy[k] = string_k[::-1]
del fruit_list[-1]
print('original:',fruit_list)
print('copy:',fruit_copy)
|
297b183f237054fa5ba85b21a2b5bc29f454a2fd | umairnsr87/Data_Structures_Python | /1542A - odd set.py | 334 | 3.671875 | 4 | test = int(input())
for _ in range(test):
pairs = int(input())
nums = list(map(int, input().split()))
odd, even = 0, 0
for num in nums:
if num % 2 == 0:
even += 1
else:
odd += 1
flag = min(odd, even)
if flag<pairs:
print("NO")
else:
print("YES")
|
eb0f36a43259a0137d6fbac318c80e3f8c8a3f89 | yogii1981/Fullspeedpythoneducative1 | /loginpage.py | 628 | 3.71875 | 4 | class User:
def __init__(self, username=None, password=None):
self.__username = username
self.__password = password
def username1(self):
self.__username = input('What is the username?')
def password1(self):
self.__password = int(input("Enter a password"))
def login(self):
self.username1()
self.password1()
if self.__username == "Yogesh" and self.__password == 123456:
print("login granted")
else:
print("incorrect username or password")
test = User()
test.login()
test.password = 2341234
test.login()
|
ab67df17f094a82af28132e27b5e3d87e36c426b | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeRepeticao - PythonBrasil/exec33.py | 285 | 3.59375 | 4 | cont = 1
soma = 0
maior = 0
temp = 1
while temp != 0:
temp = float(input('Temperatura %d: '%cont))
if temp > maior:
maior = temp
soma += temp
cont += 1
media = soma/cont
print('A maior nota registrada no periodo foi %d e a media geral foi %5.1f'%(maior, media)) |
5c881e7b343b5cac4080b6adc1e069b08f02c62d | piotrek9999/Mario | /SuperMarioDemo/SuperMarioDemo/classes/enemy.py | 1,591 | 3.875 | 4 | """ Class Enemy. """
import pygame as pg
from pygame import sprite
class Enemy(sprite.Sprite):
"""
This is a class for Enemy object.
Attributes:
image : The image of Enemy.
rect : The coordinates of Enemy.
last_direction : Last direction of Enemy horizontally.
counter : The adjunct int to update Enemy's coordinate.
range : The range to walk Enemy.
half : The middle of Enemy's range.
"""
def __init__(self, image_to_load, coo_x, rang, coo_y=432):
"""
The constructor for Enemy class.
Parameters:
image_to_load : The image for Enemy.
coo_x, coo_y : The values of coordinates for Enemy's object.
rang : The value of Enemy's range.
"""
super().__init__()
self.image = pg.image.load(image_to_load)
self.image = pg.transform.scale(self.image, (80, 80))
self.rect = self.image.get_rect()
self.rect.x = coo_x
self.rect.y = coo_y
self.last_direction = 1
self.counter = 0
self.range = rang
if self.range % 2 == 0:
self.half = self.range / 2 - 1
else:
self.half = self.range / 2
def update(self):
"""Function for updating position of Enemy."""
if self.counter < (self.half + 1):
self.rect.x += 10
if self.half < self.counter < self.range:
self.rect.x -= 10
if self.counter == self.range - 1:
self.counter = -1
self.counter += 1
ENEMY_GROUP = sprite.Group()
|
28e571bab5e55960e7c5e29137bf37db5fe0537b | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/mrpgeo001/question1.py | 1,340 | 4.09375 | 4 | """Program for checking is strings are palindromes
Geoff Murphy
MRPGEO001
6 May 2014"""
string = input("Enter a string:\n")
def pal_check(string):
palindrome = 0 #Initial value of a. If a = 0, not a palindrome. If a = 1, the string is a palindrome.
if len(string) == 1: #If there is only one letter, it is automatically a palindrome.
palindrome = 1
elif len(string) == 2 and string[0] == string[1]: #If there are only two letters and those letters are the same, it is a palindrome.
palindrome = 1
elif string[0] == string[-1]: #If the front and back letters are the same, it runs the recursive step, i.e. cuts the back and front letters and runs the function again.
palindrome = 1
return pal_check(string[1:-1])
else: #If all other conditions are not met, it makes 'a' equal to 0, i.e. it is not a palindrome.
palindrome = 0
if palindrome == 1: #Prints the respective message depending on the value of 'a'.
print("Palindrome!")
else:
print("Not a palindrome!")
pal_check(string) |
33374838a317e965f52ee1665a4cc5f9854427b2 | JiaXingBinggan/For_work | /code/tree/is_same_tree.py | 1,277 | 3.875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isSameTree(self, p, q):
"""
给定两个二叉树,编写一个函数来检验它们是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if not p and not q:
return True
if not q or not p:
return False
pre_p = self.preorder(p)
pre_q = self.preorder(q)
return pre_p == pre_q
def preorder(self, root):
if not root:
return ['null']
else:
left = self.preorder(root.left)
right = self.preorder(root.right)
return [root.val] + left + right
def is_same_tree(self, p, q):
if not p and not q: # 如果两者同时为空肯定返回True
return True
elif p and q:
return p.val == q.val and self.is_same_tree(p.left, q.left) and self.is_same_tree(p.right, q.right)
else:
return False |
44429ba938831e52b43fa93fecba01e127d7d637 | heet-gorakhiya/Scaler-solutions | /Searching/Searching-2-AS_aggressive_cows.py | 3,562 | 3.96875 | 4 | # Aggressive cows
# Problem Description
# Farmer John has built a new long barn, with N stalls. Given an array of integers A of size N where each element of the array represents the location of the stall, and an integer B which represent the number of cows.
# His cows don't like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, John wants to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?
# Problem Constraints
# 2 <= N <= 100000
# 0 <= A[i] <= 109
# 2 <= B <= N
# Input Format
# The first argument given is the integer array A.
# The second argument given is the integer B.
# Output Format
# Return the largest minimum distance possible among the cows.
# Example Input
# Input 1:
# A = [1, 2, 3, 4, 5]
# B = 3
# Input 2:
# A = [1, 2]
# B = 2
# Example Output
# Output 1:
# 2
# Output 2:
# 1
# Example Explanation
# Explanation 1:
# John can assign the stalls at location 1,3 and 5 to the 3 cows respectively.
# So the minimum distance will be 2.
# Explanation 2:
# The minimum distance will be 1.
class Solution:
# @param A : list of integers
# @param B : integer
# @return an integer
def solve(self, A, B):
# A.sort()
# low = 0
# high = max(A)-min(A)
# ans = 0
# def possibe(A, B, mid):
# last_pos = A[0]
# cows_placed = 1
# for i in range(1,len(A)):
# if(A[i]-last_pos >= mid):
# cows_placed += 1
# if cows_placed == B:
# return True
# last_pos = A[i]
# if cows_placed >= B:
# return True
# else:
# return False
# while low < high:
# mid = low + (high-low)//2
# if(possibe(A, B, mid)):
# ans = mid
# low = mid+1
# else:
# high = mid
# return ans
# def pre_compute(A, B, mid):
# count = 1
# n = len(A)
# pos = 0
# i = 0
# while i<n:
# if A[i] - A[pos] >= mid:
# count+=1
# pos = i
# if count == B:
# return True
# i+=1
# return False
# l = 1
# h = max(A)-min(A)
# A.sort()
# while l <= h:
# mid = l + (h-l)//2
# temp = pre_compute(A, B, mid)
# # print(mid)
# if temp == True:
# ans = mid
# l = mid + 1
# else:
# h = mid - 1
# return ans
A = list(sorted(A))
lo = 0
hi = A[0] + A[-1] + 1
while lo < hi:
mid = (hi + lo) // 2
if self.F(A, B, mid):
lo = mid + 1
else:
hi = mid
return lo - 1
def F(self, A, B, mid):
prev = A[0]
cow = 1
for i in range(1, len(A)):
diff = A[i] - prev
if diff >= mid:
cow += 1
if cow == B:
return 1
prev = A[i]
return 0 |
7c663ad0c8d254ad85132c26724ff9af30ec621c | dieforice/Unity_LeThanhCuong | /Session4/4.9/many squares.py | 312 | 3.53125 | 4 | from turtle import *
bgcolor("yellow")
speed(-1)
def draw_4_squares(sz):
color("blue")
pensize(2)
for _ in range(4):
for i in range(4):
forward(sz)
left(90)
right(90)
## draw 4 squares with same sizes sz
for n in range(6):
draw_4_squares(100)
left(15)
|
21cd4f4514397e1b044b7bca7a23f2e009947e0d | oliviagonzalez/caesar | /helpers.py | 803 | 3.875 | 4 | def alphabet_position(letter):
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
for l in alphabet:
if l == letter.lower():
return alphabet.index(l)
return "error. input should be a single letter"
def get_letter_by_position(pos):
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
return alphabet[pos]
def rotate_character(ch, rot):
if ch.isalpha() == True:
initPosition = alphabet_position(ch)
newPosition = (initPosition + int(rot))%26
newCh = get_letter_by_position(newPosition)
if ch.isupper() == True:
return newCh.upper()
return newCh
else:
return ch |
040aeed610b90165c3ef16d6aaa14bf44b4da825 | RenataTNT/Python-OOP | /OOP_Task_2.py | 1,173 | 3.609375 | 4 | # Используя навыки работы с текстом, получите количество студентов GeekBrains со стартовой страницы сайта geekbrains.ru.
# У вас два пути решения:
# * использовать регулярные выражения (библиотеку re),
# * использовать библиотеку BeautifulSoup.
import os
import re
from bs4 import BeautifulSoup as BS
with open('startpage.txt', 'r', encoding='utf-8') as f:
text = f.read()
print('---------использовать регулярные выражения (библиотеку re)---------')
pattern = re.compile('<span class="total-users">Нас уже ([0-9 ]+) человек</span>')
users = pattern.findall(text)[0]
print(users)
number_of_students = re.sub('\s', '', users)
print(number_of_students)
print('---------использовать библиотеку BeautifulSoup---------')
soup = BS(text, 'html.parser')
span=soup.span.string
print(span)
temp=re.findall('\s[0-9 ]+\s',span)[0]
print(temp)
number_of_students=re.sub('\s','',temp)
print(number_of_students)
|
66dbe8a67a0a07a36eaf83e574e60aaebe5a4f4d | panok90/gb-lessons | /task-1.py | 553 | 4.375 | 4 | # Создать список и заполнить его элементами различных типов данных.
# Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа.
# Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
list = [1, "list", True, [1, 2], {1: 1, 2: 2}]
for item in list:
print(type(item))
|
10e2acf037d9baf5b3650bd8a8e2ad6dda20ee26 | pkuipers1/PythonAchievements | /Les05/shuffleAndReturn.py | 695 | 3.921875 | 4 | #Schrijf een functie die de letters van een woord willekeurig door elkaar schudt.
#Je mag deze code hiervoor hergebruiken.
#Bij het aanroepen van de functie moet je elk woord mee kunnen geven als argument.
#De functie moet het geschudde woord terug geven via een return.
#Roep de functie 3x aan met een ander woord en print de geschudde woorden uit.
import random
def randomiseLetters(original):
randomised = ''.join(random.sample(original, len(original)))
return randomised
print(randomiseLetters("test"))
print(randomiseLetters("word"))
print(randomiseLetters("Star"))
woord = input("Welk woord wil je shuffelen?")
randomise = randomiseLetters(woord)
print(randomise.upper())
|
bb6c715bb6d1dd259ca158345e13f5489f12ddaf | alirezaghey/leetcode-solutions | /python/path-with-maximum-gold.py | 2,008 | 4.28125 | 4 | # https://leetcode.com/problems/path-with-maximum-gold/
# Related Topics: DFS, Backtracking
# Difficulty: Medium
# Initial thoughts:
# Aside from the starting cell, each cell has at most three paths that go out of it
# (that's because we can't go back to our previous cell since we have already visited it).
# We need to recursively check every possibility to find the optimal solution.
# Using backtracking to investigate every possible path from a given starting cell
# we are going to search for the maximum value. The backtracking will be implemented
# in a depth first approach, since this will take less auxilliary space and is also
# more natural to implement.
# Since we can start our search at any cell in the grid, we are going to apply this
# algorithm to every cell of the grid as the starting point.
# Time complexity: O(n*m*3^(m*n)) [THIS IS NOT CORRECT! NEEDS REVIEW] where n === grid width and m === grid heigth
# Space complexity: O(n) where n === number of cells in the grid. This is the worst case
# where our algorithm is able to visit each and every cell in a given path and so the depth
# of our virtual tree equals the number of nodes in it.
from typing import List
class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
if len(grid) == 0 or len(grid[0]) == 0:
return 0
R, C = len(grid), len(grid[0])
def dfs(r: int, c: int, curr: int) -> int:
if r < 0 or r >= R or c < 0 or c >= C or grid[r][c] == 0:
return curr
temp = grid[r][c]
grid[r][c] = 0
top = dfs(r-1, c, curr+temp)
right = dfs(r, c+1, curr+temp)
bottom = dfs(r+1, c, curr+temp)
left = dfs(r, c-1, curr+temp)
grid[r][c] = temp
return max(top, right, bottom, left)
maximum = float('-inf')
for r in range(R):
for c in range(C):
maximum = max(maximum, dfs(r, c, 0))
return maximum
|
5cb6ad2533e4dbe68af6399b05c293f3bfc92bef | kimth007kim/python_choi | /Chap10/10_17.py | 410 | 3.984375 | 4 | from tkinter import *
mycolor="blue"
def paint(event):
x1,y1=(event.x-1),(event.y+1)
x2,y2=(event.x-1),(event.y+1)
canvas.create_oval(x1,y1,x2,y2,fill=mycolor)
def change_color():
global mycolor
mycolor="red"
window = Tk()
canvas= Canvas(window)
canvas.pack()
canvas.bind("<B1-Motion>",paint)
button = Button(window,text="빨간색",command=change_color)
button.pack()
window.mainloop() |
f90b6cdd7837dda28f05dd18902fc47fd304c20f | sitayebsofiane/cours-PYTHON | /divers/vetusté.py | 324 | 3.5625 | 4 | #coding:utf-8
def calcul_prix(anné_achat,coef,prix):
nbr=2019-anné_achat
while nbr>0:
nbr -=1
prix *=1-coef
return prix
a=int(input('entrez année d''achat '))
b=float(input('entrez coef '))
c=float(input('entrez prix '))
print('le prix qui sera rembousé est {}'.format(calcul_prix(a,b,c)))
|
2f9907ec41c94565a282c7e323dd14c04c28eda4 | sghosh1991/InterviewPrepPython | /LeetCodeProblemsMedium/17_letter_combination_phone_number.py | 1,121 | 3.71875 | 4 | """
https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
"""
class Solution(object):
def __init__(self):
self.results = []
self.mappings = {
2: "abc",
3: "def",
4: "ghi",
5: "jkl",
6: "mno",
7: "pqrs",
8: "tuv",
9: "wxyz"
}
self.num_digits = 0
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
self.digits = digits
self.num_digits = len(digits)
self.combinations_helper(["" for i in range(self.num_digits)], 0)
return self.results
def combinations_helper(self, partial_res, position):
if position == self.num_digits:
self.results.append("".join(partial_res))
else:
for ch in self.mappings[int(self.digits[position])]:
partial_res[position] = ch
self.combinations_helper(partial_res, position + 1)
if __name__ == "__main__":
x = Solution()
print x.letterCombinations("23")
|
c4d1a247b25bbbab1e375d29e092fb00d7ac185c | qqewrt/python_lecture | /if_and_or_test.py | 164 | 3.8125 | 4 | a = 10
b = 13
if (a%2==0)and(b%2==0):
print('두 수 모두 짝수입니다.')
if (a%2==0)or(b%2==0):
print('두 수 중 하나 이상이 짝수입니다.') |
efd5f51c616973dc5d934562db033412acd92857 | everqiujuan/python | /day19/code/08_format.py | 1,280 | 3.828125 | 4 |
print()
"""
format方法
"""
#括号及其里面的字符 (称作格式化字段) 将会被 format() 中的参数替换
print("我叫{},今年{}!".format("张三",22))
#括号中的数字用于指向传入对象在 format() 中的位置
print("我叫{0},今年{1}!".format("张三",22))
print("我叫{1},今年{0}!".format("张三",22))
#
#在format()中使用关键字参数,它们的值会指向使用该名字的参数
print("我叫{name},今年{age}!".format(name="张三",age=22))
print("我叫{name},今年{age}!".format(age=22,name="张三"))
#位置及关键字参数可以任意的结合
print("我叫{0},今年{1},现住{place}!".format("张三",22,place="深圳"))
print("我叫{0},现住{place},今年{1}!".format("张三",22,place="深圳"))
# print("我叫{name},现住{0},今年{1}!".format(name="张三","深圳",22))
#':'和格式标识符可以跟着字段名。可以对值进行更好的格式化
a = 3.1415926
print("a的值为{0:.3f}".format(a))
print("{0:5}---{1:05d}".format("张三",18))
# __call__
# __str__
# __add__
# __repr__
# __iter__
# __next__
# __dict__
#
#
# 2007 iphone
# 2008 iphone3
# 2009 iphone3GS
# 2010 iphone4
# 2011 iphone4S
# 2012 iphone5
# 2013 iphone5S
# ...
#
|
45a47c79160a813d031597ea9435036b1c2a584a | cvhs-cs-2017/practice-exam-Narfanta | /Loops.py | 330 | 4.3125 | 4 | """Use a loop to make a turtle draw a shape that is has at least 100 sides and
that shows symmetry. The entire shape must fit inside the screen"""
import turtle
shape = turtle.Turtle()
shape.pu()
shape.left(90)
shape.forward(200)
shape.right(90)
shape.pd()
for i in range(150):
shape.forward(10)
shape.right(2.4)
input()
|
e88858c7d026401f5314490a29c412152f080b99 | abayirli/leetCodeProblems | /Challange_2020_June/03_TwoCity_Scheduling.py | 1,085 | 3.609375 | 4 | # LeedCode June Challange Day 3
# Two City Scheduling Problem
# Definition:
# There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0],
# and the cost of flying the i-th person to city B is costs[i][1].
# Return the minimum cost to fly every person to a city such that exactly N people arrive in each city.
import random
def twoCitySchedCost(costs):
n = int(len(costs)/2)
cost_diff = sorted(costs, key = lambda k: abs(k[0] - k[1]), reverse = True)
sum_cost = 0
n0, n1 = (0,0)
k = 0
while(k < 2*n):
t0 = cost_diff[k][0]
t1 = cost_diff[k][1]
if((t0 <= t1 and n0 < n) or n1 == n):
sum_cost += t0
n0 += 1
else:
sum_cost += t1
n1 += 1
k += 1
return sum_cost
def test():
assert twoCitySchedCost([[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]) == 1859
assert twoCitySchedCost([[10,20],[30,200],[400,50],[30,20]])
assert twoCitySchedCost([[518,518],[71,971],[121,862],[967,607],[138,754],[513,337],[499,873],[337,387],[647,917],[76,417]]) == 3671
print("All test passed!")
test() |
4cce30096d92a65dd4c81a4beac8461525039239 | obiwan1715/python_practice | /word_by_letters.py | 167 | 4.15625 | 4 | def wordbreakdown(word):
for i in word:
print i
wordbreakdown("Ben")
#this was the old code before I made it a function
#word="Hello"
#for i in word:
#print i
|
42053fdee06ee51ea948310eab6dc8cf38fc41e7 | 2SEHI/Python-Programming-Test | /programmers/StrToNum.py | 381 | 3.765625 | 4 | '''
2021 카카오 채용연계형 인턴십
숫자 문자열과 영단어
https://programmers.co.kr/learn/courses/30/lessons/81301?language=python3
'''
def solution(answer):
g = {0:'zero', 1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine'}
for key, value in g.items():
answer = answer.replace(value, str(key) )
return int(answer) |
e46034dedbbd933b511799b870b5a7789415df08 | nbiadrytski-zz/python-training | /cookbook/class_object/calling_super.py | 177 | 3.734375 | 4 | class A:
def __init__(self):
self.x = 1
class B(A):
def __init__(self):
super().__init__()
self.y = 2
a = A()
print(a.x)
b = B()
print(b.y)
|
4c03861d33f444543e0be19b79e5da66b82cab0b | interwho/Python-in-a-Week | /2 - Python Assignment #1 - New/Ex1.py | 1,535 | 4 | 4 | #Ex1.py
#
#Variables:
#name - name of the item
#price - price of the item
#tax - HST
#full - Full Price + HST
#inp - Temp. Reset Variable
#
#Input: Name and price of an item
#Output: Name, Price, HST, and Total Price of an item
#Process: Get data > verify > calculate > round final answers > print output
import sys #Import required system resources (for exit)
def taxcalc() : #Function to get and verify the input number
name = raw_input('Enter the name of the item:\n') #Get data
price = raw_input('Enter the price of the item:\n')
try : #error catching
price = float(price) #verification
name = str(name)
calctax(name,price)
except ValueError : #error
print 'Invalid Number - Please Try Again.' #Errors
taxcalc() #reset
def calctax(name,price) : #Function to actually do the work
tax = 0.13 * price #calculate tax
full = price + tax #calc. full price
tax = round(tax, 2) #round numbers
full = round(full, 2) #round numbers
price = round(price, 2) #round numbers
print "Tax Calculator Program" #Print output
print "Item: " + str(name)
print "Price: $" + str(price)
print "HST: $" + str(tax)
print "Total: $" + str(full)
inp = raw_input('\n\nTry again? (yes/no)\n') #Asks the user if they want to try again
if inp == 'yes' or inp == 'Yes' or inp == 'YES' or inp == 'y' or inp == 'Y' :
taxcalc() #try again
else :
sys.exit() #exit
taxcalc() #Initialize Program
|
79fa6789bfafb6879d743cdee60c22ddfeb286d2 | KlimentiyFrolov/-pythontutor | /Занятие 6. Цикл while/задача 6.PY | 140 | 3.953125 | 4 | #http://pythontutor.ru/lessons/while/problems/seq_sum/
a = int(input())
b = 0
while a != 0:
b = b+a
a = int(input())
print(b)
|
7b2d88511b752ce1827756de7c4037dea274c72a | leungcc/pythonLxf | /FunctionalProgramming/sorted/basic.py | 576 | 4.09375 | 4 | #最基础用法
print( sorted([36, 5, -12, 9, 21]) )
#加入key命名关键字参数
print( sorted([36, 5, -12, 9, 21], key=abs) )
#字符串排序默认按照 ASCII 的大小比较的,由于'Z'<'a',所以大写字母Z会排在小写字母a前面
print( sorted(['bob', 'about', 'aaaaa', 'Zoo', 'Credit']) )
#现在我们提出排序要忽略大小写
print( sorted(['bob', 'about', 'aaaaa', 'Zoo', 'Credit'], key=str.lower) )
#要进行反向排序,不必改动key函数,可以传入第三个参数 reverse=True
print( sorted([36, 5, -12, 9, 21], reverse=True) )
|
f35ff7a26908e26922a02b7fc3837dd5ae50b2d1 | Rachaelllwong/-mini-proj | /temp.py | 3,266 | 3.640625 | 4 | import matplotlib.pyplot as plt
import numpy as np
maze = []
walls = []
Start =[]
end = [47,1]
Dimensions = 51
with open(r"C:\Users\racha\OneDrive\Desktop\maze.txt", 'r') as f:
line = f.readlines() #reading the lines in the file
for element in line:
if element == 'True\n':
walls.append(1)
elif element == "False\n":
walls.append(0)
if len(walls) == Dimensions:
maze.append(walls)
walls = []
#starting point
def Startpoint_input():
for i in range(0,2):
Userinput = input("Enter your coordinates: ")
if Userinput in str(list(range(Dimensions))):
Start.append(int(Userinput))
else:
print("Wrong input type.")
Start.clear()
Startpoint_input() #rerun loop function
break
Startpoint_input()
#Checking for walls
def Startpoint_Coords():
#determining of value of coord
List1 = maze[Start[1]]
List2 = List1[Start[0]]
if List2 == 1:
print("Coordinate is a wall, please re-enter your coordinate")
Start.clear()
Startpoint_input()
Startpoint_Coords()
Startpoint_Coords()
print('Your Starting Coordinates: ', Start)
#Creating a 0 matrix
p = []
for i in range(len(maze)):
p.append([])
for j in range(len(maze[i])):
p[-1].append(0)
p[Start[1]][Start[0]] = 1
def steps(k):
for y in range(len(p)):
for x in range(len(p[y])):
if p[y][x] == k:
if y>0 and maze[y-1][x] == 0 and p[y-1][x] == 0:
p[y-1][x] = k+1
if x>0 and maze[y][x-1] == 0 and p[y][x-1] == 0:
p[y][x-1] = k+1
if y<(len(p)-1) and maze[y+1][x] == 0 and p[y+1][x] == 0:
p[y+1][x] = k+1
if x<len(p[y])-1 and maze[y][x+1] == 0 and p[y][x+1] == 0:
p[y][x+1] = k+1
k=1
while p[end[1]][end[0]] == 0:
steps(k)
k += 1
path_taken = []
def path():
y,x = end[1],end[0]
k = p[y][x]
while k > 1:
if y > 0 and p[y-1][x] == k-1:
x,y = x,y-1
path_taken.append((x,y))
k-=1
elif x > 0 and p[y][x-1] == k-1:
x,y = x-1,y
path_taken.append((x,y))
k-=1
elif y<len(maze)-1 and p[y+1][x] == k-1:
x,y = x,y+1
path_taken.append((x,y))
k-=1
elif x < len(maze[y]) - 1 and p[y][x+1] == k-1:
x,y = x+1,y
path_taken.append((x,y))
k -= 1
path()
#add path taken into maze[]
for a in range(len(path_taken)):
maze[path_taken[a][1]][path_taken[a][0]]=2
#visualising maze
endpoint = plt.plot(end[1]+0.5,end[0]+0.5,'ro')
startpoint = plt.plot(Start[0]+0.5,Start[1]+0.5,'go')
Tmaze = np.array(maze)
Tmaze = np.transpose(Tmaze)
plt.pcolormesh(Tmaze)
plt.axes().set_aspect('equal') #set the x and y axes to the same scale
# plt.xticks([]) # remove the tick marks by setting to an empty list
# plt.yticks([]) # remove the tick marks by setting to an empty list
plt.gca().invert_yaxis()
#plotting points
plt.show()
|
31132e7c1660696bf6263bb26bec66c8227fcda4 | amritat123/function-questions | /maximum_from_nested_list.py | 264 | 3.546875 | 4 |
def max_num(num_1):
i=0
while i<len(num_1):
j=0
max=0
a=num_1[i]
while j<len(a):
if a[j]>max:
max=a[j]
j+=1
print(max)
i+=1
max_num([[2,4,6,81,0],[1,3,5,17,9]]) |
9796cad82a78cb5c764dc6614eedda75dd2ffdfb | Annatcaci/InstructiuneaFOR | /FOR 4.py | 111 | 3.6875 | 4 | n=int(input("Introduceti n"))
s=0
for i in range(1,n):
if (i%3==0) and (i%5==0):
s+=i
print(s) |
e9318639c8e27cebce108114f3da4d5ced52e97c | hellozepp/iotest-pyy | /iotestpy/oop/ooptest1.py | 611 | 4.0625 | 4 | class Person:
X=1
def __init__(self,id,name):
self.id=id
self.name=name
def xxx(self):
print(self.id)
def __str__(self):
return "str id: "+str(self.id)+" name: "+self.name
def __repr__(self):
return "repr id: " + str(self.id) + " name: " + self.name
if __name__ == "__main__":
p1=Person(1,"aaa")
Person.xxx(p1)
p1.xxx()
print(p1)
print(str(p1))
print(repr(p1))
print("id: "+str(p1.id)+" name: "+p1.name)
print(Person.__dict__)
p=Person(1,"aaa")
p.X=2
print(p.X)
print(p.__dict__)
print(Person.X) |
e2c05ba1b49422a276903a770cedeead42b4f532 | larryv/CodeChef | /practice/easy/test.py | 432 | 4 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
test.py
Your program is to use the brute-force approach in order to find the Answer to
Life, the Universe, and Everything. More precisely... rewrite small numbers
from input to output. Stop processing input after reading in the number 42.
All numbers at input are integers of one or two digits.
"""
import sys
for line in sys.stdin:
if line == "42\n":
break
print(line) |
a5a8da9c1b8d2bb88dfe2280bf260c7595eb6e99 | spencerhcheng/holbertonschool-higher_level_programming | /0x0B-python-input_output/6-from_json_string.py | 175 | 3.71875 | 4 | #!/usr/bin/python3
import json
def from_json_string(my_str):
"""
Returns an object represented by
a JSON string
"""
f = json.loads(my_str)
return(f)
|
f8795cf79763ee8f27f77eeb8937b20d550fcb1a | alirezaghey/leetcode-solutions | /python/maximum-xor-of-two-numbers-in-an-array.py | 971 | 3.515625 | 4 | from typing import List
class Solution:
# Time complexity: O(n) where n is the length of nums
# Space complexity: O(n)
def findMaximumXOR(self, nums: List[int]) -> int:
masks = [2**i for i in range(31, -1, -1)]
res = 0
trie = {}
for num in nums:
node = trie
for mask in masks:
bit = num & mask
bit = 1 if bit > 0 else 0
if bit not in node:
node[bit] = {}
node = node[bit]
curr = 0
node = trie
for mask in masks:
bit = num & mask
bit = 1 if bit > 0 else 0
if bit^1 in node:
curr += mask
node = node[bit^1]
elif bit in node:
node = node[bit]
else:
break
res = max(res, curr)
return res |
bfe0555eb1f8c2c7901e1883838081444727ac27 | SensibilityTestbed/indoor-localization | /gyro_step_online.r2py | 6,231 | 3.6875 | 4 |
"""
<Program Name>
pedometer.r2py
<Purpose>
This is a script for walking step counter. Analysis of the sensor data
from accelerometer to detect the walking / running steps. Introducing
pre-calibration stage, noise level threshold and moving average filter
to accurate step detection for difference devices.
*Note: the device must be stable for 1 second pre-calibration from beginning
"""
dy_import_module_symbols('getsensor.r2py')
dy_import_module_symbols('pre_online.r2py')
hanning = dy_import_module('moving_average_hanning.r2py')
butterworth = dy_import_module('butterworth.r2py')
# constants for pre-calibratino stage
PRE_LEARN_SAMPLE_NUMBER = 100
ZERO_INTERVAL = 0.4 # Minimum time difference between each step in senconds
PEAK_INTERVAL = 0.5
# Peodmeter class, includes filtering raw data and step estimation
class Pedometer:
def __init__(self, precalibration, height):
# Coefficient from pre-calibration stage
self.gravity_constant = precalibration.get_gravity()
self.samplerate = precalibration.get_sample_rate()
self.threshold = precalibration.gyro_stats.variance ** 0.5 * 8
self.gyro_mean = precalibration.gyro_stats.mean
log("threshold: ", self.threshold, "mean: ", self.gyro_mean, '\n')
self.steptime = precalibration.time
# Initialize moving average filter
self.maf = hanning.HanningFilter(precalibration.time, 0.125)
# Initialize low pass filter
self.lpf = butterworth.ButterworthFilter("low", 3.0, self.samplerate, precalibration.time, 0.125)
self.hpf = butterworth.ButterworthFilter("high", 0.1, self.samplerate, precalibration.time, 0.125)
self.height = height
self.zerocount = 0
self.lastmag = 0.0
self.peakcount = 0
self.peak_window_start = self.steptime
self.maglist = []
self.timelist = []
self.max_mag = self.threshold
self.max_time = self.peak_window_start
self.last_peak_time = self.max_time
self.flag = 1
self.distance_zero = []
self.time_zero = []
self.distance_peak = []
self.time_peak = []
def detect_step(self, raw_data, time, method = 0):
# Non-gravity acceleration
raw_mag = matrix_row_magnitude(raw_data['roll'], raw_data['pitch'], raw_data['azimuth']) - self.gyro_mean
# linear phase low pass filter
lpf_mag = self.lpf.filter(raw_mag, time, True)
hpf_mag = self.hpf.filter(lpf_mag, time, True)
# moving average filter
maf_mag = self.maf.hanning_filter(hpf_mag, time)
log("raw: ", raw_mag, "maf_mag: ", maf_mag, '\n')
# step detection
peak = self._detect_peak(maf_mag, time)
zero = self._detect_zero(maf_mag, time)
if method == 1:
return peak
else:
return zero
def get_stepcount(self):
return {"zero": self.zerocount, "peak": self.peakcount}
def get_distance(self):
sum_zero = 0.0
sum_peak = 0.0
if len(self.distance_zero) > 0:
for i in range(0, len(self.distance_zero)):
sum_zero += self.distance_zero[i]
if len(self.distance_peak) > 0:
for i in range(0, len(self.distance_peak)):
sum_peak += self.distance_peak[i]
# Average of people's stride is height * 0.415
# Average stride works as reference
average_zero_distance = self.zerocount * 0.415 * self.height/100
average_peak_distance = self.peakcount * 0.415 * self.height/100
return {"distance_estimation_zero": sum_zero, "distance_estimation_peak": sum_peak, "average_zero_distance": average_zero_distance, "average_peak_distance": average_peak_distance}
# crossing noise level and actual step interval > minimum step interval
def _detect_zero(self, data, time):
stepped = False
if self.lastmag <= self.threshold and data > self.threshold and time - self.steptime >= ZERO_INTERVAL:
self.zerocount += 1
self.distance_zero.append(self._distance_estimation(self.steptime, time))
self.time_zero.append(time)
self.steptime = time
log("zero count:", self.zerocount, '\n')
stepped = True
self.lastmag = data
return stepped
# a moving window to capture the peak
# will change to queue later
def _detect_peak(self, data, time):
stepped = False
self.maglist.append(data)
self.timelist.append(time)
if time - self.peak_window_start >= PEAK_INTERVAL * self.flag:
for i in range(1, len(self.maglist)-1):
if self.maglist[i-1] <= self.maglist[i] and self.maglist[i] > self.maglist[i+1] and \
self.maglist[i] > self.max_mag:
self.max_mag = self.maglist[i]
self.max_time = self.timelist[i]
self.flag = 0
if self.flag:
self.flag += 1
else:
self.flag = 1
self.peakcount += 1
stepped = True
self.distance_peak.append(self._distance_estimation(self.last_peak_time, self.max_time))
self.time_peak.append(time)
log("peak count: ", self.peakcount, '\n')
self.peak_window_start = time
self.last_peak_time = self.max_time
self.max_mag = self.threshold
# self.last_maxtime = self.maxtime
self.maglist = []
self.timelist = []
return stepped
# Distance estimation by height and steps frequency
def _distance_estimation(self, lasttime, currenttime):
interval = currenttime - lasttime
step_per_second = 1.0/interval
if 0.0 <= step_per_second < 1.0:
stride_per_step = self.height/5.0
elif 1.0 <= step_per_second < 1.5:
stride_per_step = self.height/4.0
elif 1.5 <= step_per_second < 2.0:
stride_per_step = self.height/3.0
elif 2.0 <= step_per_second < 2.5:
stride_per_step = self.height/2.0
elif 2.5 <= step_per_second < 3.0:
stride_per_step = self.height/1.2
elif 3.0 <= step_per_second < 4.0:
stride_per_step = self.height
else:
stride_per_step = self.height * 1.2
speed_per_second = step_per_second * stride_per_step
step_length = speed_per_second * interval
if interval > 1.0 or step_length > 300.0:
log("interval", interval, "step_length", step_length)
step_length = self.height * 0.415
return step_length/100
# -*- mode: python;-*-
|
d3d6df0264cc316ead026be346635fa4e8aaffa8 | garona2dz/ChongChongChong | /shuJuJieGou/xuanZePaiXu.py | 1,145 | 3.53125 | 4 | list1 = [2, 4, 5, 3, 1]
list2 = [3, 2, 1, 5, 4]
def selection_sort1(deal_list):
i = 0
while i <= len(deal_list) - 2:
j = i + 1
while j <= len(deal_list) - 1:
if deal_list[i] >= deal_list[j]:
temp = deal_list[j]
deal_list[j] = deal_list[i]
deal_list[i] = temp # 直接交换赋值,直到把最小值放在最小位置
j += 1
i += 1
# print(list)
return deal_list
def select_sort2(lyst):
i=0
while i < len(lyst) - 1:
min_index = i
j = i + 1
while j < len(lyst):
if lyst[j] < lyst[min_index]:
min_index = j # 没有直接交换赋值,先标记最小位置,然后再将
j += 1 # 最小位置直接和指定位置交换赋值,减少了赋值次数
if min_index != i:
temp = lyst[min_index]
lyst[min_index] = lyst[i]
lyst[i] = temp
i +=1
return lyst
print(list1)
print("-" * 16)
print(selection_sort1(list1))
print("*" * 16)
print(list2)
print(select_sort2(list2))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.