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
2d410e32b205bd5dcbd4bcf904f480c4107f9092
Karsenh/DataScience
/FunLessons/PythonBasicsFun/main.py
6,317
4.1875
4
import hello_world import math import random # to use deep copy import copy #data types # int, float, double, str, list, tuple, dict, set, etc. x = 10 # print(x, type(x)) x = "hello" # print(x, type(x)) # operators # /floating point div # / / int divison # ** exponentiation # can also use math.pow() and other functio...
64dd34e4fdc74a4349fcf55cc7b43a049f316b09
blubbers122/Python-LeetCode-Problems
/Easy/Fizz_Buzz.py
397
3.65625
4
class Solution: def fizzBuzz(self, n): results = [] for i in range(1, n + 1): result = "" if i % 3 == 0: result += "Fizz" if i % 5 == 0: result += "Buzz" if not result: result = str(i) results...
74dc5b68cd5609579d2336dd3a65c426a6defa5d
blubbers122/Python-LeetCode-Problems
/Easy/Range_Sum_of_BST.py
1,830
3.953125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class node: def __init__(self, value=None): self.value=value self.left=None self.right=None class ...
8b0feb4bed77663ac2fec82b20ed8117fd34b258
NelsonBilber/dp.tensorflow.regression
/tensorflow_simple_regression.py
4,295
3.609375
4
# code from https://medium.com/@saxenarohan97/intro-to-tensorflow-solving-a-simple-regression-problem-e87b42fd4845 import tensorflow as tf from sklearn.datasets import load_boston from sklearn.preprocessing import scale from matplotlib import pyplot as plt # Returns predictions and error def calc(x, y, b, w): pr...
5b6e62f02818cb4d39944fb08e5afb371cf306f3
joanalza/GECCO_2021
/Code/src/Individual/Permutation.py
1,963
3.890625
4
''' Created on 24 Jan 2020 @author: ja9508 ''' import random def create_new_permutation(permu_size): """Generates a u.a.r. permutation @param permu_size : size of the permutation wanted to generate. """ # Fill the vector with the values 1, 2, 3, ..., n aux_list = list(range(permu_s...
464d00436d9c90def53af9f7b1717e16f1031b23
JerryCodes-dev/hacktoberfest
/1st Assignment.py
884
4.15625
4
# NAME : YUSUF JERRY MUSAGA # MATRIC NUMBER : BHU/19/04/05/0056 # program to find the sum of numbers between 1-100 in step 2 for a in range(1,100,2): print(a) num = 1 while num < 100: print(num) num += 2 # program to find all even numbers between 1-100 for b in range(2,100,2): print (b) numb = 2...
2b2322a81700317944435f1d33c77cd654cf6249
abhishekvtiwari/DSA-Problems
/LinkedList Problem 1/Rotate a Linked List.py
829
4
4
class Node: def __init__(self,data): self.data=data self.next=None class LinkedList: def __init__(self): self.head=None self.c=0 def add_element(self,data): self.c=0 new_node=Node(data) if self.head is None: self.head=new_node return current=self.head while c...
aaf9bede1159e2e3d0781b5bfc0a8f101a3b8070
rlamacraft/ProjectEuler
/Python/Euler22.py
1,222
3.609375
4
names = [] Snames = [] total = 0 #import names from file input = "" with open("names.txt") as file: for line in file: input = line file.close() #find total number of names numOfNames = 0 for i in range(len(input)): if(input[i]==','): numOfNames = numOfNames + 1 numOfNames = numOfNames + 1 ...
d58a7bd5f64f42df37a6ec628141a5fb82ba58e9
jakubowiczish/host-parasite-simulation
/examples/example_grid.py
731
3.59375
4
import pygame size = 800 rows = 20 def grid(window, size, rows): distance_between_rows = size // rows x = 0 y = 0 for i in range(rows): x += distance_between_rows y += distance_between_rows pygame.draw.line(window, (0, 0, 0), (x, 0), (x, size)) pygame.draw.line(window,...
ecbb9649bf5580a55aac7f2f1c6c3fd3e466cdee
weissab/barcode-processing
/barcodes_RevComp.py
1,115
3.984375
4
#!/c/Users/Andrea/Anaconda3/python import sys import csv from libs.utils import read_barcodes, reverse_complement """ By: Andrea Weiss Last edited: 15 April 2020 Calculate the reverse complement of a list of sequences INPUTS: barcode_file: file of all sequnces to take reverse complement of """ # parrse input ar...
b5aec16dab5708526e25a2583aaa0e5205b6f0cf
ZaWael/python_module
/Exercice2.py
1,786
3.953125
4
# -*-coding:Utf-8 -* def intCheck(): # Demande une saisie d'entier et la renvoie try: nombre = int(input("Saisissez un entier positif : ")) except ValueError: print("Votre suggestion n'était pas un entier") # Si la saisie n'est pas un entier, on met fin à l'appel print("Le programme se ...
c6b05f9ab3533ae4bc9b9d8d9199a40ef25a8e60
Luispapiernik/Fractales
/fractals/cartesian.py
9,046
3.5
4
from numbers import Real from typing import Any import numpy as np from PIL import Image from fractals.schemas import Color, Component, Coordinate from fractals.utils import get_channels_number class Cartesian: """ This class handles the conversion of coordinates between a region on the cartesian plane ...
f98d8e0f6034cd085e4febe5f390fec1a2c9e3c8
zoeimogen/AoC2017
/day4.py
1,692
3.546875
4
#!/usr/bin/python # pylint: disable=invalid-name '''Advent of Code 2017 Day 9 solution''' import unittest import re def validphrase(phrase): '''Check for valid phrases using the part 1 definition''' words = re.split(' +', phrase) return len(set(words)) == len(words) def validphrasepart2(phrase): '''C...
c7bc7e2f54e9e7aa56d2bd1bc89667a2f98ecc9f
chiraag786/ml
/c2.py
74
3.734375
4
x=int(input("how many loops should run")) i=0 while i<=x: print(i) i+=1
270fff32bf3c0334e13e98761e74dff6f53250e2
esumanra/Random-Solves
/poisonous_plants.py
392
3.578125
4
def poisonousPlants(p): days = 0 flag = True while flag: tlis = [] prev = 10**11 for cur in p: if cur < prev: tlis.append(cur) prev = cur p = list(tlis) if(tlis == sorted(tlis, reverse=True)): flag = False da...
b4554a7c2ece968593885d5654ae55d8befc7810
kimmanbo/cheat-sheet
/python3/singleton/thread-safe-singleton.py
542
3.53125
4
from threading import RLock class Singleton(type): _instance = None _lock = RLock() def __call__(cls, *args, **kwargs): with cls._lock: if not cls._instance: cls._instance = super().__call__(*args, **kwargs) return cls._instance class SingletonClass(metaclass=S...
3a704754c1c693c9e2f236460734d044cdaa1d09
CoffeePlatypus/Python
/Class/class07/file_io.py
432
3.828125
4
# # Code example demonstrating a couple of simple file methods # # author: David Mathias # from os import listdir # open a file and read contents into a list of strings fn = open('random_ex.py', 'r') lines = fn.readlines() fn.close() for line in lines: print line print # create a list of the files in a director...
5cc890b202f98bb88b5d614c43745cf2b427b0e4
CoffeePlatypus/Python
/Class/class09/exercise1.py
893
4.6875
5
# # Code example demonstrating list comprehensions # # author: David Mathias # from os import listdir from random import randint from math import sqrt print # create a list of temps in deg F from list of temps in deg C # first we create a list of temps in deg C print('Create a list of deg F from a list of deg C tem...
7185ccd8e4a6913a24efb58ee17692112564b4d7
CoffeePlatypus/Python
/Class/class03/variables.py
804
4.125
4
# # Various examples related to the use of variables. # # author: David Mathias # x = 20 print type(x) print y = 20.0 print type(y) print s = "a" print type(s) print c = 'a' print type(c) print b = True print type(b) print print('8/11 = {}'.format(8/11)) print print('8.0/11 = {}'.format(8.0/11)) print print('...
5955eab90d13ea330b025c11f38dc8c4ccd14348
CoffeePlatypus/Python
/Assignment/program3/program3/otis.py
1,048
3.890625
4
# # CS 224 Spring 2019 # Programming Assignment 3 # # Your wonderful, pithy, erudite description of the assignment. -> Just read the read me # # Author: Julia # Date: March 13, 2019 # from building import Building import sys # sys.argv - list of args # # b = Building(10,5, True) # b.run(2,True) def main() : # ...
c0aff8d34e9f67e4e7a3f309bb1c48051f065d25
CoffeePlatypus/Python
/Competitive/Week3/hangover.py
305
3.78125
4
def main() : n = float(raw_input("")) while(n != 0) : i = 0.0 cards = 1 while i + (1.0/(cards+1)) < n : i += 1.0/(cards+1) cards += 1 print("{} card(s)".format(cards)) n = float(raw_input("")) if __name__ == "__main__" : main()
72c0a0afa9efb5de0930977634a263dad1981f0a
makeri89/Ohjelmistotekniikka
/minigolf-game/src/entities/field.py
4,537
3.859375
4
import pygame from entities.element import Element from entities.ball import Ball class Field: """A class for creating the field. Attributes: height: The height of the field. width: The width of the field. holes: Pygame sprite group for the hole(s). walls: Pygame sprite group...
b2352b5f49bffb781dac1cf51e1fa573ce5a841f
ohhdanielson/Assessment_2
/Assessment2.py
4,548
3.5
4
# -*- coding: utf-8 -*- """ Created on Mon Dec 18 21:03:20 2017 @author: Danielson """ #import functions import csv import matplotlib import random import operator import matplotlib.pyplot import matplotlib.animation import math #number of drunks to create num_of_drunks = 25 infinity_moves = math.i...
2b9a8e67139a7fe881f2840fcbbbd0adbfb26a60
Shubham-iiitk/Codes
/Adj_list_without_class.py
311
3.859375
4
# Adjlist without using class from collections import defaultdict m = defaultdict(list) def adjlist(v1,v2): if v1!=v2: if v1 not in m: m[v1]=[v2] else: m[v1].append(v2) adjlist(1,2) adjlist(1,3) adjlist(2,1) adjlist(1,3) adjlist(2,3) print(m,'hfuas')
5316d0029f6b47f3016f1dcfb3376bddbc5d7a4e
Shubham-iiitk/Codes
/bfs.py
578
3.859375
4
import collections def bfs(graph,root ): visited , queue = set(), collections.deque([root]) visited.add(root) print(root,end="") while queue: v = queue.popleft() for n in graph[v]: if n not in visited: visited.add(n) queue.append(n)...
2e7c9a35b3a787dcb078d3f4f174f241cfcb0730
guneetbrar/Python3
/t03.py
1,206
3.890625
4
""" ------------------------------------------------------- [program description] ------------------------------------------------------- Author: Guneet Singh ID: 211605090 Email: sing0509@mylaurier.ca __updated__ = "2021-02-06" ------------------------------------------------------- """ # Imports # Constants ...
ccfa3b1513dee20a9cb7ed30d0262c35ffb0b875
khangnngo12/astr-110-section-3
/if_else_control.py
659
3.984375
4
#define a function def flow_control(k): #define a string based on the value of k if (k==0): s = "Variable k = %d equal to 0" % k elif (k==1): s = "variable k = %d equal to 1" % k else: s = "Variable k = %d does not equal to 0 or 1" % k print(s) #print the string #define a main function def main(): #decl...
1c0c89ae17b6a45822a0082b8274d83ca55b697a
shaquilledavid/Advent_Of_Code
/Day 3/Day3.py
3,995
4.0625
4
""" Advent of Code Day 3 https://adventofcode.com/2020/day/3 Suppose you have the following list: You start on the open square (.) in the top-left corner and need to reach the bottom (below the bottom-most row on your map). The toboggan can only follow a few specific slopes (you opted for a cheaper model that prefer...
e1289588dbeda86fe78870f3f025f823777a40a6
jdtorres1997/Proyecto1Complejidad
/SAT-IP/Reductor/reductor.py
2,166
3.5
4
import sys def leer(ruta): try: archivoR = open(ruta, "r") lineas = archivoR.readlines() result = {'variables': 0, 'constraints': 0, 'lines':[]} for linea in lineas: if linea[0] != 'c' and linea[0] != 'p' and linea[0] != '%' and linea[0] != '0' and linea[0] != '\n': resu...
e11284c66d1744771fc1bae465fcfe26252d68a8
LeeJongbokz/python_fundamental
/콜라츠 추측.py
763
3.625
4
def solution(num): answer = 0 // cnt = 0 에서 시작한다 cnt = 0 while 1: // num이 1이 되거나, cnt가 501이면 // while문을 탈출한다 if num == 1 or cnt == 501: break // num이 짝수이면 2로 나눠준다 if num % 2 == 0: num /= 2 // num이 홀수이면 3을 곱하고 1...
0d91eca13f3722ae3e09db66d998288677ae6bf4
leticiaAMADOR/extra
/datos.py
820
3.515625
4
import json class data: data = [] def read(self): with open('clientes.json','r') as file: data = json.load(file) self.data = data['results'] def getClientes(self): clientes = [] for row in self.data: data = row['nom'] ...
758bf3714ecd4b96f1030454276996c0bbbed725
LizaMatyukhina/screen_saver
/screen_saver.py
7,115
3.828125
4
import pygame from random import random, randint from math import sqrt SCREEN_SIZE = (1280, 720) class Vector: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): # сумма векторов if other.is_vector(other): return Vector(self.x + oth...
7aee07cab407068c48edde58567cf24be09fdc3c
banma1234/KSU_study
/1st_week/I_average.py
247
3.5625
4
case = int(input()) for i in range(case): arr = list(map(int, input().split())) avg = sum(arr[1:])/arr[0] count = 0 for j in arr[1:]: if j > avg: count+=1 print("%.3f%%"%((count/arr[0])*100))
e0cefa099a6086107cafe36ee56e1cfd06590554
banma1234/KSU_study
/1st_week/F_4bunmyun.py
220
3.828125
4
x, y=int(input()), int(input()) if x!=0 and y!=0: if x>0 and y>0: print("1") elif x>0 and y<0: print("4") elif x<0 and y>0: print("2") else: print("3")
d4b2e48dfb4b57078759bbeffd3d030693db87ef
Ankit01Mishra/Neural-Network-From-Scratch
/nn_from_scracth1.py
2,450
3.53125
4
import numpy as np #Seed the random function to ensure that we always get the same result np.random.seed(1) #Variable definition #set up w0 W1 = 2*np.random.random((60,30)) - 1 W2 = 2*np.random.random((30,60)) - 1 W3 = 2*np.random.random((1,30))-1 #define X from sklearn.datasets import load_breast_cancer can = load_br...
00cde42b0a1db408992096d8d6a49e612654b2de
yhyuk/Algorithm
/CodeUp/6082.py
186
3.78125
4
# 6082번 3 6 9 게임의 왕이 되자 n = int(input()) for i in range(1,n+1): if i%10 == 3 or i%10 == 6 or i%10 == 9: print("X", end=" ") else: print(i, end=" ")
30d67e9911145e39e2684adc0aa5aad47988a3ae
yhyuk/Algorithm
/Baekjoon/10886번 0=not cute_1=cute.py
633
3.515625
4
# 1 # 정수 0, 1 의 갯수를 비교해 주어진 문장 출력 # 1이 입력 될 때마다 c값 증가로 0과 1의 갯수 비교 n = int(input()) c = 0 for i in range(n): if int(input()) == 1: c+=1 if c > n//2: print("Junhee is cute!") else: print("Junhee is not cute!") # 2 # 입력값을 리스트[]에 넣고 count 함수를 통해 0,1 의 갯수값 구함 # if문 비교로 주어진 문장 출력 n = int(input()...
884f3d8864db1f221e5ff8b3f06fc87a20fc6882
shabazaktar/Excellence-Test
/Question2.py
304
4.21875
4
# 2 Question def maxValue(d2): key = max(d2, key=d2.get) d3={key : d2[key]} return d3 d1= { "1" : "Shahbaz", "2" : "Kamran", "3" : "Tayyab" } d2= { "1" : 50, "2" : 60, "3" :70 } print(maxValue(d2))
d003923e5821952d124356b803e415590c2780af
Stanwar/Code_Academy
/Python/median.py
322
3.984375
4
def median(integers): integers = sorted(integers) length = len(integers) avg = 0 if length%2==0 : avg = float((integers[(length/2)-1] + integers[length/2])/2.0) print avg return avg else: print integers[length/2] return integers[length/2] ...
d02a0639223314fc1ba3879298d9b19b351b0259
lephdao/ZeroOne
/zero_one.py
171
3.609375
4
#!/usr/bin/env python with open("zero_one") as f: for line in f: aline = line.split(" ") for ch in aline: if ch == "ZERO": print "1", else: print "0",
f7d298e2220ac903ab25ddcf9e4cd7dae764a757
Jordanzuo/Algorithm
/reverse_k.py
1,859
3.734375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # This method is intuitive, and it's easy to implement class Solution1: def reverseKGroup(self, head, k): if not head or k == 1: return head groupList = ...
72d08207180248a1bf6e1c26cadbce3752a98a37
Jordanzuo/Algorithm
/sort_merge.py
1,217
4.03125
4
#!/usr/bin/python3 import sys def binarySort(itemList): if len(itemList) == 1: return itemList mid = len(itemList) // 2 left = binarySort(itemList[:mid]) right = binarySort(itemList[mid:]) retItemList = [] leftIndex, leftIndexMax, rightIndex, rightIndexMax = 0, len(left), 0, len(right) whi...
332b5c350f441b862a9535726a1bd790a234441e
j-kasama/AutoEmail
/send_mail.py
2,148
3.8125
4
from smtplib import SMTP_SSL, SMTPException import random def make_data_dict(file): f = open(file, "r") data = f.read().split('\n') f.close() data_list = [] for d in data: data_list.append(d.split(',')) number = len(data_list) student_address = [] for i in range(number): ...
37c4f46720268d8472c7310c2a17cc179b070bb1
PongDev/2110101-COMP-PROG
/Grader/08_Dict_23/08_Dict_23.py
335
3.59375
4
n=int(input()) translator={} for i in range(n): data=input().split() translator[data[2]]=data[0]+" "+data[1] translator[data[0]+" "+data[1]]=data[2] m=int(input()) for i in range(m): query=input() if query in translator: print(query,"-->",translator[query]) else: print(query,"...
baa7fde23dd9e03a3a155945ea97ed03688d7be2
PongDev/2110101-COMP-PROG
/Grader/09_MoreDC_26/09_MoreDC_26.py
582
3.75
4
n=int(input()) memberList=[] cityDict={} memberDict={} for i in range(n): data=input().split(": ") data[1]=data[1].split(", ") memberDict[data[0]]=data[1] memberList.append(data[0]) for city in data[1]: if city not in cityDict: cityDict[city]=set() cityDict[city].add(dat...
b377779015e952c0b782b9901799345141a37703
PongDev/2110101-COMP-PROG
/Grader/04_Loop_01/04_Loop_01.py
200
3.828125
4
sum=0 count=0 while True: data=input() if (data=="q"): break else: count+=1 sum+=float(data) if (count==0): print("No Data") else: print(round(sum/count,2))
26b51bf853fb8559b5ad56231c32079801a9d270
PongDev/2110101-COMP-PROG
/Grader/12_Class_32/12_Class_32.py
696
3.671875
4
class Point: def __init__(self,x,y): self.x=x self.y=y def __str__(self): return "("+str(self.x)+","+str(self.y)+")" class Rect: def __init__(self,p1,p2): self.lowerleft=p1 self.upperright=p2 def __str__(self): return str(self.lowerleft)+"-"+str(self.uppe...
6905652b0818020d474aca1c8ba5f4659c317ada
PongDev/2110101-COMP-PROG
/Grader/04_Loop_04/04_Loop_04.py
213
3.6875
4
data=input() ans="" for i in data: if (i=="("): ans+="[" elif (i==")"): ans+="]" elif (i=="["): ans+="(" elif (i=="]"): ans+=")" else: ans+=i print(ans)
fe36e3d915fb983f419a740786aafd17e84c314c
PongDev/2110101-COMP-PROG
/Grader/09_MoreDC_27/09_MoreDC_27.py
754
3.578125
4
def knows(R,x,y): return y in R[x] def is_celeb(R,x): for member in R: if member!=x and (not knows(R,member,x)): return False if len(R[x])==0 or (len(R[x])==1 and x in R[x]): return True else: return False def find_celeb(R): for x in R: if is_celeb(R,x):...
08a2acee239c1b6207a9d9324083ca084ad079f9
PongDev/2110101-COMP-PROG
/Grader/P3_03_Text/template.py
414
3.625
4
#-------------------------------------. # Q4: Text Formatting #---------------------------------------- fname = input().strip() k = int(input()) ruler = '' for i in range(k//10) : ruler += '-'*9 + str(i+1) # เพิ่มรอบละ 9 ขีด ตามด้วยตัวเลข if ??? : ruler += '-'*( ??? ) # เพิ่มที่เหลือ (ถ้ามี) print(...
c31d96b799280e07778c2928dffa030a8eb3726a
PongDev/2110101-COMP-PROG
/Grader/03_If_02/03_If_02.py
171
3.734375
4
score=float(input()) if (score>=80): print("A") elif (score>=70): print("B") elif (score>=60): print("C") elif (score>=50): print("D") else: print("F")
f37c571f10bfe21530d9cbbe844d1028efdc3b15
PongDev/2110101-COMP-PROG
/Grader/09_MoreDC_24/09_MoreDC_24.py
317
3.75
4
animalDict={} animalOrder=[] while True: data=input().split(", ") if data[0]=="q":break if data[1] not in animalDict: animalOrder.append(data[1]) animalDict[data[1]]=[] animalDict[data[1]].append(data[0]) for animal in animalOrder: print(animal+":",", ".join(animalDict[animal]))
7c41941184c4c6b57d44bb80239e705dc78a26ed
PongDev/2110101-COMP-PROG
/Grader/05_List_12/05_List_12.py
443
3.78125
4
realname = ["Robert", "William", "James", "John", "Margaret", "Edward", "Sarah", "Andrew", "Anthony", "Deborah"] nickname = ["Dick", "Bill", "Jim", "Jack", "Peggy", "Ed", "Sally", "Andy", "Tony", "Debbie"] n = int(input()) for i in range(n): data = input() if data in realname: print(nickname[realname.i...
8107096f5d0631da396c1f51a2ecf596619f6427
PongDev/2110101-COMP-PROG
/Grader/12_Class_23/12_Class_23.py
956
3.671875
4
class Card: def __init__(self,value,suit): self.value=value self.suit=suit def __str__(self): return "({} {})".format(self.value,self.suit) def next1(self): if self.suit=="spade": valueList=["3","4","5","6","7","8","9","10","J","Q","K","A","2"] return ...
204cef987b5a7a50a8c04c6469809921989268b4
PongDev/2110101-COMP-PROG
/Workshop/7/debuggingworkshop.171879.1603260405.5443/Student/coin.py
894
3.640625
4
# -*- coding: utf-8 -*- import math # find greatest common divisor # of given inputs a and b def gcd(a,b): if(b==0): return a else: return gcd(b, a%b) if __name__ == '__main__': # na : amount of coin_a # nb : amount of coin_b # find such a case that T = a*na + b*nb # print na, nb if possible, ...
feab0dd3473e616c9fa16f2126437daae2589bc6
itsmrajesh/python-programming-questions
/substringmatch.py
426
3.625
4
def is_match(str, n): print(str) lst = [] for i in range(n): ss = input() lst.append(ss) is_matched = False for i in range(n): for j in range(i + 1, n): if sorted(lst[i] + lst[j]) == sorted(str): print(lst[i],lst[j]) is_matched = Tr...
b5e08943f89d80cddb2eda97586a0572e283d754
itsmrajesh/python-programming-questions
/TCS/fib_prime_series.py
676
3.890625
4
import math as m """print these series 1 2 1 3 5 3 7 5 11 8""" def is_prime(n): if n <= 1: return False else: val = round(m.sqrt(n)) for i in range(2, val + 1): if n % i == 0: return False return True num = int(input()) a = 1 b = 0 p = 2 for i in ra...
388bb8cd9b9714e998e5dfe8c3bc1f847a74628a
itsmrajesh/python-programming-questions
/TCS/binary_to_decimal.py
265
4
4
import math as m def get_binary_to_decimal(num): decimal, i = 0, 0 while num > 0: rem = num % 10 decimal += rem * m.pow(2, i) i += 1 num //= 10 return round(decimal) num=int(input()) print(get_binary_to_decimal(num))
9777d0a0bcf303a6c689f0016e4f5c73b100d6fd
itsmrajesh/python-programming-questions
/EBox/primeFactor.py
165
3.765625
4
from prime import is_prime p=2 num = int(input()) print(help(is_prime(7))) for i in range(2,num+1): if is_prime(i): if num%i==0: print(i)
58ebee4b3ac9d71c260e5f02f35c043181f66931
itsmrajesh/python-programming-questions
/TCS/Armstrong.py
349
3.71875
4
def is_armstrong(n): s = str(n) lst = list(s) sum = 0 for i in lst: sum += pow(int(i), len(lst)) return sum == n num1 = int(input()) num2 = int(input()) if num1 > 0 and num2 >= num1: while num1 < num2: if is_armstrong(num1): print(num1) num1 += 1 else: ...
1f07d6711000556813797a0b309eb1d6a6b5b338
itsmrajesh/python-programming-questions
/TCS/reverseNumber.py
160
3.984375
4
def reverse(n): n = str(n) lst = list(n) lst.reverse() s = '' for ele in lst: s += ele return int(s) print(reverse(input()))
d3594f8ed3c508e702f423c36dfae1482ef83f06
itsmrajesh/python-programming-questions
/TCS/series2.py
593
3.8125
4
import math as m """1 2 3 3 5 5 7 7 7 7 11 11 13 13 13 13 17 17""" def is_prime(n): if n <= 1: return False else: val = round(m.sqrt(n)) for i in range(2, val + 1): if n % i == 0: return False return True a=1 p=2 def get_next_prime(p): p += 1 ...
3b61bba00ff40e4658678c27cf833a88768de5b6
nicesoul/hangman-python
/utils/game.py
5,057
4
4
#! python3 # -*- coding: utf-8 -*- """ This is a game module for hangman game. We define a logic of word guessing here. """ import random # generate random number or objects import re # Regural expression import os # Miscellaneous operating system interfaces os.system('') # Execute the command(a string) in a su...
6b51164b597e40f084589c3aa5375c9d5bd6d945
gnfandrade/Projetos_Python
/Litsa_TDD.py
2,407
4
4
# -*-coding: utf-8 -*- """ # Código que adiciona numéros no intervalo de 1 a 5 (inclusive) no vetor de nome lista. lista = [] for i in range(1, 6): lista.append(i) # Teste Unitário para a lógica de inserção de números na lista. assert 1 == lista[0] assert 2 == lista[1] assert 3 == lista[2] assert 4 == lista[3] a...
0d6c0f84244fd8ffc7d6365e9054dc5f3a535e41
gnfandrade/Projetos_Python
/Banco.py
1,132
3.9375
4
contas = [] depositos = [] saldo = 0 def main(): opcao = bool(int(input("Deseja criar conta(1) ou fechar o programa(0)? "))) while opcao: criaConta() verSaldo() opcao = bool(int(input("Deseja criar conta(1) ou fechar o programa(0)? "))) def criaConta(): global contas, depositos, sa...
ff7782feb7edcc3bf91715a193977e0e7478602f
gnfandrade/Projetos_Python
/TDD_FuncaoDobroNum.py
217
3.78125
4
# -*- coding: utf-8 -*- # # Função que retorna o dobro de um número qualquer # def dobro(num): return num * 2 # # Seus testes # assert 40 == dobro(20), "o dobro de 5 deve ser 10" print("O Teste Passou !!!")
d5e8fdf8e6df82ec7f6ed500703324bcb6e10400
gnfandrade/Projetos_Python
/P_Funcional.py
810
4.0625
4
matriz = [[1,2,3], [5,9,1], [7,8,9]] lstindice = [] lstcopia = matriz[1].copy() matriz[1].sort() # Pela iteração dos elementos da lista matriz na linha 1, usa-se tais elementos para obter-se os índices dos mesmos adicionando-os na variável valor. Posteriormente os índices são # adicionados na list...
4de4c3526d1151e6c6a9bbe6bb698630b2060774
vesche/breakout-curses
/breakout.py
4,850
3.703125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # breakout using curses # https://github.com/vesche # import curses import time import board # consts HEIGHT = 19 # 20x60 grid WIDTH = 59 BLOCK_SIZE = 6 # 1x6 block B_ROWS = 5 # 10 blocks in top 5 rows B_COLS = 10 PADDLE_SIZE = 11 BLK = 17 # color code for black DEBUG ...
0b72c01feab24b4844eedd8386a5d8eb72d7ad93
rp927/Portfolio
/Python Scripts/nested_lists.py
1,599
3.96875
4
''' Given the names and grades for each student in a Physics class of students N, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. ''' #Empty list to play with name_input = [] score_input = [] # Basic input to get all of the information needed for _ in range(int(inp...
3e8ea3989cf216ab53e9a493b07ea974dbe17091
rp927/Portfolio
/Python Scripts/string_finder.py
585
4.125
4
''' In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left. ''' def count_substring(string, sub_string): ls = [] o = 0 count = 0 l = le...
3d8e4e7d53933aa3bb7b9cdee802188431e92638
charlespittman/fuzzy-wight
/py/hackingciphers/reverseCipher.py
229
3.8125
4
# Reverse Cipher #message = 'Three can keep a secret, iff two of them are dead.' message = input('Enter message: ') translated = '' i = len(message) - 1 while i >= 0: translated += message[i] i -= 1 print(translated)
cf5fe661178efcee74f52ff522a2c70500609c3a
konradr33/active-firewall
/active_firewall/config.py
1,039
3.5
4
import configparser import sys class Config: """ A static class that retrieves defined values from a configuration file and distributes them throughout the application. """ __config_file_name = 'config.ini' __config = None @staticmethod def __init_config(): """ Opens a con...
c38eac0e2a71608670442f81713fb69834edb75f
Mabozaid0X1/Intro_to_programming_udacity_projects
/3.Adventure Game/adventure_game.py
4,148
4.0625
4
import time import random def print_pause(message_to_print): print(message_to_print) time.sleep(3) enemy = ["troll", "dragon", "gorgon", "fairie", "pirate"] wicked = random.choice(enemy) def intro(): print_pause( "You find yourself standing in an open field, " "filled w...
b098f87ebc06d10d19c84078bdc8975a3a020d1c
lherrada/LeetCode
/stacks/stack.py
575
3.734375
4
class Stack: def __init__(self): self.StackArray = [] def push(self,value): self.StackArray.append(value) def pop(self): return self.StackArray.pop() def peek(self): return self.StackArray[-1] def __repr__(self): return str(self.StackArray) def __len_...
0fa7471aa14fec407c4b491a338ffaf70f530183
lherrada/LeetCode
/stacks/problem1.py
741
4.28125
4
# Check for balanced parentheses in Python # Given an expression string, write a python program to find whether a given string has balanced parentheses or not. # # Examples: # # Input : {[]{()}} # Output : Balanced # # Input : [{}{}(] # Output : Unbalanced from stack import Stack H = {'{': '}', '[': ']', '(': ')'...
411d14584d8d08419d32e9649e85eb9ec0cad77b
lherrada/LeetCode
/linkedlist/DoubleLinkedList.py
2,150
4.09375
4
import time # Implementation of LinkedList data structure # with forward and backward links class Node: # Constructor def __init__(self, data): self.data = data self.next = None self.prev = None self.visit = False class LinkedList: def __init__(self, data): self....
4c4cbbf75cd598226f55a08b967597dde477e7a3
odemeniuk/twitch-challenges
/interview/test_palindrome.py
336
4.40625
4
# write a function that tells us if a string is a palindrome def is_palindrome(string): """ Compare original string with its reverse.""" # [::-1] reverses a string reverse = string[::-1] return string == reverse def test_is_palindrome(): assert is_palindrome('banana') is False assert is_pal...
e7e11e4f8556999c6a17550de8e42edc9cd8d68b
SuGranadaA/Dia_24_09abril
/main.py
3,237
3.546875
4
#@Librería NumPy #Importamos la librería para leer .xlsx import openpyxl #Importamos la librería de NumPy import numpy as nmp #Abrimos el archivo de excel wob1 = openpyxl.load_workbook('numpy1.xlsx') #Accedemos a las hojas de cálculo num1 = wob1['Hoja1'] #Accedemos a las celdas y las transformamos en valores A1 = ...
d8f9c69874ca0ab5da4dac704f88fedb77b1b30d
dragonRath/PythonBasics
/stringformatting.py
2,162
4.53125
5
#The following will illustrate the basic string formatting techniques used in python age = 24 #print("My age is " + str(age) + " years\n") print("My age is {0} years".format(age)) #{} Replacement brackets print("There are {0} days in {1}, {2}, {3}, {4}, {5}, {6} and {7}".format(31, "January", "March", "May", "July", ...
530fa7c4e6b94161edf79af01a046911743295f3
Bal2018/hackerrank
/Loops/Loops.py
236
3.78125
4
# hackerrank - Used Python 3 Final Code #!/bin/python3 if __name__ == '__main__': n = int(input()) #User enters max number of lines for i in range(0,n): print(i*i) #Print out the square number of that line number
b15d394b442a2b69d56cc73a16e13b82bf7a5dd7
Bal2018/hackerrank
/Setoperations/setoperations.py
804
3.734375
4
# hackerrank - Used Python 3 Final Code #!/bin/python3 if __name__ == '__main__': n = int(input()) #length of string s = set(map(int, input().split())) #actual string split by space NumberActions=int(input()) #number of actions to enter for _ in range (NumberActions): #loop until end a...
c603d6ab0955cfc0100daa3a9c4c37cceb58876c
loweryk/CTI110
/p3Lab2a_lowerykasey.py
1,026
4.46875
4
#Using Turtle in Python #CTI-110 P3LAB2a_LoweryKasey import turtle #Allows us to use turtles wn = turtle.Screen() #Creates a playground for turtles alex = turtle.Turtle() #Creatles a turtle, assign to alex #commands from here to the last line can be replaced alex.hideturtle() #Hides the turtle i...
d73230ddaf0aba19d82303af14ac9f1036626005
TheRenegadeCoder/sample-programs
/archive/p/python/binary_search.py
1,193
4
4
import sys def binary_search(array_list, key): start = 0 end = len(array_list) while start < end: mid = (start + end) // 2 if array_list[mid] > key: end = mid elif array_list[mid] < key: start = mid + 1 else: return mid return -1 de...
8ca5f3c620b6d0fe56a5b23b0a9bb324f54a3a1c
TheRenegadeCoder/sample-programs
/archive/p/python/fraction_math.py
1,007
3.703125
4
import operator import sys from fractions import Fraction d = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv, "==": lambda x, y: int(operator.eq(x, y)), "<": lambda x, y: int(operator.lt(x, y)), ">": lambda x, y: int(operator.gt(x, y)), "<=": lambda x, ...
f1fa0c6506cf3e3648d123116c9adb3cbf96c353
TheRenegadeCoder/sample-programs
/archive/p/python/file_input_output.py
548
3.671875
4
def write_file(): try: with open("output.txt", "w") as out: out.write("Hi! I'm a line of text in this file!\n") out.write("Me, too!\n") except OSError as e: print(f"Cannot open file: {e}") return def read_file(): try: with open("output.txt", "r") as ...
e3f200c12b618614e15df78f801b2409d5b1511d
TheRenegadeCoder/sample-programs
/archive/p/python/depth_first_search.py
1,859
3.734375
4
import sys def get_input(argv): error_message = 'Usage: please provide a tree in an adjacency matrix form ("0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0") together with a list of vertex values ("1, 3, 5, 2, 4") and the integer to find ("4")' # check input if len(argv) ...
5a0f3eec1ad99f4fd43870ec65c2a6e9c92368fe
en3ri/abe487
/problems/kmer_counter/kmer_counter.py
825
3.65625
4
#!/usr/bin/env python3 import sys import os from collections import Counter args = sys.argv[1:] if len(args) != 2: print('Usage: {} LEN STR'.format(os.path.basename(sys.argv[0]))) sys.exit(1) LEN = args[0] STR = args[1].upper() LEN_STR = int(len(STR)) if len(args) == 2: if not args[0].isdigit(): print(...
c3163016182207a74b1d2d57a4ce6530685d8482
ingridt123/python-minigenefinder
/geneFinder.py
3,452
3.65625
4
import BioDNA import time def main(): print ("\n ---+++ IngeneT v5.136 +++---") # opens text file containing explanations explain = open('explain.txt', 'r') explainDict = BioDNA.inputExplan(explain, 150) # print introduction BioDNA.printExplan(explainDict, 0) times = 0 while True: ...
a9da16a2892a98428170f2182fd31e385ec114d3
lindsaynchan/hb_fellowship_final_project
/giphy.py
489
3.546875
4
"""Giphy API calls and functions.""" import os import requests GIPHY_API_KEY = os.environ.get('GIPHY_API_KEY') def giphy_random_generator(): """Generate random television related gif.""" url = "http://api.giphy.com/v1/gifs/random?api_key=" + GIPHY_API_KEY + "&rating=g&tag=television" #submit API reques...
16147b3030b183a3a1d4f5b1d8af73bca557f1f6
RishiNandhan/Hackerrank-Python-Solutions
/Set mutation.py
408
3.5
4
n=int(input()) s1=set(map(int,input().split())) m=int(input()) for i in range(m): c,k=input().split() s2=set(map(int,input().split())) if c=="intersection_update": s1.intersection_update(s2) elif c=="update": s1.update(s2) elif c=="symmetric_difference_update": s1.symmetri...
3f28dc40e189f35abaac56371001f7e981c06b46
DmitrofNET/Dmitrof
/my reverse.py
260
4
4
while True: word = (input("Enter Here : ")) newword='' print('The length of this word was', len(word),'characters') letters = len(word) for x in range(letters): newword += word[letters-x-1] print(newword.title().strip())
081b4815619930a1711f6d4c235583e9efb7ecec
BackGraden/Data-Structures-and-Algorithm
/浙大数据结构/week5/测试2.py
5,596
3.78125
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 10 21:52:23 2018 @author: Administrator """ # -*- coding: utf-8 -*- """ Created on Wed Mar 28 23:07:14 2018 @author: Administrator """ #定义堆 class Heap(object): #初始化,a为哨兵 def __init__(self,x,a,M): #哨兵填入首元素 s=[a] s+=x self.data=s ...
e15032e3d5214af41c55f6ca52e60037ef7eca22
BackGraden/Data-Structures-and-Algorithm
/浙大数据结构/week2/Pop Sequence.py
1,617
3.5625
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 24 11:23:23 2018 @author: Administrator """ #定义栈 class Stack(): def __init__(self,size): self.size=size self.stack=[] self.top=-1 def isfull(self): return self.size==(self.top+1) def push(self,x): if self....
ddb63cd4d8a6cf3bc97912db40e047c80449033e
pythondev0101/-j-natividad-web-billing
/bds/functions.py
772
3.5
4
""" Functions """ def generate_number(prefix, lID): generated_number = "" if 1 <= lID < 9: generated_number = prefix +"0000000" + str(lID+1) elif 9 <= lID < 99: generated_number = prefix + "000000" + str(lID+1) elif 999 <= lID < 9999: generated_number = prefix + "0000...
3584514835098391dbe535f41cb9d529fab242c8
ipdae/homework
/LinkedList.py
2,695
3.578125
4
class Node: def __init__(self,data,prev=None,next=None): self.data = data self.prev = prev self.next = next class LinkedList: def __init__(self): self.head = None self.current = None self.tail = None def print_list(self): current = self.head while current: print current.data curre...
676b4eb2f036c5379c5367528429cd124facc5b0
CBGO2/Mision-04
/Triangulos.py
1,086
4.25
4
# Carlos Badillo García # Programa que lee el valor de cada uno de los lados de un triangulo e indica el tipo de triángulo que es def indicarTipoTriangulo(lado1, lado2, lado3): #Indicar que tipo de triángulo es dependiendo el valor de sus lados if lado1 == lado2 == lado3: return "El triángulo es equ...
42d82efd888300ad812947d5b3a92f1351c8b344
MikeMor-fr/shooter-game
/player.py
1,872
3.609375
4
import pygame from projectile import Projectile import animation # Create the player class class Player(animation.AnimateSprite): def __init__(self, game): super().__init__('player') self.health = 100 self.max_health = 100 self.attack = 30 self.velocity = 5 self.rec...
2ea9f7ee2ecaf30a0678c566a6492d3c2f75a290
DrOuissem/useful_programs
/code_python2/chapter1_oop/4_video_abstract_class/video4_AbstractClass.py
1,054
4.15625
4
from abc import ABC, abstractmethod class Person(ABC): def __init__(self,name,age): self.name = name self.age = age def print_name(self): print("name: ",self.name) def print_age(self): print("age: ",self.age) @abstractmethod def print_info(self): pass class St...
fc3a170f883e4a99fdc0ff0145a39533f9e56967
DrOuissem/useful_programs
/code_python2/chapter4_DB/2_video2_insert_replace/program4.py
431
3.671875
4
import sqlite3 conn = sqlite3.connect("example.db") c = conn.cursor() c.execute('''CREATE IF NOT EXISTS TABLE Students (Name TEXT, Id INTEGER PRIMARY KEY, AGE INTEGER, Grade REAL )''') c.execute(''' REPLACE INTO Students ('NAME', 'Id','AGE','Grade') VALUES ('MOHAMED',3233,20,91.5) ''') c.execute(''' REP...
d11719e27a4c6ab4b5cc24ad35931c95bf6ef290
DrOuissem/useful_programs
/code_python2/chapter2_GUI/3_video_Listbox/camtasia_listbox.py
477
3.5625
4
import tkinter window = tkinter.Tk() window.geometry("300x300+100+100") listbox = tkinter.Listbox(window) listbox.pack() listbox.insert(tkinter.END,"Orange") listbox.insert(tkinter.END,"Red") listbox.insert(tkinter.END,"Yellow") listbox.insert(tkinter.END,"Blue") listbox.insert(tkinter.END,"Green") def on_select(event...