blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
3fd2f80fe346b83c41d19de03005a9dbad5a0ae3
mrDurandall/Python-Basics-Course
/Lesson_1/Lesson-1 HW Task-2.py
330
3.90625
4
# Задание 2 - время из секунд в ЧЧ:ММ:СС print('Задание 2 - время из секунд в ЧЧ:ММ:СС') time = int(input('Введите время в секундах:')) seconds = time % 60 hours = time // 3600 minutes = time % 3600 // 60 print(f'{hours:02d}:{minutes:02d}:{seconds:02d}')
70360520f80bd575cd8d9258cba7441ca590024c
businan/Clarusway_Assignment
/fizzbuzz.py
461
4.09375
4
def fizzbuzz(x, y): for i in range(x, y): if i % 15 == 0 : print(i, 'is FizzBuzz') elif i % 3 == 0 : print(i, 'is Fizz') elif i % 5 == 0 : print(i, 'is Buzz') else: print(i, 'is unchanged') start = int(input("Enter number that you want ...
a351cd64f4c589d3248f2b784a888f6b9dc9d73f
jacob1992/FormationIA
/FormationStrat/Plays/PlayBase.py
551
3.765625
4
from abc import abstractmethod __author__ = 'jbecirovski' class PlayBase: """ Play contain: + Contain Sequence of Tactics for each bots + Manage Tactic attribution """ def __init__(self, name): assert isinstance(name, str) self.name = name @abstractmethod def getTacti...
27d9cc7dbf723d81e5be5aff0b46dc8fdd430533
tkent198/hydraulic_wetro
/python3/NET/checkdata.py
2,918
3.671875
4
# -*- coding: utf-8 -*- """ @author: TK <checkdata.py>: inital data upload-- clean and tidy up etc for further analysis. Output: new .csv to be uploaded elsewhere. >>>> Norlys ET -- Quant exercise <<<< One of your colleagues have discovered a trading strategy that looks to be quite profitable. The...
aaffe39c5d3ba56fcffdb9326f0e28bcdc2b62c8
jamjar102/IVMM
/utils/vector_haversine_distances.py
1,169
3.59375
4
import numpy as np import math def haversine_np(lon1, lat1, lon2, lat2, miles=False): """ Calculate the great-circle distance bewteen two points on the Earth surface. :input: 4 GPS coordinates, containing the latitude and longitude of each point in decimal degrees. Example: haversine(...
8e714e3521a8b717d50a106ef023612286ae936a
trudzer/TileTraveller
/TileTraveller.py
1,586
3.96875
4
#https://github.com/trudzer #https://github.com/JakobOli #https://github.com/trudzer/TileTraveller #https://github.com/trudzer/TileTraveller/blob/master/TileTraveller.py def walk(direction, position): if direction == "e": position += 10 elif direction == "n": position += 1 elif direction == "w": ...
87d05666b0abfbf246d53c6951e91282312d0ff9
mertfb186/GlobalAIHubPythonCourse-Mert_Yardimci-
/Final Project/FinalÖdevi.py
3,620
3.921875
4
#!/usr/bin/env python # coding: utf-8 # In[2]: print("********10 Soruluk Bilgi Yarışmasına Hoşgeldiniz******** \nUYARI:Soruları cevaplarken yazım yanlışı yapmamaya dikkat ediniz.\nBirinci soru ile başlıyoruz") puan=0 a1=input("Güneş sisteminde yer alan en büyük gezegenin ismi nedir?").lower() if(a1==("jüpiter")): ...
064d8ad5d3a6e0c0e69cefbbfc54f12491e5222d
Josipovic/pythonProject
/Employees.py
205
3.546875
4
class Employees: def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary def Display(self): print(self.id, self.name, self.salary)
62f2731a545ff06fd1d3ad6c2df31ac151fb9165
Josipovic/pythonProject
/Numbers.py
273
4
4
x = 10 # int y = 10.5 # float # print(type(x), type(y)) get data type float(x) # converting into float int(x) # converting into integer # max gets biggest value large = max(10, 20, 30, 100) print(large) # min gets smallest value small = min(1, 20, 3) print(small)
96a7201bb8f2b94a888009cf4c504dc55849cd5d
jamesbond007dj/py-data-structures-and-algorithms
/challenges/queue_with_stacks/queue_with_stacks.py
879
4.03125
4
class Node: def __init__(self, x, next_node = None): self.value = x self.next = next_node class Stack: def __init__(self, top = None): self.top = top def push(self, value): next_top = Node(value, self.top) self.top = next_top def pop(self): if not isinstance(self.top, Node): p...
7c2d566ba03383ef6db6caf624aa645cac23e9d4
jamesbond007dj/py-data-structures-and-algorithms
/data-structures/tree/test_tree.py
3,374
3.78125
4
from tree import BinaryTree, BinarySearchTree ''' BinaryTree connection test ''' def test_binary_tree_instance(): tree = BinaryTree() assert tree._root is None ''' add one member happy feet test ''' def test_add_one_member(): tree = BinarySearchTree() tree.add('james_bond') assert tree._root.valu...
e75f05d27d2b56833dd19bc78cce126df196c975
jamesbond007dj/py-data-structures-and-algorithms
/data-structures/linkend-list/linked_list.py
2,476
3.953125
4
from node import Node class LinkedList: def __init__(self): self.head = None def insert(self, value): node = Node(value) node.next = self.head self.head = node def includes(self, value): if not self.head: return False current = self.he...
ee3e8a5c4d6ec96cff2a334959ce022a2cc3de5b
ABIATHI/basics
/count.py
129
3.640625
4
n=int(input("enter a integer")) i=0 count=1 while i<=n: r=n%10 count=count+1 n=n//10 i=i+1 print(count)
34b33e0e9ee35770bfe35d644b0cb5fa1aedbc45
saurabh-singh-au13/day03week3code
/multiplication.py
150
4.09375
4
a=int(input("Enter the no. :")) b=int(input("Enter the second no :")) multiplication=a*b; print("multiplication of the given no is :",multiplication)
fc7f44ab1df2dd85600fd7edefcd49e28aee6f6b
MVGasior/Udemy_training
/Variables_Strings_Print/about_variables.py
287
4.0625
4
# Python is case sensitive! text = 'This is a text' #simple assigment here print(text) anotherText = 'this is a text' print(text == anotherText) ''' this is a block comment I can add here more lines without using # ''' print("this is not a comment")
1f7ffaf0ea903cb3557eaab7e4a477b72bca418c
MVGasior/Udemy_training
/While_If_Elseif/if.py
1,141
3.84375
4
age = 27 if age >= 18: print("You are adult and you can buy alcohol") else: print("You are too young to buy alcohol") isDrunk = False if age >= 18 and not isDrunk: print("You are adult and you can buy alcohol") else: print("Sorry, we cannot sell you alcohol") isRestictedArea = Fals...
c5f7b8008aeb45ad54408b333da30ad7b7a8c9e9
MVGasior/Udemy_training
/While_If_Elseif/while_1.py
494
3.921875
4
i=10 imax=0 while i >= imax : print(i, "I like Python") i-=2 else: print("Now i =",i) firstRow=1 lastRow=31 currentRow=1 while currentRow <= lastRow : print("Row number",currentRow) currentRow+=1 number=1 maxNumber=13 while number <= maxNumber : print(number**2) ...
825e69dc82e00143fa1243fd94a2573df0ff132e
MVGasior/Udemy_training
/Inne/for_emails.py
715
3.6875
4
##persons=['Elizabeth','Steven','Sebastian','Margaret','Svetlana','Raphael'] ## ##domain = 'mycompany.com' ## ##for person in persons: ## email = person + '@' + domain ## print('Email for\t', person, '\tis\t', email) ##else: ## print('--end of the list--') data = ['Error:File cannot be open', ...
a2510d4c072bbae473cee9ea22e27c081bd97a4c
MVGasior/Udemy_training
/We_Wy/reading_input.py
1,536
4.3125
4
# This program is a 1# lesson of In_Ou Udemy # Author: Mateusz Gąsior # filename = input("Enter filename: ") # print("The file name is: %s" % filename) file_size = int(input("Enter the max file size (MB): ")) print("The max size is %d" % file_size) print("Size in KB is %d" % (file_size * 1024)) pri...
ed4cca8dda8ae225ae6f4eb391135f97f2cce893
lpicknel/Fibonacci-Calculator
/12.py
138
3.71875
4
a = 0 b = 1 for x in range(1,26): if(x == 1): print (str(x) + ":1") else: c = a + b print(str(x) + ":" + str(c)) a = b b = c
7f748a9adf377359bf6554f3a34be7b41c37aafa
sbyount/pyaut3
/class7/ex1_xml_basics.py
2,135
4
4
from lxml import etree ''' 1a. Using the show_security_zones.xml file, read the file contents and parse the file using etree.fromstring(). Print out the newly created XML variable and also print out the variable's type. Your output should look similar to the following: ​<Element zones-information at 0x7f3271194b48> <c...
bf3b87b39706eba7fcf442ab426831d0eff551c3
enginpost/python-game
/games/tests/test_games.py
2,022
3.546875
4
import unittest from games.enginpost.games import GuessingGame, SpaceShooter class TestGuessingGame(unittest.TestCase): '''Testing the methods of the GuessingGame class''' def test_pluraled_singular(self): game = GuessingGame() result = game.pluraled('game', 'games', 1) self.assertEq...
5144b89764998f8085c0c3f20ef9ac1b0bec36b1
Olgakorotkova90/PY
/task2.py
3,171
3.890625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ############################################################################### # Единичная функция # # Написать функцию, возвращающую свой аргумент # # identity("a") -> "a" def identity(x): return x ##################################################################...
fce5d590306e31d9506de6ce2d0f308029f0e6ca
narcisolobo/april_python_lectures
/lectures/model_relationships.py
3,712
4.125
4
# Three Main Types of Model Relationships # One to One, One to Many, Many to Many # Example of One to One Relationship # Users and Primary Addresses (where users may have only one address) # Examples of One to Many Relationships # Baseball Team to Baseball Players (One team may have many players, but one player may ...
ed8609386f53ce3582e8ddc7dd858c18f024201a
OwenBowler/BCPR301A2
/class_builder.py
3,829
3.84375
4
from method import Method from attribute import Attribute class ClassBuilder: """Create an instance of the object ClassBuilder that contains a list of the objects attributes, methods and relationships >>> a = ClassBuilder() >>> a.build_class("ClassName", ["attribute1: string"], \ ["Method1(in...
4bff67a9b48974c9e0f8a23b75146f7dbcb29af8
soimafreak/Deck
/deck/card.py
1,153
3.953125
4
"""Card Class. Define A Card so that a Deck can be made up of many cards.""" from . import exceptions class Card(object): """Card Class. A card has a some properties: Suite: Hearts, Diamonds, Spades, Clubs Value: 1-11 *NB* This can be 2 values as with an Ace [1 or 11] Number: 1-13 Face: King...
e8967361e05174dcd4cd64751213ecf91ce88814
pynic-dot/Python-code-practice
/Objects and Data Structures Assessment Test.py
955
4.28125
4
# Print out 'e' using indexing s = 'Hello' print(s[1]) # Reverse the string print(s[::-1]) # Two method to produce letter 'o' print(s[4]) print(s[-1]) # Lists Build list [0,0,0] in two different way s = [] for i in range(3): s.append(0) print(s) print([0, 0, 0]) print([0]*3) # Reassign 'hello' in this nested l...
3f90347db78282c99d1d540c0ef2b2bdae756d11
Shiling1234/Algorithms4
/Gcd.py
135
3.6875
4
# 最大公约数 def gcd(p, q): if q == 0: return p r = p % q return gcd(q, r) # test example print(gcd(10, 6))
1c68ec02f6a010839abbf94a34822b6b299f7b1a
jh1992jh/python-books-gui
/gui.py
4,492
3.578125
4
from tkinter import * from backend import Database database = Database('books.db') class Window(object): def __init__(self, window): self.window = window self.window.wm_title("BookStore") label1= Label(window, text="Title") label1.grid(row=0,...
37608d63a5c026adb2f2d86249b19b158c0bd057
isaacgrove/advent-of-code
/day_3/day_3.py
2,761
3.796875
4
# Part 1: # # Tl;dr, you are given a large matrix of the format # [[..#..#..#.], # [#...#..##..]] and so on. # = tree, and you need your # toboggan sled to move down the rows, a specified number # of steps to the right each time, and you assume that the # tree/no tree pattern repeats itself to the right of the # giv...
59522e37cd0d66f6993a1f999fce6ebc2625368f
isaacgrove/advent-of-code
/day_11/day11_part1.py
12,892
3.578125
4
def handle_input(file): '''returns input as a list of ints''' inp = open(file) lst = inp.readlines() for i in range(len(lst)): lst[i] = lst[i].rstrip('\n') new_lst = [] for char in lst[i]: if char == 'L': new_lst.append(1) else: ...
5130c7a837697889f6ca1ef237028d87c37b8d52
petitlapin86/high_stakes_stakes
/wallet.py
1,132
3.578125
4
#Wallet Class keeps provides money to bet with and tracks winnings/losses class Wallet: def __init__(self,wallet): #__init__ method with private __wallet self.__wallet = wallet def __check_money_in_wallet(self): try: if self.__wallet <= 0: #If user runs out of money raise an ...
f63ef42edd8e6859bef40dd3d44ca163b913d108
martinsunyi/Python-Trial
/input trial.py
710
3.734375
4
''' print "Enter F" F=input() C=float(5)/9*(F-32) print F,'F=' ,C, 'C' import urllib2 file = urllib2.urlopen('http://helloworldbook2.com/data/message.txt') message = file.read() print message ''' ''' FN='Martin' SN='Sun' print FN,SN print "1ԪǮӲǣ" _1RMB=int(raw_input()) print "5ëǮӲǣ" _05RM...
0c0731b56a5d21f854cb82fa2205102d7ebbba20
kakamband/demo-blackjack
/classes/hand.py
1,108
3.671875
4
class Hand: # This init serves no other purpose than to generate # new instances of Hand. Must remember to do this! def __init__(self): self.cards = [] self.stand = False self.busted = False self.contains_ace = False self.natural = False def clear(self): ...
60da96d2a841fa0dbcf3e67f50e914092edafa76
joaquimgomez/FIB-APA-Pulsars
/code/Py/Linear Model 1 - Nearest-neighbors.py
4,200
3.734375
4
#### # Autores: Ferran Velasco y Joaquin Gomez #### # coding: utf-8 # # Linear Model 1 - Nearest-neighbor # In[23]: import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, accuracy_score from auxiliars import * import pickle #...
ca8422d425491cb759cf7397c7fdd16ac5f42d36
Wenslaus-Makumba/address-book1
/GUI/new.py
1,474
3.703125
4
"""New Address Book Window Authors: group 5 Requests users for the name of their address book. """ import tkinter as Tk import db import gui import newcw class New_AddBookWindow(object): def ok(self): """Open the user specified address book.""" book_name = self.book_name.get() if len(book_name) > 1: db.d...
c6fd9774176663a75853ab33bd9ac42c5573f65f
ursu1964/Libro2-python
/Cap2/Programa 2_9.py
1,576
4.125
4
# -*- coding: utf-8 -*- """ @author: guardati Problema 2.9 """ def aparece_dos_veces(palabra): """ Determina si todas las letras de la palabra están exactamente 2 veces. Parámetro: palabra: de tipo str. Regresa: True si la palabra cumple la condición y False en caso contrario. ...
59bc3839861d8d3671296e46e3e10829d8258cd4
ursu1964/Libro2-python
/Cap3/Ejemplo 3_2.py
2,287
3.828125
4
# -*- coding: utf-8 -*- """ @author: guardati Ejemplo 3_2 Algunas operaciones con diccionarios. """ nom_meses = {1: 'enero', 2: 'febrero', 3: 'marzo', 4: 'abril', 5: 'mayo', 6: 'junio'} puntaje = {}.fromkeys(['futbol', 'basquetbol', 'tenis', 'natación'], 5) frutas = {'manzana': 34, 'pera': 45} # Agrega un nu...
38d5548e7ae23f2baff14148fdb4cc2fffca0ca8
ursu1964/Libro2-python
/Cap1/Programa 1_10.py
1,307
3.9375
4
# -*- coding: utf-8 -*- """ @author: guardati Problema 1.10 """ def nombres_sin_espacios(lista): """ Genera una lista con los elementos de la lista recibida que no contengan espacios en blanco. Parámetro: lista: de tipo list. Almacena cadenas de caracteres. Regresa: Un...
115f3a6e85b2e462390ecee8357d0dd3af208161
ursu1964/Libro2-python
/Cap3/Ejemplo 3_3.py
1,792
3.921875
4
# -*- coding: utf-8 -*- """ @author: guardati Ejemplo 3_3 Diccionarios: aplicación de funciones predefinidas y operadores. """ # Se importa el módulo operator para poder ordenar por valor. import operator num_meses = {'ene': 1, 'feb': 2, 'mar': 3, 'abr': 4, 'may': 5, 'jun': 6} nom_meses = {1: 'enero', 2: 'fe...
67fb7e07d365a01c1a2bb191ed873e8115cc0dd0
ursu1964/Libro2-python
/Cap4/Programa 4_4.py
881
3.859375
4
# -*- coding: utf-8 -*- """ @author: guardati Problema 4.4 """ import array def suma_arre1(arreglo): """ Suma los elementos de un arreglo numérico. Parámetro: arreglo: de tipo array. Almacena datos de tipo int o float. Regresa: La suma de los números contenidos en el arreg...
1d6facab8f9b20bf10e920614106ffdee72372e0
ursu1964/Libro2-python
/Cap4/Programa 4_13.py
507
3.75
4
# -*- coding: utf-8 -*- """ @author: guardati Problema 4.16 Calcula e imprime la desviación estándard de un grupo de números. """ import array import arreglo datos = array.array('f') n = int(input('\nIngrese total de números: ')) arreglo.lectura(datos, n, float, 'Ingrese un número: ') try: ds = arre...
78afbd22e5cce8d0372897f25654046bc4c7a3b8
ursu1964/Libro2-python
/Cap1/Programa 1_18.py
2,124
4.09375
4
# -*- coding: utf-8 -*- """ @author: guardati Problema 1.18 """ def uno_y_uno(lista1, lista2, separador): """ Genera una nueva lista mezclando los elementos de las listas dadas y separador por los caracteres almacenados en separador. Parámetros: lista1: de tipo list. lista2: de t...
7af831e19af6f8fd26a5e83ae00c391ff9bfcd15
ursu1964/Libro2-python
/Cap1/Ejemplo 1_2.py
1,392
4.1875
4
# -*- coding: utf-8 -*- """ @author: guardati Ejemplo 1_2 Operaciones con listas. """ dias_laborables = ["lunes", "martes", "miércoles", "jueves", "viernes"] colores_primarios = ['rojo', 'verde', 'azul'] precios = [205.30, 107.18, 25, 450, 310.89, 170.23, 340] # ============================================...
697aa7c35c1b75171bf80ee92389b5c0c7b0df59
ursu1964/Libro2-python
/Cap3/Programa 3_4.py
1,453
3.953125
4
# -*- coding: utf-8 -*- """ @author: guardati Problema 3.4 Se tiene un diccionario con nombres y teléfonos de amigos: una agenda. El programa permite agregar amigos y teléfonos, cambiar y eliminar el teléfono de un amigo. """ def pide_opcion(): """ Despliega opciones de trabajo con la agenda. Regre...
d17df75efeb8bd6c03f7556d015573d1c4997883
ursu1964/Libro2-python
/Cap1/Programa 1_1.py
1,378
4.03125
4
# -*- coding: utf-8 -*- """ @author: guardati Problema 1.1 """ def primero_y_ultimo(lista): """ Obtiene el primero y el último elemento de la lista. Parámetro: lista: de tipo list. Regresa: Una tupla formada con el primero y el último elemento de la lista. Lanza: ...
394eec34dbe6cd23b24e6f75c02049969ef8a099
ursu1964/Libro2-python
/Cap3/Programa 3_11.py
1,186
3.953125
4
# -*- coding: utf-8 -*- """ @author: guardati Problema 3.11 """ def obtiene_largo_palabras(cadena): """ Obtiene y regresa la longitud de cada una de las palabras que aparecen en una cadena de caracteres. Parámetro: cadena: de tipo str. Regresa: Un diccionario que almacena la...
f4b7fcd1f047dc08610c0a49b3ee919e442eb2c2
ursu1964/Libro2-python
/Cap1/Ejemplo 1_9.py
2,024
3.859375
4
# -*- coding: utf-8 -*- """ @author: guardati Ejemplo 1_9. Ejemplos de uso de las funciones flter(), map() y zip(). """ def multiplo_de4(numero): return numero % 4 == 0 def cubo(x): return x ** 3 def es_mayusc(c): return c.isupper() def conv_mayus(c): res = c if c.islower(): ...
edc27525b18a71a517718aff0df915c2b3cc78ec
ursu1964/Libro2-python
/Cap4/Programa 4_8.py
1,341
3.796875
4
# -*- coding: utf-8 -*- """ @author: guardati Problema 4.9 Elimina los elementos de un arreglo que son múltiplos de un valor dado. Los datos del arreglo se leen de un archivo binario. """ import array import arreglo def elimina_multiplos(arrenum, numero): """ Elimina del arreglo todos los elementos q...
567f0b9e9fb99db6db6abcb91ce438f9b81e350e
ursu1964/Libro2-python
/Cap1/Programa 1_14.py
780
3.65625
4
# -*- coding: utf-8 -*- """ @author: guardati Problema 1.14 """ def calcula_long(frase): """ Genera una lista con la longitud de cada una de las palabras que forman la frase. Parámetro: frase: de tipo str. Las palabras están separadas por espacios en blanco. Regresa: Una l...
4a0f20530ed75499ffd8b6a2ad7929d8cc9c271b
HamdanAlWahidan/UAS-Bahasa-Pemrograman
/UAS Pemrograman/model/daftar_nilai.py
2,076
3.6875
4
data = [] data = {} def tambah(): print("=======Tambah Data=======") nama =input("Nama : ") nim =input("Nim : ") tugas =int(input("Masukan Nilai Tugas : ")) uts =int(input("Masukan Nilai UTS : ")) uas =int(in...
c14c88a6d6391b1105877fa0d53f0ebad01501f7
hvas01/vietlott
/vietlott.py
3,502
3.90625
4
__version__ = "1.0" """ Generates Vietlott ticket number Author: Anh Hong File Name: main.py Vietlott 6/55 Play rule: You have to choose 6 different numbers to make a combination. Each number is between 1 to 55. Problem: You have 1 in 28,989,675 chance of winning the Vietlott Power 6/55. How to improve the chance o...
01772a00d954d281d138c5d467aaf4dff2740769
mgxian/study-refactor
/encapsulation/subsitute-algorithm/v1.py
245
3.6875
4
def foundPerson(people): for i in range(len(people)): if people[i] == "Don": return "Don" if people[i] == "John": return "John" if people[i] == "Kent": return "Kent" return ""
e818d1807425d345674f6bfae9820f548dd8afe4
siddarthjha/Opencv
/GUI Features/01_Image.py
1,402
4.09375
4
import numpy as np import cv2 # Load an color image in grayscale # img = cv2.imread('a.jpg', 0) img = cv2.imread('a.jpg') # 1. This function is used to read image cv2.imshow('image', img) # 2. This function is used to display the image cv2.waitKey(0) # 3. This is keyboard binding fun...
1f7dec9eafd0f765b887e5905f9bb8211a648fc3
osmanseytablaev/Learn-Python
/Functions/keyword_only.py
374
4.0625
4
def total(initial=5, *numbers, extra_number): count = initial for number in numbers: count += number count += extra_number print(count) total(10, 1, 2, 3, extra_number=50) total(10, 1, 2, 3) # Вызовет ошибку, поскольку мы не указали значение # аргумента по умолчанию для 'extra_number'.
7734f3f6894235b5023bf22eea4facbb7ac4ed27
MihaiColbasevici/Instructiunea_FOR
/Problema_6_FOR.py
463
3.75
4
n = int(input("Dati un numar: ")) s1 = 0 s2 = 0 s5 = 0 s6 = 0 for num in range(1, n): s1 += num s2 += ((num - 1) * num) s5 += (num / (num + 1)) s6 += (20 + num) s3 = 1 factorial = 1 for num in range(2, n): factorial *= num s3 += factorial s4 = 0 for num in range(1, ((n * 10) + 1)...
6f9f289550c7674b00621066d9c57ca7b7254efe
Injector-Spenral/city_model
/model.py
513
3.640625
4
import math class zone: def __init__(self, pos, ring): self.pos = pos # The position around the circle. 0 - 15 self.ring = ring # The inner distance of the circle. 0 - city.radius self.area = math.pi * (2 * self.ring + 1) / 16 class city: def __init__(self, radius, population): ...
f7ec63d677c8c7a5c4a4a75ce53b78fe5dc72a39
Magnum-07/Python-questions-and-Data-structures
/Questions/two_sum.py
366
3.78125
4
A = [3, 5, 2, -4, 8, 11] target_sum = 7 # Time Complexity(T.C.) = O(n) # Space Complexity(S.C.) = O(n) def two_sum(arr, target_value): # To solve this question by using of hashing seen = dict() for i, n in enumerate(arr): if n in seen: return [seen[n], i] seen[target_value ...
fc152e07f65962afa33c9267795bbe9292a48e8b
Bluespongecake/cs50-2020-solutions
/pset7/houses/roster.py
991
3.765625
4
import sys from sys import argv from cs50 import SQL def main(): if len(argv) != 2: sys.exit("Usage: roster.py house") # make the house lowercase houseq = argv[1].lower() # ensure that house exists houses = ["slytherin", "gryffindor", "ravenclaw", "hufflepuff"] if houseq...
26261ec94637c1badc4c941b05575f5e3d4960ff
RichardRivaldo/Machine-Learning
/Python/Regression/Simple Linear Regression/Simple_Linear_Regression.py
1,466
3.9375
4
#%% # Simple Linear Regression # No need Feature Scaling #%% # Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #%% # Dataset data = pd.read_csv("") #%% # Features and Dependent Variables X = data.iloc[:, :-1].values y = data.iloc[:, -1].values #%% # Splitting The Dataset from sklea...
5dadd3534717ea51e683122da796aedf08a474d9
ribizly/python
/lab2_task3.py
620
3.59375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import argparse import collections from itertools import chain parser = argparse.ArgumentParser(description='E-mail parsing help') parser.add_argument('infile',nargs="?",type=file,help="Input file") try: args = parser.parse_args() except Exception as e: pars...
b04d63437e67fb2089aded2c6d8c33b6e3af4499
Brandonlac/Fraction-class
/Fraction.py
5,047
3.890625
4
# Fraction.py creates a class of fractions that can be used for operations class Fraction: def __init__(self, num, den): if (not isinstance(num, int) or not isinstance(den,int)): raise Exception("Sorry, only intergers") if den == 0: raise Exception("Sorry, infinity...
2ce0d181669dfa62b9fb9bae6584aceff36c53de
yujie-hao/python_basics
/datatypes/numbers.py
237
3.671875
4
a = 5 print(a, "is of type", type(a)) a = -1.1 print(a, "is of type", type(a)) a = 9.7e3 # scientific notation print(a, "is of type", type(a)) a = 1e-1 print(a, "is of type", type(a)) a = 0xff # 255 print(a, "is of type", type(a))
d1af7d34089b172801b7bef550955595791f2422
yujie-hao/python_basics
/datatypes/type_conversion_and_casting.py
1,689
4.75
5
# ================================================== """ https://www.programiz.com/python-programming/type-conversion-and-casting Key Points to Remember 1. Type Conversion is the conversion of object from one data type to another data type. 2. Implicit Type Conversion is automatically performed by the Python interpret...
1eb815e71e54a98630a1c89715a1a59edabaf461
yujie-hao/python_basics
/objects/class_and_object.py
2,060
4.53125
5
# A class is a blueprint for the object class Parrot: # docstring: a brief description about the class. """This is a Parrot class""" # class attribute species = "bird" # constructor def __init__(self, name, age): # instance attribute self.name = name self.age = age ...
716890750b881482bbf80d024c4fea0df989ad4a
mandyhee/STATS-507-Data-Science-in-Python
/hw4/stat507_hw4.py
4,338
3.765625
4
#!/usr/bin/env python3 #1.1 class Fibo: def __init__(self): self.a = -1 self.b = 1 def __iter__(self): return self def __next__(self): fibo = self.a + self.b self.a, self.b = self.b, (self.a + self.b) return fibo f = Fibo() [next(f) for i in...
9f699b77cd31d86ef8c66737dd5d938f4d4ed42c
Ardnived/Regicide
/src/regicide/data/blueprints.py
12,391
3.8125
4
''' Created on Mar 10, 2013 @author: Devindra An implementation of the blueprints system from Three Hundred Mechanics http://www.squidi.net/three/entry.php?id=165 This system is used to define the various data components of this game. Including Characters, Enemies, Rooms, Skills, Traits, Items, etc. ''' from itertoo...
1bbf8fa168d231d702631d5301d7c7bd91c9aa33
stcolema/ra_chris_wallace
/Data_prep/row_names_to_string.py
1,478
3.59375
4
#!/usr/bin/env python """ Author: Stephen D. Coleman (the D is for David) Studnet nr: 940309160050 Dedication: This script goes out to all of the boys Description: this is a script to generate csv files with row names appended by an X (and thus autmoatically a string) """ # Import statements from sys import argv de...
f694ffef819b0b0562f3db7aa273689353819673
Jeesups/SmallProjects
/Studia/zaj2/ReverseInput.py
135
3.890625
4
def ReverseInput(inp): temp = '' for i in range(-len(inp),0): temp += inp[i+1] print(temp) ReverseInput("Hello")
2a953ece5ab26dd5168d9ab65d070d5d021e7772
Jeesups/SmallProjects
/Studia/Zaj3/BrownMovement/BM1.py
1,335
3.5
4
import numpy as np import random import matplotlib.pyplot as plt class BrownMovement(): def __init__(self): self.input = 0 self.x,self.y = 0, 0 self.lx = [0] self.ly = [0] self.s = 0 self.getMovementAmount() self.calcAngle() self.calcVector() ...
dab2aa49bbd17345c73219802039ed20d181edb2
Jeesups/SmallProjects
/Studia/zaj2/WordGuesser.py
2,318
3.890625
4
import random class WordGuesser(): def __init__(self): #TODO dorobic petle ktora bedzie dzialac do momentu zakonczenia przez uzytkownika. self.gameStart = True self.chances = 6 self.temp_word = "" self.correct_word = "" self.counted_words = 0 self.words = (...
75b416faebe3b9f2762869318c2ebb824f2bc7a7
Jeesups/SmallProjects
/Studia/zaj2/CaseChanger.py
601
3.75
4
class CaseChanger: def __init__(self): self.word = "aAbBcCdD" self.printWord() self.checkCases(self.word) self.printWord() def checkCases(self,word): tempstring = "" for i in range(0,len(word)): if(word[i].isupper()==True): tempstring ...
b6c03300abd431c541a22e975d87f8aca49e931a
alanpropp/compciv-2016
/exercises/0020-gender-detector/i.py
625
3.578125
4
from os.path import join, basename import csv YEAR = 2014 DATA_DIR = 'tempdata' filename = join(DATA_DIR, 'wrangled2014.csv') finalfile = open(filename, 'r') count = 0 bigdatarow = [] reader = csv.reader(finalfile) next(reader, None) #Go through CSV file for line in reader: if int(line[6]) >= 100 : bigdatarow.app...
48fd47973debe27fdf06e7d9335a92e5a5e7eb4e
DagmarMpheio/ExercicioComListasPython
/ExerciciosListas10.py
387
4.125
4
#Faa um programa que crie uma matriz aleatoriamente. O tamanho da matriz deve ser informado pelo usurio. import random print("\t\t Matriz") mat=[] lin=int(input("Digite o numero de linhas: ")) col=int(input("Digite o numero de colunas: ")) for i in range(lin): val=[] for j in range(col): val.ap...
ffbc12245c84286ea41c911f6372af7d5d2f895e
DagmarMpheio/ExercicioComListasPython
/ExerciciosListas4.py
211
3.8125
4
#Ler uma lista com 4 notas, em seguida o programa deve exibir as notas e a mdia. lista=[] for i in range(4): v=float(input("Nota: ")) lista.append(v) print(lista) print("media = ",(sum(lista)/4))
c41acf88fe3397180a249f32743e9b9160d7264d
bohdan167/My-Games
/Connect Four/Text Mode/controller.py
2,174
3.546875
4
from view import * from model import * # import os def readInt(msg): while True: try: num = int(input(msg)) except (ValueError, TypeError): printError('Error! Enter with a valid Integer.') continue except KeyboardInterrupt: printError('User p...
11534c40871b67b8791d4afa1f81b9ee0b516300
nankunda/weektwochallenge
/challenge2week2/vowels/countvowels.py
435
3.78125
4
def vowelcount(txt): if not isinstance(txt, str): raise TypeError('invalid input') vowels = 'aeiou' newtxt = txt.lower() duplicates_none = set(newtxt) duplication = len(newtxt)-len(duplicates_none) vowelstring = "" for a in vowels: if a in duplicates_none: vowel...
065d2e29484a1cd572f43b4e09146a7ee4518eb1
gkupdx/CS350-Project
/_pythonCodeForTestFiles/quicksortHoareOpenSource.py
592
3.8125
4
from random import randint def quicksort(array, low, high): if low < high: p = partition(array, low, high) quicksort(array, low, p) quicksort(array, p + 1, high) def partition(array, low, high): pivot = array[low] i=low-1 j=high+1 while 1: i = i + 1 while arr...
56ec457ac1f60f97e53d3140934077b99b13448b
eempey/AffordabilityMap
/csvMerger.py
573
3.65625
4
# -*- coding: utf-8 -*- hugehairypants = ['huge','hairy','pants'] smallsmoothskirt = ['small','smooth','skirt'] #for i in hugehairypants: # #print(i) # for j in smallsmoothskirt: # print(i +" " +j) import csv with open('shelter-by-tract.csv', 'rb') as f: with open('2006-census.csv', 'rb') as g: ...
5b90635a95718ffaed534730379b3a8898f5413c
rozmeloz/PY
/dz2/task4-10.py
541
4.03125
4
''' 10. Запросить дату (день, месяц, год) и вывести следующую за ней дату. Учтите возможность перехода на следующий месяц, год, а также високосный год ''' from datetime import datetime, timedelta YYYY = int(input ('Введите год YYYY')) MM = int (input ('Введите месяц MM')) DD = int (input ('Введите дату DD')) a = date...
867fcce1d6992bf8108ff0f7232acce9dcbefd3d
rozmeloz/PY
/dz2/task4-1.py
591
4.34375
4
""" 1. Запросить у пользователя его возраст и определить, кем он является: ребенком (0–2), подростком (12–18), взрослым (18_60) или пенсионером (60– ...). """ W = int(input('Введите Ваш возвраст:')) if W < 12: print ('Ребенок') elif 12 <= W <=18: print ('Подросток') elif 18 < W < 60: print ("Взрослый") eli...
6e75b44397c4c5b3da715dc240728ae9cb69998b
rozmeloz/PY
/dz1/task3/NLO.py
596
3.9375
4
L=int(input("Введите количество панелей:")) if (L<0 or L>100) and L.is_integer(): print("Количество панелей не верное") else: A=int(input("Введите высоту панели:")) if A<0 or A>100: print("Высота указана не верно") else: B=int(input("Введите ширину панели:")) if B<0 or B>100: ...
4dceeb3f28505ea62d4dffad4d0cdd386d8e0cbc
rozmeloz/PY
/dz6/task5.py
1,550
3.828125
4
''' Task 5: Создать массив, описывающий чек в магазине. Каждый элемент массива состоит из названия товара, количества и цены за единицу товара. Написать следующие функции. 1. Распечатка чека на экран. 2. Подсчет общей суммы покупки. 3. Получение самой дорогой покупки в чеке. 4. Подсчет средней стоимости одного...
568b8aa877800d951513fbf9098bc7635385633a
rozmeloz/PY
/dz2/task3.py
415
3.796875
4
N = int(input('Введите № билета:')) if N < 0 or N >= 10**6: print("Входные данные не верны") else: N1 = N % 10 N2 = N // 10 % 10 N3 = N // 100 % 10 N4 = N // 1000 % 10 N5 = N // 10000 % 10 N6 = N // 100000 % 10 if N1 + N2 +N3 == N4 + N5 + N6: print ('yes') else: pri...
229cdf563e1822384f3be20da9e2d32eb1ab02a4
rozmeloz/PY
/dz4/task1.py
725
4.03125
4
''' Василий давно занимается математическими аномалиями. Сейчас ему открылся новый способ анализа чисел - берется натуральное число и считается сумма всех его чисел на которое это число делится без остатка(т.е. делителей). Василий хочет автоматизировать эту процедуру. Напишите функцию, которая облегчит его изыскания. '...
01258c0bf6a9b098065eef9146ee290933b30c13
zaxecivobuny/Euler
/57.py
1,973
3.78125
4
from useful import get_primes class Fraction: def __init__(self, numerator = 1, denominator = 1): self.numerator = numerator self.denominator = denominator def invert (self): temp = self.numerator self.numerator = self.denominator self.denominator = temp ret...
b9ed7d85626e572f29ffd0b08c1384011be730ff
zaxecivobuny/Euler
/38.py
784
3.59375
4
def digitize(n): a = str(n) b = [] for i in a: b.append(int(i)) return b def undigitize(l): temp = l[:] n = temp.pop() place = 10 while len(temp) >= 1: n += (temp.pop() * place) place *= 10 return n def concatenum(*args): c = [] for i in args: c += ...
1113912ad9906d8a377a1a202bf638986aee7e12
zaxecivobuny/Euler
/27.py
963
3.5625
4
import math def get_primes(max_number): known_composites = {} i = 2 while i < max_number: if not i in known_composites: yield i known_composites[i*i] = [i] else: for j in known_composites[i]: known_composites.setdefault(i + j, []).append(j) del known_composites[i] i += 1 def prime(n): n = ab...
bc0ee586d808ef15c92a3b8d61bed8ddebc88393
zaxecivobuny/Euler
/test0.py
636
3.625
4
import math def get_primes(max_number): known_composites = {} i = 2 while i < max_number: if not i in known_composites: yield i known_composites[i*i] = [i] else: for j in known_composites[i]: known_composites.setdefault(i + j, []).append(j) del known_composites[i] i += 1 def prime(n): n = a...
bfd0695ed06d4d02e1e0828927a4b3c885e9a7ef
imthou/dat8
/code/05-basic-regression.py
950
3.578125
4
# -*- coding: utf-8 -*- """ Basic regression through the origin. """ import numpy as np import matplotlib.pyplot as plt # Cases packed vs time time = [10.15, 2.96, 3.00, 6.88, 0.28, 5.06, 9.14, 11.86, 11.69, 6.04, 7.57, 1.74, 9.38, 0.16, 1.84] cases = [24, 6, 8, 17, 2, 13, 23, 30, 28, 1...
6036ace228cdbde62232b75fdd8d70a2131da9c0
RahulKachhap/python-files
/bankatm.py
2,696
3.859375
4
import random #registration for a bankaccount def registration(): global deposit,pin,accountno name=input("enter your name:") adharid=int(input("enter your adharid:")) phoneno=int(input("enter your phoneno:")) deposit=int(input("enter how much money you want to deposit")) #if(len(adh...
acc3febb1a6b9ef659302ebfbeb9d2848abf049c
rfukutome/TTAI
/main_bkup.py
3,226
3.84375
4
from pip._vendor.distlib.compat import raw_input X = ' X ' O = ' O ' BLANK = ' ' MINIMUM_MOVES_TO_WIN = 4 class GameBoard: def __init__(self): self.__number_of_moves = 0 self.__game_board = [[BLANK, BLANK, BLANK], [BLANK, BLANK, BLANK], ...
e0d50f9c9c2ab83a18fe1e310f07a25f3686c9d5
cselab/covid19
/epidemics/utils/date.py
332
3.84375
4
import datetime def date_fromisoformat(s): """Parse a YYYY-MM-DD date format to a datetime.date object. Reproduces Python 3.7's datetime.date.fromisoformat. """ dstr = s[0:10] # sometimes s comes with hr, sec and ms year, month, day = dstr.split('-') return datetime.date(int(year), int(month)...
046295410b2612e9b46dba2d9e3de5ef17a1aacb
dmitry5in/Work_File_Read_and_write
/Task_3.py
964
3.65625
4
import os def add_txt_file(): file_list = [x for x in os.listdir() if x.endswith(".txt")] return file_list def sort_file(): list_file = add_txt_file() new_list = [] for file in list_file: with open(file, "r", encoding='utf-8') as read_file: dict_list = {} lines = ...
07089002303cf976ef9d9e1c544b570319888dea
pjdurden/VenueMonk
/pythagorean triplets.py
1,681
3.765625
4
#Prajjwal Chittori #Delhi Technological University(2k18/co/249) #8700694107 #prajjwalchittori_2k18co249@dtu.ac.in import math class Solution: def tripletsBruteForce(self, sums:int) -> int: #since a<b<c then we can safely assume that a can be at most #a<sum/3 and a<b<s/2 for i in ran...
f822488ab6d42dd978e5cb80086b8e46e4a22254
hschilb1/Intro-to-Python
/breakfast.py
551
3.890625
4
seconds = 1 minutes = 60 * seconds hours = 60 * minutes depart = 6 * hours + 52 * minutes miles_run_easy = 2 * (8 * minutes + 15 * seconds) miles_run_hard = 3 * (7 * minutes + 12 * seconds) total_time_run = miles_run_easy + miles_run_hard + depart hours2 = total_time_run // hours part_hour = total_time_run...
74b08a6b818ce8f090c19542024a6d20f1c7f9e0
VerdAlvae2245/backup
/Mini.py
607
4.09375
4
# Eduardo Verdugo Alvarez #hour 1 print("Welcome to To Do List") todoList = [ ] while True: print("Enter a to add a item") print("Enter r to remove a item") print("Enter p to print the List") print("Enter q to quit") choice = input("Choose: ") if choice == "q": break elif choice == "a": c...
f0841971061897c756c507155edad6f14c5a2c89
SandyHoffmann/ListasPythonAlgoritmos
/Lista 8/SH-PCRG-AER-Alg-08-Ex-03.py
454
4
4
def palindromo(palavra): #Colocar validação para simbolos de pontuação e etc palavra = palavra.replace(' ','') if palavra == "": return (True) elif palavra[0] == palavra[-1]: palavra = palavra[1 : -1] return(palindromo(palavra)) else: return False def main(): p...
578790c353fac9749b20bc7f0436e7aa65213c45
SandyHoffmann/ListasPythonAlgoritmos
/Lista 6/SH-PCRG-AER-Alg-06-Ex-07.py
487
3.640625
4
def calcular_div(numero): divisores=[] for x in range(1,numero+1): if numero%x==0: divisores.append(x) return divisores def verificar_perfeicao(numero): lista = calcular_div(numero) soma = 0 for x in range(len(lista)-1): soma+=lista[x] if soma == numero: ...
a9e8b54eab24dc99f7df766a39e54ee0127651d0
SandyHoffmann/ListasPythonAlgoritmos
/Lista 2/SH-PCRG-AER-Alg-02-Ex-10.py
241
3.71875
4
#Pedindo matricula data = int(input("Diga a matricula usando a formatação AASDDD: ")) #Pegando o ano ano = data//10000 #Pegando o semestre semestre = data//1000 - ano*10 #Mostrando no console print(f'Ano: {ano}, Semestre: {semestre}')