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
cae5738e2bbd39222ac3f00323b494995aca6819
tanyastropheus/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/9-multiply_by_2.py
123
4.15625
4
#!/usr/bin/python3 def multiply_by_2(my_dict): new_dict = {x: y*2 for (x, y) in my_dict.items()} return (new_dict)
5f18c995a0e312204cb1fa7d8a82eade759e6911
tanyastropheus/holbertonschool-higher_level_programming
/0x0A-python-inheritance/4-inherits_from.py
520
3.9375
4
#!/usr/bin/python3 def inherits_from(obj, a_class): """check if an object is an instance of a subclass of the specified class. Args: obj: a given object a_class: the specified class Returns: True if the object is an instance of the subclass of a_class; False if the object i...
845057019717a97542123b135b52bea060b5dd29
tanyastropheus/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/0-square_matrix_simple.py
176
3.640625
4
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): matrix_squared = [] for i in matrix: matrix_squared.append([j**2 for j in i]) return matrix_squared
115b477fb7b86d34e9df784d43bfe29b2dcbf06a
tanyastropheus/holbertonschool-higher_level_programming
/0x0B-python-input_output/1-number_of_lines.py
364
4.28125
4
#!/usr/bin/python3 def number_of_lines(filename=""): """count the number of lines in a text file Args: filename (str): file to be counted Returns: line_num (int): number of lines in the file. """ line_num = 0 with open(filename, encoding="UTF8") as f: for line in f: ...
84b3e15da6389410a283888168265bd20ee0f086
tanyastropheus/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/rectangle.py
4,019
3.875
4
#!/usr/bin/python3 """Module contains class Rectangle inherited from class Base """ from models.base import Base class Rectangle(Base): """Produces a rectangle based on given parameters. """ def __init__(self, width, height, x=0, y=0, id=None): # accepts parameters """Initializing instances o...
02b19bbbb632b1df6736fe16e5377307faeec9d6
tanyastropheus/holbertonschool-higher_level_programming
/0x0A-python-inheritance/2-is_same_class.py
348
3.75
4
#!/usr/bin/python3 def is_same_class(obj, a_class): """checks if the object is exactly an instance of the specified class Args: obj: a given object. a_class: given class. Returns: True id the object is exactly an instance of the specified class; False if not. """ ...
a5a9508c4bd7da58951b1968f02ec0341cb4d360
syedh123/OPENSOURCE_SDP_PROJECT
/SET 5/Set5-q2.py
391
4.09375
4
print("The program works for the following range of inputs : \n") print("48-57, 65-90, 97-122 \n") ch=int(input("\nEnter the number from the range above - ")) flag=0 while flag!=1: if 47<ch<58 or 64<ch<91 or 96<ch<123: print("\n\tThe character for the given ASCII value is -> %s"%(chr(ch))) flag=1 else: ch=int(...
bec32eb432ecf827adc995a5e176d58291c4b1f0
syedh123/OPENSOURCE_SDP_PROJECT
/SET 4/Set4-q3.py
179
4.21875
4
string=input("\nEnter any string - ") a=input("Enter a character to find frequency of - ") print ("\n\tThe frequency of character in the given string is - %d\n"%(string.count(a)))
b892044a6357a29a857857ffb37c5b438a9ef785
AYamaui/Practice
/sort/insertion_sort.py
414
4.21875
4
# Complexity: O(n^2) for swaps / O(n^2) for comparisons def insertion_sort(array): for i in range(1, len(array)): j = i while j >= 1 and array[j-1] > array[j]: aux = array[j-1] array[j-1] = array[j] array[j] = aux j -= 1 return array if __nam...
e5c330015f0bfd80b32ebcae0c855184502546f7
AYamaui/Practice
/graphs/Dijkstra.py
1,537
3.5
4
from graph import Graph def initialize_costs(graph, start_vertex): costs = {} for vertex in graph.adjacency_list: costs[vertex] = float("inf") costs[start_vertex] = 0 return costs def extract_min(pending_edges): min_weight = float('inf') min_idx = None for idx, (v1, v2, weight...
fafd561f1c3020231747a3480278bcf91c457a82
AYamaui/Practice
/exercises/cyclic_rotation.py
1,998
4.3125
4
""" An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved ...
c0bea3ea2ac54ad68f74ed0474afc99a67d68663
AYamaui/Practice
/data_structures/my_binary_search_tree.py
1,868
3.953125
4
class Node: def __init__(self, value, parent): self.value = value self.left_child = None self.right_child = None self.parent = parent def __str__(self): print(self.value) class BinarySearchTree: def __init__(self): self.root = None @staticmethod ...
b18b358947ec235fdb97f5d6cca555f43248f4b0
yenphuong1993/PythonBasic
/bai1.py
816
3.921875
4
from math import sqrt class Triangle(): def __init__(self,a,b,c): self.a1 = a self.a2 = b self.a3 =c def perimeter(self): p = self.a1+self.a2+self.a3 return p def area_Triangle(self): triangle1 = Triangle(self.a1,self.a2,self.a3) p = triangle1.perimet...
de6b4368af733e925d77800c3ef171551c8508e1
jswright-dstl/Fuzzy-Felt-Framework
/stonesoup/deleter/base.py
981
3.53125
4
# -*- coding: utf-8 -*- from abc import abstractmethod from ..base import Base class Deleter(Base): """Deleter base class. Proposes tracks for deletion. """ @abstractmethod def check_for_deletion(self, track, **kwargs): """Abstract method to check if a given track should be deleted""" ...
0ea680f04aa7565c32416d8c4c22f8423462ec88
DominikaJastrzebska/Kurs_Python
/03_kolekcje/zad_1_set.py
229
3.609375
4
''' 1▹ Utwórz dowolną krotkę, w której elementy mogą się powtarzać. Przekształć ją w set. ''' my_tuple = (1, 2, 3, 4, 'lalala', 2, 'aaa', 'ugdts', 'aa') my_set = set(my_tuple) print(my_set) print(set('qwertttty'))
c7466989b0e8899105ac0fc8cb32998993df8d82
DominikaJastrzebska/Kurs_Python
/02_instrukcje_sterujace/zad_3_calosc_count_signs.py
591
3.953125
4
''' 3▹ W podanym przez użytkownika ciągu wejściowym policz wszystkie małe litery, wielkie litery, cyfry i znaki specjalne. ''' text = input('Podaj zdanie: ') sum_low = 0 sum_title = 0 sum_special = 0 sum_digits = 0 for sign in text: if sign.islower(): sum_low += 1 elif sign.istitle(): sum_titl...
5ebaa485776d02308ad5fa08f12dbb00a5de2981
DominikaJastrzebska/Kurs_Python
/02_instrukcje_sterujace/zad_1_while_celsius_to_farenhait.py
642
4.09375
4
''' 1) Napisz program zmieniający skalę w stopniach Fahrenheita na naszą w Celcjuszach. Program powinen wykonać się w pętli od 0 do 200 stopni Fahrenheit, co 20 stopni. C = 5/9 * (F - 32) # wzór Celsjusz → Fahrenheit Napisz rozwiązanie zarówno z użyciem pętli while jak i for. ''' print() print('Rozwiazanie dla petli w...
201a4ffbce93d385bd1ac06c2818a50fd194bf7d
DominikaJastrzebska/Kurs_Python
/01_typy_zmienne/zad_5_string_palindrome.py
486
3.71875
4
#palindrom ''' 5. Palindrom to wyrażenie brzmiące tak samo czytane od lewej do prawej i od prawej do lewej np.: Kobyła ma mały bok. Pozwól użytkownikowi wprowadzić dowolne zdanie. Następnie sprawdź czy wprowadzone wyrażenie jest palindromem. ''' czy_palindrom = 'Kobyła ma mały bok.' czy_palindrom = czy_palindrom.repl...
ff974a2208552c3f7f7599521db0d3a3f38bca99
DominikaJastrzebska/Kurs_Python
/06_pliki/tekst.py
991
3.53125
4
filename = 'text.txt' # with open(filename, 'r') as f: #r jest domyslne do odczytu tutaj juz nie trzeba zamykac # content = f.read() #bo python sam zamyka ten plik # print(content) # # print('Koniec') # # f = open(filename) # print(f.read()) # f.close() # with open('text.txt', 'r') as fopen: # # print(fop...
cac021334e569979600265e564dfc3b818b225a1
DominikaJastrzebska/Kurs_Python
/01_typy_zmienne/zad_2_string.py
223
3.640625
4
""" 2. Stwórz dwie zmienne s1 i s2 przechowujące dowolne wyrazy, utwórz nowy łańcuch s3, dołączając s2 w środku s1. """ s1 = 'AliBaba23' s2 = 'Alladin Resort' s3 = s1[0:len(s1)//2] + s2 + s1[len(s1)//2:len(s1)] print(s3)
d5a90fc3a2ff2b03b174dfde8b86cd5c8d6c39b3
DominikaJastrzebska/Kurs_Python
/03_kolekcje/zad_10_slownik_square.py
673
3.96875
4
''' 10. Uzytkownik podaje dowolna liczbe N. Napisz, który wygeneruje slownik, wg zasady, ze kazdej liczbie przyporzadkowany jest jej kwadrat (n : n * n). Zalózmy, ze uzytkownik podal N = 8 Wynik: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36 ''' # N = int(input('Podaj dowolna liczbe naturalna N: ')) # dict_square = {x: x**2 f...
dd0be8a5381061aa659aa720a4dfc4bb3a3ccf1f
DominikaJastrzebska/Kurs_Python
/05_christmas_tree/tic_tac_toe_2.py
5,039
3.796875
4
# def create_board(): # # print(' A', ' B ', 'C', end=' ') # print() # for i in range(0, 4): # if i == 0: # print(' ', 'A ', 'B ', 'C', end=' ') # print() # else: # print(i, end=' ') # for j in range(3): # if i == 0: # ...
caf75ac4609ea35b3d6caeb4fdb7e2c0c9647e5f
DominikaJastrzebska/Kurs_Python
/01_typy_zmienne/zad_1_string.py
276
3.59375
4
""" 1. Stwórz zmienną przechowującą wyraz o długości nieparzystej większej niż 7 i zwróć łańcuch złożony z trzech środkowych znaków danego ciągu. """ word = 'armagedon' word_len = len(word) middle = word_len//2 print(word_len) print(word[middle-1:middle+2])
fe7f0886432e6cdcca6a4927900171eb4f7118af
DominikaJastrzebska/Kurs_Python
/09_algorytmy/zad_nwd_nww.py
353
3.671875
4
def nwd(a, b): while b != 0: c = a % b a = b b = c return a def nww(a, b): return a * b / d a = int(input('Podaj pierwsza liczbe: ')) b = int(input('Podaj druga liczbe: ')) d = nwd(a, b) print(f'Najwieksza wspolna wielokrotnosc liczb {a} i {b} to:', nww(a, b), 'a ich najm...
fdbac786899294f71e4f53e60ab26f4617a69baf
DominikaJastrzebska/Kurs_Python
/hakaton_2/generator_linkow/is_id_number.py
448
3.6875
4
def is_id_number(number): if not number.isdigit(): return False else: if len(number) != 5: print('Dlugosc powinna wynosic 5') return False else: return True def get_partner_num(): while True: partner_id = input('Podaj swoj numer id:') ...
be32ef94a8e1f1e52360a4ec64f1c6373ce939aa
DominikaJastrzebska/Kurs_Python
/07_moduly/triangle.py
198
3.515625
4
''' funkcja ktora liczy pole trojkata ''' print('Pole trojkata') def triangle_field(base, height): result = 1/2 * base * height return result a = 5 h = 10 # print(triangle_field(a, h))
a3e637e834569c1eced5a119d773f330ad28771c
DominikaJastrzebska/Kurs_Python
/08_wyjatki/zad_5_bmi/fitmeter.py
576
3.53125
4
import bmi def advice(filename): with open(filename + '.txt') as f: content = f.read() print(content) def main(): try: w = float(input('Give me your weight [kg]: ')) except ValueError as e: print('Err1', e) w = 0 try: h = float(input('Give me your height [...
48fa172c71f661bf3f7c47721597f965a5b6cd66
DominikaJastrzebska/Kurs_Python
/05_christmas_tree/zad_calendar_2.py
795
3.734375
4
def add_zero(value): if value < 10: return '0' + str(value) else: return str(value) def show_calendar(): for month in data: print(month[0]) for day in month[1]: if day % 7 == 0: print() print(add_zero(day), end=' ') ...
e8e3c6a69bbb92e428e7bd2c7a79e35914b75db0
ImperialCollegeLondon/DLH-open
/custom-graders/ASDS-python-notebook-grader-demo/autograder/solutions/solutions.py
436
3.625
4
# GRADED FUNCTION: factors def factors1(n): ## Begin your code here factor_list = [] for i in range(1,n+1): if n % i == 0: factor_list.append(i) return factor_list ## End your code here def factors2(n): ## Begin your code here factor_list = [] for i in range(1...
52ba7b09812b0707888d87d9e2cc137c9043045a
kirsty-tortoise/mathsmap
/mathsmap/home.py
876
3.625
4
""" Defines a class to set up and run the home screen. """ import tkinter as tk from tkinter import ttk as ttk from PIL import ImageTk from mathsmap.screen import Screen class Home(Screen): """ A class that sets up and runs the home screen. """ def __init__(self, master, controller): """ ...
cc55966390a24f66f8a370af4259129675ed6091
YJSYJSYJS/python_machineLearning
/week3/3_9.py
516
3.8125
4
# 1에서 100까지 숫자를 리스트에 append할 것, 단 3, 6, 9는 *를 append할 것 result=[] for i in range(1,101): i_str = str(i) is_changed=False if '3' in i_str: i_str = i_str.replace('3', '*') is_changed=True if '6' in i_str: i_str = i_str.replace('6', '*') is_changed=True if '9' in i_str: ...
04705ca54386860ba764c2e01b43758b4bf9e707
YJSYJSYJS/python_machineLearning
/week2/20144722_윤종수_2-12.py
77
4.09375
4
my_list = ['A', 'b', 'c', 'D'] for m in my_list: if m.isupper(): print(m)
454427f1dd22ab9d841e6ed42d46958f81a809ea
YJSYJSYJS/python_machineLearning
/week3/3_13.py
796
3.640625
4
# 입력받은 수가 prime number인지 판별하는 프로그램을 생각 # prime number(소수): 약수가 1과 자기자신뿐인 2이상의 자연수 # for문과 while문 이용 각각 작성 # 프로그램을 이용하여 1부터 100까지 소수의 합 num = int(input("input number: ")) def is_prime(num): """ 입력받은 수가 소수인지 1부터 num-1까지 나눠떨어질때까지 순회 나눠떨어지면 return True 반복문이 종료되면 return False """ for i in range(2,n...
079d693f23a4e4a2f2c5709d5a56b1bdd7e87835
YJSYJSYJS/python_machineLearning
/week1/20144722_윤종수_2-3.py
88
3.515625
4
a = "a:b:c:d" b = a.replace(':','#') print(b) c = a.split(':') d = '#'.join(c) print(d)
4ac6ed58522f0a1207ed1c6872137bc670b0edd8
YJSYJSYJS/python_machineLearning
/week5/5-4_5.py
722
4.0625
4
# 실습과제 5-4 ## Coordinate 클래스 정의 ## distance()메서드 정의 하나의 인스턴스를 매개변수로 전달받아 거리 계산 ## 인스턴스 새로 생성하여 메서드 테스트 # 실습과제 5-5 ## Coordinate 클래스의 인스턴스화 과정에서 x와 y초기화할 수 있게 ## 초기값 전달되지 않은 경우 기본값 0 import math def square(x): """전달 받은 수의 제곱을 반환한다.""" return x*x class Coordinate: def __init__(self, x=0, y=0): sel...
78fe80be36cbece313072336855d18e35511937c
YJSYJSYJS/python_machineLearning
/week5/5-10_11.py
753
3.734375
4
# 실습과제 5-10(Upgrade Calculator) class Calculator: def __init__(self): self.value = 0 def add(self, val): self.value+=val class UpgradeCalculator(Calculator): def minus(self, val): self.value-=val cal = UpgradeCalculator() cal.add(10) cal.minus(7) print(cal.value) # 실습과제 5-11(Ma...
8e7f4b54e26d34aab86f353b9c16f10d16ad8db2
jbsam2/algo_problem
/swea/D3/5549. 홀수일까 짝수일까.py
123
3.65625
4
for t in range(1,int(input())+1): if int(input()) % 2: print(f'#{t} Odd') else: print(f'#{t} Even')
3c3324346359c52dc1a53ff8d9a1c6bd40fdbd54
jbsam2/algo_problem
/swea/D1/2050. 알파벳을 숫자로 변환.py
101
3.984375
4
alphabets = input() alphabets.upper() for char in alphabets: print(ord(char)-ord("A")+1, end=" ")
a6c58d95478652cc6ed9f128e6c49a5a1fbdc6e2
hvela/movies-shows
/data_storage.py
3,630
4.1875
4
import sqlite3 # from Shows2 import Movies, Implementation from shows_movies import Flix import random class FlixStorage: # method here for adding movies to the database def add_movies(self): # step 1 connect the database conn = sqlite3.connect('databaseFile.db') # step 2 create the c...
86ba02e3c21b8fbcf1b0a93d618abc6c3b778170
BoscoDomingo/KNN
/KNN.py
3,627
4.03125
4
import pandas as pd import numpy as np from collections import Counter import os import sys data_path = "data\iris.data" column_names = ["sepal_length", "sepal_width", "petal_length", "petal_width", "class"] def is_float_list(iterable): """Checks if all elements of an iterable are floats """ ...
ef6a09e40e0fd947e81addf03268cf6b63e9610c
wm-huang/apothecary-app
/objects.py
6,092
4.28125
4
class Item(object): def __init__(self, itemCode, item, price, itemsLeft,unit): """Creates an Item object, initializing its methods. input: 1. itemCode - string - unique code identifying the product 2. item - string - the name of the product 3. price - float - the...
edc7a7ec2e7151d0c36c227d58de0045bac38422
ysyi212/Study
/day01/guess.py
533
3.796875
4
#!/root/ysy/python/bin/python3 '''guess guess which is the right number in 100 ''' import random prompt = ''' choose the number between 0~100: ''' sys_num = random.randint(0,100) times = 0 while times < 5: your_num = int(input(prompt)) if your_num > sys_num: print('Your number is larger~') elif y...
df837e432998355cf428256e88435ab0d4d06a3b
tgloves/MIT-6.0001-CS-and-Programming-in-Python
/ps1/ps1a_v3.py
1,211
3.90625
4
# -*- coding: utf-8 -*- """ Created on Thu May 7 08:01:17 2020 @author: tgloves """ # #Problem Set A Answer annual_salary = float(input("Enter starting annual salary:")) portion_saved = float(input("Enter portion of salary to be saved:")) total_cost = float(input("Enter the cost of your dream home:")) ...
348fa7aaa7a65fea49123b2e1c035568972f2a5d
nickitabogdanow/banksystem
/banking.py
5,627
3.765625
4
import random import sqlite3 conn = sqlite3.connect('card.s3db') cur = conn.cursor() cur.execute('''CREATE TABLE IF NOT EXISTS card( id INTEGER, number TEXT, pin TEXT, balance INTEGER );''') conn.commit() n_1 = None n_2 = None balance = 0 id = 0 card_number_db = None PIN_number_db = None def main_menu(): """отк...
70ec659134822a9109185f89bd7de7ba57a74e82
Rinki8890/PythonTrial
/Sorting/BubbleSort.py
595
3.59375
4
#!/bin/python3 import math import os import random import re import sys # Complete the countSwaps function below. def countSwaps(a): swap = 0 for i in range(len(a)-1): for j in range(len(a)-1): if a[j] > a[j+1]: a[j],a[j+1] = a[j+1],a[j] swap += 1 return...
aa774a88d88699d14f58eb8913a448705dff4cd0
Rinki8890/PythonTrial
/Sorting/MergeSortCountInversions.py
1,853
4.0625
4
inv_counts = 0 def mergeSort(arr, n): return _mergeSort(arr) # This Function will use MergeSort to count inversions def _mergeSort(arr): if len(arr) > 1 : mid = len(arr)//2 lefthalf = arr[:mid] righthalf = arr[mid:] _mergeSort(lefthalf) _mergeSort(righthalf) ...
36b7802c457fea2e0a9fe2cf41c5dddfff9e99e0
Rinki8890/PythonTrial
/ExaWizardTest/prob1.py
696
3.765625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT #Input String #love #velo low vole lovee volvell lowly lower lover levo loved love lovee lowe lowes lovey lowan lowa evolve loves volvelle lowed love s = input().strip() words = input().split() count = 0 #all the ltters of s # for all the ltters of w...
d4399b3d5203780c2581f8665748e07f1fa7a417
Rinki8890/PythonTrial
/AmazonCodeWork/GCD.py
568
3.703125
4
# Python program to find H.C.F of two numbers # define a function def compute_hcf(x, y): hcf = 0 # choose the smaller number if x > y: smaller = y else: smaller = x for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf if __name__ ...
f59def3c79357d4c1ece9c4b6374bd6355a7a873
Rinki8890/PythonTrial
/WordLadder.py
779
3.546875
4
L = ['POON', 'PLEE', 'SAME', 'POIE', 'PLEA', 'PLIE', 'POIN'] Start = 'TOON' End = 'PLEA' count = 0 c=0 Temp = L[c] while (Start != End): #for i in range (4): print("looping times ******************:") for j in range (4): print("START, Temp: ",Start,Temp) itr = 1 if Start[j] == Temp...
fde914f36c5ac5efaaa91173ef057728d077ba05
willingc/new-coder
/gui/sudoku.py
7,947
3.609375
4
import argparse from Tkinter import Tk, Canvas, Frame, Button, BOTH, TOP, BOTTOM BOARDS = ['debug', 'n00b', 'l33t', 'error'] # Available sudoku boards MARGIN = 20 # Pixels around the board SIDE = 50 # Width of every board cell. WIDTH = HEIGHT = MARGIN * 2 + SIDE * 9 # Width and height of the whole board class S...
89c702043dbff6413453099bcd6c42d1435750f4
willingc/new-coder
/dataviz/full_source/dataviz.py
6,209
3.9375
4
#!/usr/bin/env python """ Data Visualization Project Parse data from an ugly CSV or Excel file, and render it in JSON-like form, visualize in graphs, and plot on Google Maps. """ from collections import Counter import argparse import csv import geojson import matplotlib.pyplot as plt import numpy as np def parse(r...
03296d4dcd7002ce4039c90aae31916c79526128
akotwicka/Learning_Python_Udemy
/diplay_options.py
673
4.03125
4
def DisplayOptions(options): for index, opt in enumerate(options): print(index, " - ", opt) print('Select option above or press enter to exit:') a = input() return a options = ['load data', 'export data', 'analyze & predict'] choice = 'x' while choice: choice = DisplayOptions(options) ...
dd3bc0d5ce56eed180bfae36ad3d605d28a9383b
intulint/PythonLearning
/lesson2.py
1,170
3.984375
4
# x = input() # y = input() # try: # print(float(x) + float(y)) # except(ValueError): # print(x + y) # old = int(input('How are you old?\n')) # print('I recommend it ', end='') # if 3<=old<6: # print('"zayac"') # elif 6<=old<12: # print('"mars"') # elif 12<=old<16: # print('"mystery i...
a5ade5e195ba84f8e44a9bfc7e066adfd2fdade4
intulint/PythonLearning
/lessens_warcode.py
784
3.703125
4
def count_bits(num): it = [num] x = [] while True: f, it[0] = cikl(it[0]) x.append(f) print(x[0], it[0]) if it[0] == 1: x.append(1) break elif it[0] == 0: x.append(0) break return sum(x) def cikl(nu...
7517ec0866733fcfdeb4dd2845a6eac24ebc2d1f
Fiquee/OS-lab
/OSLab5/FCFS_DiscSchedule.py
566
3.515625
4
import random import time # test tracks_size = 200 head = random.randint(0, tracks_size) travel = 0 path = [93, 176, 42, 148, 27, 14, 180] print() starttime = time.time() print("head start at", head) for i in path: print("from head", head, "to track", i) print("head traveled", abs(i-head), "tracks") travel...
dc4f162a521988f5fcc9f6400659944c5afae3d0
wertnerve/Eulers-Snake
/Euler3.py
1,069
3.703125
4
#the answer is 6857 #its the biggest prime factor num=600851475143 factorTest=716151937 reverseFactorTest=num rft=reverseFactorTest factorList=[] #factorList=[71, 839 ,1471, 6857, 59569, 104441, 486847, 1234169, 5753023, 10086647, 87625999, 408464633, 716151937] print(factorList) while factorTest<num...
20a18ec8d45800d59d28d148f02673e952332437
anassBelcaid/MachineLearningToronto
/assignments/A1/hw1_code_python/logistic.py
4,086
3.875
4
""" Methods for doing logistic regression.""" import numpy as np from utils import sigmoid from scipy.special import xlogy def logistic_predict(weights, data): """ Compute the probabilities predicted by the logistic classifier. Note: N is the number of examples and M is the number of features ...
bf12ff6dd1f7b4c693c7cd3b35d760e3ec6614af
matt969696/holbertonschool-higher_level_programming
/0x0A-python-inheritance/100-my_int.py
420
3.640625
4
#!/usr/bin/python3 """ Module that contains a simple classe : MyInt """ class MyInt(int): """Simple class """ def __eq__(self, other): """ Modify the equal method""" if int(self) == int(other): return False return True def __ne__(self, other): """ Modify the n...
5f404ca2db9ce87abe64ba7fd1dd111b1ceeb022
matt969696/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/100-matrix_mul.py
1,965
4.25
4
#!/usr/bin/python3 """ 2-matrix_mul module - Contains simple function matrix_mul """ def matrix_mul(m_a, m_b): """ Multiplies 2 matrices Return the new matrix The 2 matrix must be non null list of list The 2 matrix must be multiable All elements of the 2 matrix must be integers or floats "...
64a3f95ace1e85fa65403481653a31092bf0a330
matt969696/holbertonschool-higher_level_programming
/0x03-python-data_structures/9-max_integer.py
209
3.640625
4
#!/usr/bin/python3 def max_integer(my_list=[]): if len(my_list) == 0: return None mymax = my_list[0] for elem in my_list: if elem > mymax: mymax = elem return mymax
bdd88bd67f25727f2e088e623f9363d271252afd
matt969696/holbertonschool-higher_level_programming
/0x08-python-more_classes/101-nqueens.py
1,660
3.9375
4
#!/usr/bin/python3 """ N Queens main file. For creating a program that solves the nqueens algorithm. """ import sys if len(sys.argv) != 2: print("Usage: nqueens N") exit(1) try: n = int(sys.argv[1]) except: print("N must be a number") exit(1) if n < 4: print("N must be at least 4") exit(1...
d2033d5cc22b1d254e66b4d23e294b7299157861
Floozutter/silly
/python/hammingweightmagic.py
732
4.03125
4
""" https://en.wikipedia.org/wiki/Hamming_weight https://dl.acm.org/doi/10.1145/367236.367286 """ from argparse import ArgumentParser from typing import Iterator def magic(z: int) -> Iterator[int]: while z: yield z z &= z - 1 def parse_args() -> int: parser = ArgumentParser() parser.add_a...
6aef4c2a49e81fe1fe83dacb7e246acee51ab11c
Floozutter/silly
/python/montyhallsim.py
2,038
4.15625
4
""" A loose simulation of the Monty Hall problem in Python. """ from random import randrange, sample from typing import Tuple Prize = bool GOAT = False CAR = True def make_doors(doorcount: int, car_index: int) -> Tuple[Prize]: """Returns a representation of the doors in the Monty Hall Problem.""" return tup...
ebf7adb80f656ef83d8a413beb144160b1a8e46d
Floozutter/silly
/python/numerals.py
3,652
4
4
""" A module that names integers as attributes using English number words. """ from typing import Any, List # Global constants. LOWERBOUND = -1000 # inclusive UPPERBOUND = 1001 # exclusive # Helper function for concatenating English number words. def concat(a: str, b: str, separator: str = " ") -> str: """C...
baef5ffbfa651935af38e58a1ff119fc2a8417d1
chloeegong/covidsimulator
/main.py
595
3.703125
4
import Covid def main(): option = "" while option != '0': print(""" 1 COVID-19 Simulation (No Lockdown) 2 COVID-19 Simulation (Lockdown) """) option = input() if option == "1": covid = Covid.Covid(60) day = int(input("Enter the range of ...
e69846094fd25b6f5b101f78879ce7fde4de03c1
ariquintal/StructuredProgramming2A
/unit2/project/For1.py
632
4
4
import sys if __name__ == "__main__": for m in range(1,13): print("\nMonth:", m) if m==2: for day in range(1,29): print("Day:", day) elif m== 4: for day in range(1,31): print("Day:", day) elif m == 6: for day in ran...
c7e11b86d21975a2afda2485194161106cadf3b3
ariquintal/StructuredProgramming2A
/unit1/activity_04.py
338
4.1875
4
print("Start Program") ##### DECLARE VARIABLES ###### num1 = 0 num2 = 0 result_add = 0 result_m = 0 num1 = int(input("Enter number1\n")) num2 = int(input("Enter number2\n")) result_add = num1 + num2 result_m = num1 * num2 print("This is the add", result_add) print("This is the multiplication", result_m) print ("P...
a017f93a8053bcacc267ad2cb5c7e142f60ae0b1
ogyogy/atcoder
/tenka1-2018-beginner/a.py
82
3.65625
4
s = input() length = len(s) if length == 2: print(s) else: print(s[::-1])
70b6d4b90c5790d3fde8f824dfda27bfbb324c86
OnMyWayBackHome/Rotaviz-3.0-python
/tmp-Writer.py
1,548
3.59375
4
def xmlTags(xml): import xml.etree.ElementTree as ET from collections import defaultdict xml_tree = defaultdict(list) attribs = defaultdict(list) root = ET.fromstring(xml) attrib = set() for a in root.findall('animal'): print("findall", a.attrib) for b in list(a.attrib.key...
13d591d8b3a63cd14c9052330664d3542d061781
TokyoTech-Astro/Kousyukai2020
/第2回/kousyu2_2_ans.py
312
3.8125
4
def main(n): listA = [0] * (n + 1) return Fibonacci(n,listA) def Fibonacci(n,listA): if n <= 2: return 1 if listA[n] > 0: return listA[n] fn = Fibonacci(n-1, listA) + Fibonacci(n-2, listA) listA[n] = fn return fn if __name__ == "__main__": print(main(500))
4f60ef5f035d0e9aac3b3e37ee32a782157888cf
mohamedabo/Software-Design-And-Implementation
/PPM driver.py
2,151
3.59375
4
###################################################################### # Author: Abdirahman Mohamed # Username: mohameda # # Assignment: A11: PPM # # Purpose: Navigating large code bases #Working with classes, particularly creating new methods and calling them #Explore different image encoding methods, and understand ...
603c0d62e4a4aa1b09c076081f753a34ecc19893
byronhallett/towers-of-hanoi
/towers.py
3,400
3.703125
4
class GameError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class State: def __init__(self, disc_count): # Stack all discs on the left column self.disc_count = disc_count self.left = [i for i in range(disc_cou...
0b0d6d328ad2e2a9fd9aab7460392fa40f08a4bc
ata-jamil/Testscodedocs
/sut & tests/test_sut.py
2,068
3.5625
4
import unittest from sut import Account class TestSut(unittest.TestCase): def setUp(self): # Setting up accounts for tests self.fab = Account("Fabian", 3000) self.ata = Account("Ata", 2500) # ---------------Desposit & Balance Check -------- def test_deposit(self): ...
df10e17b0e13a965b32fda8db67bcaba3743938a
candacewilliams/Intro-to-Computer-Science
/kind_of_a_big_deal.py
403
4.125
4
minutes = float(input('Minutes: ')) num_hours = float(minutes / 60) num_hours = int(num_hours) #print(num_hours) num_minutes = float(minutes % 60) whole_minutes = int(num_minutes) #print(num_minutes) num_seconds = minutes - int(minutes) num_seconds = num_seconds * 60 num_seconds = round(num_seconds) p...
c5239b303a99370ab99df458f758eaef7af3cbac
candacewilliams/Intro-to-Computer-Science
/day_of_year.py
840
4.25
4
month = input('Insert Month: ') day = int(input('Insert Day: ')) def GetDayOfYear(month,day): if month == 'January': print(day) if month == 'February': print(day + 31) if month == 'March': print(day +(31 + 28)) if month == 'April': print(day + ((31*2) + 28)) ...
b9c3c868e064818e27304573dec01cc97a4c3ab1
candacewilliams/Intro-to-Computer-Science
/moon_earths_moon.py
299
4.15625
4
first_name = input('What is your first name?') last_name = input('What is your last name?') weight = float(input('What is your weight?')) moon_weight = str(weight* .17) print('My name is ' + last_name + '. ' + first_name + last_name + '. And I weigh ' + moon_weight + ' pounds on the moon.')
3b3e87f7f11e3287516bf4fec945004c1e608a91
candacewilliams/Intro-to-Computer-Science
/math.py
537
4.21875
4
val_1 = input('First Number: ') val_1 = float(val_1) val_2 = input('Second Number: ') val_2 = float(val_2) sum_val = val_1 + val_2 print('The sum of ' , val_1 , ' and ' , val_2 , ' is ' , sum_val) minus_val = val_1 - val_2 print('The difference of ' , val_1 , ' and ' , val_2 , ' is ' , minus_val) ...
771251b8c34e7c68fdf60c33769fbb597c8edb72
candacewilliams/Intro-to-Computer-Science
/palindrome.py
336
3.921875
4
val_list = [10,-1,-1,10] def IsPalindrome (val_list): for i in range(len(val_list)): original = val_list[i] for j in range(len(val_list)-1,-1,-1): reverse = val_list[j] if original == reverse: print('True') else: print('False') IsPalind...
9f6ac411edd44fc57c15a76344ca12255ae5cbf0
YarrDOpanas/uData
/Numerical methods/Laba2/input_output.py
1,175
4.09375
4
def print_matrix(A, text): '''As argument takes matrix and text you want to ouput with matrix''' print(text) for i in range(len(A)): for j in range(len(A[i])): print('{:>8}'.format(round(A[i][j],5)), end = ' ') print() def Input_matrix_from_keyboard(): '''Input matix by...
a1efb556de71ac450484fb1a8f1c56f3c01eef88
YarrDOpanas/uData
/Numerical methods/Laba2/aditional_functions.py
1,927
3.671875
4
def checking_SLAR(A, a): '''Takes two matrix as argument. Checks if they are correct (Second length should be equivalent to amount of stakes in each raw). Terminates program if they are incorrect.''' m = len(A[0]) for i in range(1, len(A)): if len(A[i]) != m: print("Invalid matr...
5abc6375060e14470a0d68f0c86689541fe0b17c
Jailsonmc/projects-python
/Geral/equacao2grau.py
362
3.734375
4
import math print("Digite o índice 2:") indice2 = int(input()) print("Digite o índice 1:") indice1 = int(input()) print("Digite a constante:") constante = int(input()) delta = (indice1*indice1 - 4*indice2*constante) raiz1 = ( - indice1 - math.sqrt(delta) ) / (2 * indice2) raiz2 = ( - indice1 + math.sqrt(delta) ) / ...
4b62f2f35aa1a6b85155351a1793559a1113ee69
Jailsonmc/projects-python
/Geral/ConverterB10Bn.py
372
4.125
4
print("Digite o número a ser convertido para base 10:") valor = int(input()) print("Digite a base:") baseN = int(input()) continuar = True aux = valor while continuar: quociente = int(aux / baseN) resto = int(aux % baseN) print(str(resto),end="") aux = quociente if quociente < baseN: conti...
dba9eac804e3cc991ee8c2baeb17f180d2876414
jdvpl/Python
/7 funciones/7variablelocalesgloabales.py
732
4.25
4
""" variables locales:se defines dentro de la funcion y no se puede usar fuera de ella solo estan disponibles dentro a no ser que hagamos un retunr variables globales: son las que se declaran fuera de una funcion y estan disponibles dentro y fuera de ellas """ frase="jiren es un marica y no pudo vencer a kakaroto" #v...
191fe4741e7cd1e1fd5330a611048be5399ce783
jdvpl/Python
/Universidad Nacional/monitorias/Ejercicios/8-condicionales/elif.py
410
3.859375
4
def descuento(cantidad, precio): if 5 < cantidad <= 10: precio = precio * 0.95 elif 10 < cantidad <= 20: precio = precio * 0.90 elif 20 < cantidad: precio = precio * 0.80 return precio*cantidad def main(): cantidad = int(input("Digite la cantidad: ")) precio = float(inpu...
653aa12d67bcd895bba375cd642646bfdb26a9ef
jdvpl/Python
/7 funciones/6funcionesdentrodeotras.py
551
3.609375
4
# def getNombre(nombre): # texto=f"el nombre es: {nombre}" # rmbda # eturn texto # def getApellidos(apellidos): # texto=f"Los apellidos son: {apellidos}" # return texto # print(getNombre("jiren"),getApellidos("suarez")) # def devuelveTodo(nombre, apellidos): # texto=f"{getNombre(nombre)} \n{getApe...
208851acb00f7fbef32a7502b47257bc8732eb8b
jdvpl/Python
/Universidad Nacional/retos/2retos2.py
2,781
3.71875
4
""" El Centro Comercial Unaleño continúa trabajando en la creación de un carrito de compras. Para esto se requiere la creación de varias tareas que deben programarse en funciones detalladas a continuación: Lectura de n artículos Se requiere leer una cantidad n de artículos que representan la compra de un cliente....
65f58cf7607f996ab2c9bbc58775fa84bcfaf9f7
jdvpl/Python
/Universidad Nacional/mongo/mongo.py
2,325
3.90625
4
# ! importando la libreria para mongodb # !https://www.youtube.com/watch?v=pJO5gKxzsco importante ver este tutoriol from pymongo import MongoClient cliente=MongoClient('localhost') # *muetra las bases de datos que hay creadas db=cliente['prueba'] col=db['personas'] # insertar un documento en mongo def diccionarios(no...
b41c3e5cbd166aa4664a97a286b1cb593faf629e
jdvpl/Python
/16-constructo-POO/coche.py
1,610
3.828125
4
class Coche: # atributos o propiedades de la clase # caracteristicas del coche color="Negro" marca="Ferrari" modelo="Aventador" velocidad=300 caballaje=500 plazas=2 # porppieda publica rapido="si, es publico" #este se muestra fuera de la clase __soy_privado="estibuto privado"...
174f329130d0e376507d07bee25b7e3611910268
jdvpl/Python
/18 sqlite/sqlite.py
881
3.9375
4
# importar modulo de sqlite import sqlite3 # conexion ruta='./18 sqlite/' conexion=sqlite3.connect(ruta+'Pruebas.db') # crear cursor cursor=conexion.cursor() # crear tabla cursor.execute("CREATE TABLE IF NOT EXISTS productos("+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"+ "titulo varchar(255), "+ "descripcion text, "+ "pr...
06f79676ec85258798bd5fd5c7520ca9c040080d
jdvpl/Python
/9 sets-diccionarios/2diccionarios.py
1,236
4.1875
4
""" es un tipo de dato que almacena un conjunto de datos formato clave > valor es lo mismo que un array con en json """ # persona={ # "nombre":"Juan", # "apellidos":"Suarez", # "web":"jdvpl.com" # } # print(type(persona)) #tipo de dato # print(persona) #imprime todo # print(f" la Web: {persona['web']}") #s...
a4ab3ed227f3c71e199980035a255a2381d9582b
jdvpl/Python
/Universidad Nacional/practicas/8covid19incrementologaritmos.py
1,476
3.78125
4
""" A partir del día 1, el país A tiene una población contagiada de Divoc 9012 de n (1 <=n <= 10^8) y el país B tiene una población contagiada de Divoc 9012 de m (1 <= m <= n). Las tasas de crecimiento diario son de 2% y 3% respectivamente. Desarrollar un algoritmo para informar en que día la población contagiada del ...
33dfb3e016da6665ab1e7ef47a89344f5a1c70ad
jdvpl/Python
/4 condicionales/elif.py
1,669
4.125
4
# print(f"########################## elif ####################") # dia=int(input("Introduce el dia de la semana ")) # if dia==1: # print(f"es lunes") # elif dia==2: # print(f"es martes") # elif dia==3: # print(f"es miercoles") # elif dia==4: # print(f"es jueves") # elif dia==5: # print(f"es viernes"...
2fef799b2595b4afa2097501c4c71d88648d7ea9
jdvpl/Python
/Universidad Nacional/monitorias/Ejercicios/11-repaso y explicacion reto2/ejemplo-reto.py
873
3.859375
4
from math import ceil def main(): total_notas = int(input("Ingrese el número de notas: ")) #subtotal = 0 encabezado() nota_promediada = promedio(total_notas) nota_redondeada = redondea_nota(nota_promediada) final(nota_promediada, nota_redondeada) print("Gracias por estudiar en la UNAL") def encabezado():...
2aa3997d5c14c9fab3be7764d8ea063a3f74101e
jdvpl/Python
/Universidad Nacional/monitorias/Ejercicios/9-10-ciclos-rangos/ascii.py
409
4
4
def main(): entero = int(input("Ingrese un numero entero:")) bandera = True #opcion 1 while(bandera and (entero<65 or entero>90)): entero = int(input("Ingrese un numero entero:")) bandera = False # opcion 2 #while not (65<=entero and 90 >=entero ): # entero = int(input("I...
325caa05cbb89d266e1172071d9f97692255fdc4
charlysoledad/PythonBasics
/InputUser.py
183
3.9375
4
name = input("Enter your name: ") print("Hi", name) print("Let's calculate a square area") x = input("Enter a side value: ") z = int(x) * int(x) print("Okay, the square area is:", z)
41b51d7b8cacced28ad5c890aaed5cf5345670e2
EngincanVaran/CS301-Algorithms
/HW3/HW3 (1).py
2,594
3.546875
4
import random from functions import * from timeit import default_timer as timer from graphit import * sys.setrecursionlimit(sys.maxsize) def createRoad(n): temp = [ [ 0 for i in range(3) ] for j in range(n) ] for i in range (n-1): chance = random.randint(0,5) if(chance > 0): ...
ed89b53b3082f608adb2f612cf856d87d1f51c78
SandySingh/Code-for-fun
/name_without_vowels.py
359
4.5
4
print "Enter a name" name = raw_input() #Defining all vowels in a list vowels = ['a', 'e', 'i', 'o', 'u'] name_without_vowels = '' #Removing the vowels or rather forming a name with only consonants for i in name: if i in vowels: continue name_without_vowels += i print "The name without v...
f5f50e3e130be0068ba526eecb6173e5109a552b
LIch1994/CodigosMT
/Otros/Interface/Interfaz.py
4,275
3.65625
4
from Tkinter import * #Tkinter con mayuscula debido a la version de python 2.7 import time import tkMessageBox def saludar(): print 'Hola' def parpadear(): w.iconify() time.sleep(3) w.deiconify() def imprime(): print("Acabas de presionar imprimir") def saludar(): print("Hola" + nombre.ge...
34b0c91e798f058853c4e14867da038b86b3c25f
symbiont-val-melamed/classutilities
/src/classutilities/classproperty.py
2,674
3.640625
4
# Allows to have property on class level (and instance level) from typing import Any, Callable class ClassPropertyContainer(object): """Allows to create class level property (functionality for decorator)""" def __init__(self, prop_get: Any, prop_set: Any = None): """ Create a container that a...
ae4491afc10de074a4ea3cc0607fa241ee47d874
pshenoy-uc/mangaluru_py_meetup
/2016-02-12/word_count_prashanth_shenoy.py
713
3.625
4
import os, sys def start (): input_file_obj = open ('input_file.txt', 'r') word_list = input_file_obj.read ().split() print "There are a total of %d words" % len(word_list) word_repetition_dict = {} for word in word_list: try: word_repetition_dict [word] = word_repetition_dict ...