blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
8c50d89d21208b725c0f86b36697d32791223160
John15321/Random
/HackerRank/Python/Basic Data Types/list-comprehensions.py
326
3.609375
4
''' https://www.hackerrank.com/challenges/list-comprehensions/problem ''' if __name__ == '__main__': # Input x = int(input()) y = int(input()) z = int(input()) n = int(input()) print([[xs, ys, zs] for xs in range(0, x+1) for ys in range(0, y+1) for zs in range(0, z+1) if(zs+xs+ys !=...
56a4f8ba6ee9c1c01ad3baf88510aa8fab1dde46
ikosolapov1983/Homework6
/la_song.py
596
3.828125
4
def la(s=3, count=3, z=0): """ Функция принимает три значения в формате int: s - количество строк count - количество слогов z - знак в конце, если 1 , то выводит "!", во всех остальных случаях "." return возвращает сформированную песню la """ word = 'La' p = (word + '-') * count ...
b3c4493c7570550f289abd21cf5d5ac92d16bc8e
matveyplevako/adventofcode
/adventofcode2019/day13/second.py
4,582
3.65625
4
from collections import defaultdict from time import sleep SHOW_GAME = False PLAY = False with open("input.txt") as inp: text = dict((ind, elem) for ind, elem in enumerate(inp.read().split(","))) opcodes = defaultdict(int, text) opcodes[0] = '2' def calculate_position(platform_and_ball): platform, b...
594b890e09cb8cf130f02eeb901679e2891289c1
singhpraveen2010/experimental
/poly_point_check.py
2,251
4.28125
4
""" To check if a point P lies within the N sided polygon: Step 1: Area of the polygon = sum of area of N-2 triangles formed by the polygon points. Step 2: Area Covered by P = sum of areas of N triangles formed by P and any two adjasecnt sides of the ploygon. If areas obtain from step 1 and 2 are equal then P lies with...
3d654cf6ee4fc428687bd96a4692063860489916
thamilanban-MM/Python-Programming
/Beginner Level/positive and negative.py
170
3.953125
4
a=raw_input("") if a.isdigit(): if (int(a)>0): print("Positive") elif (int(a)<0): print("Negative") else: print("Zero") else: print("enter the invalid number")
f1c2e70d612f11ef5d983d39e2782f4f488f7776
NishKoder/Python-Repo
/Chapter 3/dry.py
515
3.921875
4
# DRY - Dont Repeat YourSelf Principle import random winning_number = random.randint(1, 100) gusse = 1 game_over = False number = int(input("Enter gussing number: ")) while not game_over: # can use break also if number == winning_number: print(f"you win, have guss {gusse}") game_over = True ...
4a35eaea491e54ab4e65a6d5a1ce69bd6ad4dba2
cgreggescalante/ads-class-pub-patches
/src/exercises/recursion/recursion_functions.py
564
3.578125
4
#!/usr/bin/env python3 """ `recursion` implementation @author: """ def gcd(a: int, b: int) -> int: """Greatest Common Denominator""" raise NotImplementedError def diamond_ite(levels: int) -> None: """Print a diamond""" raise NotImplementedError def diamond_rec(levels: int) -> None: """Print a...
8b346f4336605d751e603e377ccac10adbfc051c
acheval/python
/lirmm-fr/exercice4.2.1.py
683
3.609375
4
#!/bin/python3 # Reprenez le script et faites que le seuil et la longueur lg soient # saisis (plutôt qu'écrits dans le script) # Déclarer une variable lg dans laquelle vous mémoriser la longueur # d'une ORF d'un ARN print("Enter the value for lg: ") lg = int(input()) # Déclarer une variable seuil dans laquelle vous...
0cf2d491058e88dd23ad9653a89e85e038826a86
ronin2448/coursera_courses
/discrete_opt_2014/discrete_opt_course/hw1/rulesSolver.py
4,606
3.796875
4
#!/usr/bin/python # -*- coding: utf-8 -*- from collections import namedtuple from operator import attrgetter Item = namedtuple("Item", ['index', 'value', 'weight']) def parse_data(input_data): # parse the input lines = input_data.split('\n') firstLine = lines[0].split() item_count = int...
cfa688cd74a69dcbd9fe083c67b7771de9b137c4
PrawahK/ye-le-bro
/beginnerapp.py
2,038
3.671875
4
# Imports required import json import pandas as pd final_data = {'label': '', 'id': '', 'link': '', 'children': []} def csv_to_json_convertor(): """This function is to upload the CSV file into the Program""" try: df = pd.read_csv('data.csv') #Reading Csv. except FileNotFoundErr...
e6b8b40eda822c168957b06a1e5ba8d423e7a635
Shivvrat/Text-Classification-using-NB-and-LR
/multi_nomial_naive_bayes.py
4,865
3.515625
4
from decimal import Decimal from math import log10 as log def train_multinomial_NB(spam_email_bag_of_words, ham_email_bag_of_words, text_in_all_document, spam_mail_in_all_documents, ham_mail_in_all_documents, size_of_total_dataset, size_of_spam_dataset, size_of_...
39f5c82349c6cfd7f747d20600e0fbea505beff0
633-1-ALGO/introduction-python-ninotchkanovelle
/12.1- Exercice - Listes et Tableaux/liste1.py
808
3.796875
4
# Problème : Réaliser une table de multiplication de taile 10x10 en utilisant la liste fournie. # Résultat attendu : un affichage comme ceci : 1 2 3 4 5 6 7 8 9 10 # 1 1 2 3 4 5 6 7 8 9 10 # 2 2 4 6 8 10 12...
8fcde055e710a0680df8dc858b03b2060821ea70
nbiadrytski-zz/python-training
/dive_into_p3/classic_iterator/abstract_aggr_iter.py
742
3.953125
4
import abc class Aggregate(abc.ABC): def iterator(self): """ Returns iterator """ pass class Iterator(abc.ABC): def __init__(self, collection, cursor): self._collection = collection self._cursor = cursor @abc.abstractmethod def first(self): ""...
e516d988442f9a0cec923e637a26e1559150f6b3
noecaserez/Ejercicio-Python
/ejercicios3/ejercicio04.py
923
4.03125
4
""" Ejercicio 4: Crear una función que, a partir de 4 números, devuelva el mayor producto de dos de ellos. Imprimir resultado por pantalla. """ #ejercicio 4 def producto(): producto_numeros = [] for i in range(4): numero = int(input("Ingrese un número: ")) producto_numeros.append(numero) pr...
85a867614ba9aa64fe90119092f3fb3dc02d4624
beginner-codes/beginnerpy-pypi
/beginnerpy/challenges/daily/c50_circular_shift.py
1,677
3.890625
4
import unittest from typing import List def circular_shift(lst1: List[int], lst2: List[int], n: int) -> bool: return False # Put your code here!!! class TestCircularShift(unittest.TestCase): def test_1(self): self.assertTrue( circular_shift( [1, 2, 3, 4], ...
437e3c2ae356b9323d58830cc4567d3adf38b228
priscilamarques/pythonmundo1
/desafio10.py
331
4.03125
4
##Desafio 10 #Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar. #Considerar dólar no valor de 3.27 real = float(input('Quanto de dinheiro vocë tem na carteira: R$ ')) dolar = real/3.27 print('Com R${:.2f} você pode comprar US${:.2f} dolares.'.format(real,...
84bbba243a108cf43ea4e2fa9ae9ec35ba16b15b
rpandey94/Housing-Price_Prediction-Web-Application
/Prediction_application.py
4,356
3.875
4
# Housing price prediction web application import os import joblib import locale import numpy as np import pandas as pd import streamlit as st # Reading data from csv file_path = os.path.join("datasets", "housing") def fetch_data(file_path=file_path): file_path = os.path.join(file_path, "housing.csv") retu...
aa378a188bce0e97a0545221e65f148838b3650c
angelavuong/python_exercises
/coding_challenges/whats_your_name.py
536
4.1875
4
''' Name: What's Your Name? Task: You are given the first name and last name of a person on two different lines. Your task is to read them and print the following: Hello <firstname> <lastname>! You just delved into python. Sample Input: Guido Rossum Sample Output: Hello Guido Rossum! You just delved into python. '...
272b35169a8186623afc046957907e556272894d
bartlomiejmusial/EtchASketch
/main.py
971
3.75
4
from turtle import Turtle, Screen from random import choice tim_turtle = Turtle() tim_turtle.color('red') screen = Screen() colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] def move_forward(): tim_turtle.forward(10) def move_backward(): tim_turtle.backward(10) def turn_left(): tim_t...
581e84c236a90f762f49ab4f7d60270dd174d962
mayaragualberto/Introducao-CC-com-Python
/Parte1/Semana3/Ex2.py
104
4.1875
4
Num=int(input("Digite um número inteiro: ")) Num2=Num%3 if Num2==0: print("Fizz") else: print(Num)
b2c7b6c17aff069b0dce4fa23f71ee9be3b20e3b
CodeHemP/CAREER-TRACK-Data-Scientist-with-Python
/17_Cleaning Data in Python [Part - 2]/1_exploring-your-data/02_further-diagnosis.py
978
4.40625
4
''' Further diagnosis In the previous exercise, you identified some potentially unclean or missing data. Now, you'll continue to diagnose your data with the very useful .info() method. The .info() method provides important information about a DataFrame, such as the number of rows, number of columns, number of non-mis...
e7f79141b1c99c0cf9cb7ac02035951b8478d89e
kondraschovAV1999/TAU.LAB1
/Week5.py
806
4.28125
4
# Кортежы # myTuple = [1, 2, 3] # Создаем кортеж # print(myTuple[1]) # sTuple = [4, 5, 6] # print(myTuple + sTuple) # print(len(myTuple)) # myTuple = (1, (2, 3), (4,)) # print(myTuple[1][0]) # man = ('Ivan', 'Ivanov', 28) # print(man[-1]) # myTuple = 1, 2, 3 # a, b, c = myTuple # print(b) # Цикл For # a = 1 # b = ...
f61e21078ff70c21dcecadf1376fa0fece79bdef
Irisviel-0/a1
/myq1.py
754
3.796875
4
grid_map = [] # Put the map in a list as a two-dimentional data for num in range(1, 11): ''' The for loop will generate each column of the map at a time ''' grid_map.append([x+str(num) for x in "ABCDEFGHIJ"]) def find_my_neighbourhood(x, y): ''' Using the provided coordinates to locate the neighbourhood...
071908e13f42cd0bd31078670c9767da344301e2
YX-Zang/Leetcode
/35 Search Insert Position.py
275
3.671875
4
class Solution: def searchInsert(self, nums, target) -> int: insert_index = [] for index in range(len(nums)): if target <= nums[index]: insert_index.append(index) return min(insert_index) if insert_index else len(nums)
d52b191e847741019af1f0d7fb97b21b7e39acbd
kprahman/py_book_exercises
/ch18/recursive summation.py
1,133
3.859375
4
def r_sum(nested_list): tot = 0 for element in nested_list: if type(element) == type([]): tot += r_sum(element) else: tot += element return tot print(r_sum([1,2,[3,4],5])) def r_max(nxs): """Find the maximum in a recursive structure of lists within other lis...
e7feae75caba9ef62735362f9733c783df5081ad
rafaelperazzo/programacao-web
/moodledata/vpl_data/303/usersdata/285/67370/submittedfiles/testes.py
355
3.9375
4
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO nota 1 = float (input('digite sua primeira nota')) print('nota1') nota 2 = float (input('digite sua segunda nota:')) print('nota2') nota 3 = float (input('digite sua terceira nota:')) print('nota3') nota 4 = float (input('digite sua quarta nota:')) print('nota4') ...
ec7d6ae153fd3c2fec30b3eb377f4b84d52bdc0e
culeo/LeetCode
/Python/DynamicProgramming/test_paint_house_ii.py
1,861
3.875
4
# coding: utf-8 def min_cost(costs): """ 265 Paint House II(房屋染色 II) There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same...
de6ef0dc791e399c7820fe5ff47a0fd54778da12
tgtn007/LeetCodeCompany
/OA/treeBottom.py
851
3.625
4
def treeBottom(tree): i, j = split(tree) l = tree[j+1:i+1] r = tree[i+2:len(tree)-1] if l == r == "()": return [int(tree[1:j])] if depth(l) < depth(r): return treeBottom(r) if depth(l) > depth(r): return treeBottom(l) return treeBottom(l) + treeBot...
bef1fb739bad571413b6fe1ab26c8abefce36552
AcrobatAHA/HackerRank-problem-solving
/HackerRank Transpose and Flatten problem in Python Numpy.py
172
3.5
4
import numpy n,m = map(int,input().split()) my_array = numpy.array([input().split() for i in range(n)],int) print(numpy.transpose(my_array)) print(my_array.flatten())
3bbfe1ffc0d068df8a01dfc148b897f8fb97fe4e
karthi1015/Antler
/PyRevit Extension/Antler.extension/lib/frange/frange.py
3,491
4.46875
4
import numpy as _np class frange(): """ Return an object can be used to generate a generator or an array of floats from start (inclusive) to stop (exclusive) by step. This object stores the start, stop, step and length of the data. Uses less memory than storing a large array. Example ---...
118249f215fbe9a293e5ec301f6af734c17ec9d1
kyletruong/epi
/9_binary_trees/4_lca_with_parent.py
454
3.578125
4
# Given p and q, find their least common ancestor # Nodes have a parent field def lca(p, q): def height(node): ht = 0 while node.parent: node = node.parent ht += 1 return ht p_ht, q_ht = height(p), height(q) diff = abs(p_ht - q_ht) if q_ht > p_ht: ...
3459c92c734d443fa780a15d137408a5ded728b5
nkLintcodeTeam/problems
/others/union_find_sets/union_find_sets.py
969
3.609375
4
class UnionFindSet: def __init__(self, n): self.parents=[] self.ranks=[] for i in range(n): self.parents.append(i) self.ranks.append(0) def connected(self, a, b): return self.find(a)==self.find(b) def find(self, x): if x!=self.parents[x]: ...
0e72b53aea0bfbe9fc503a61579ff219d00bfd9d
boonchu/python3lab
/coursera.org/python1/week3/clock-face-sample.py
2,211
3.90625
4
# A simplified Clock example. Just draw the "second" hand # import simplegui import math import time # Game constants WIDTH = 220 HIGHT = 220 # Some extra features is_analog = True # Toggle analog display, default to yes mode_str = ["Analog", "Digital"] # Human readable output def draw_clock_hand(canvas, center, le...
a37efeb00867935de1d3217653b02ef56f76996e
saathvik2006/learning_python
/Functions/integer_multiplication.py
383
4
4
def get_int(z): int(z) return z def mult(x,y): counter=1 product=0 while counter<=y: product+=x counter+=1 return product a=int(input("What is your number? ")) b=int(input("What do you want to multiply by? ")) print (mult(a,b)) x_input=input("What is your number? ") y_input=input("What is your multipl...
028e8fabbfd356d4f4097bc6c3867c4b848cc29c
ryfeus/lambda-packs
/H2O/ArchiveH2O/past/types/olddict.py
2,721
4.125
4
""" A dict subclass for Python 3 that behaves like Python 2's dict Example use: >>> from past.builtins import dict >>> d1 = dict() # instead of {} for an empty dict >>> d2 = dict(key1='value1', key2='value2') The keys, values and items methods now return lists on Python 3.x and there are methods for iterkeys, ite...
8b268e178041d28659547d8bd13e7ebace79f00d
ankiyong/Before_TIL
/string_func.py
2,290
3.625
4
#len() : 문자열의 길이 반환 str = "erwer" print(len(str)) #count() : 문자열 내에 있는 특정 문자의 개수 반환 print(str.count('e')) #find() : 문자열 내에서 문자열이 존재하는지 여부와 문자열의 시작 위치를 반환한다. ##문자열이 존재하면 시작위치 반환 / 미존재시 -1 반환 crawling = 'Data Crawling is Fun' print(crawling.find('Fun')) #문자열의 시작 위치 반환 print(crawling.find('a')) #중복 문자 존재 시 가장 앞의 문자 위치 반...
0c95f23d38f9782f75cdc11eadf45a37f9e3a98a
XinliJing/leetcode
/98. 验证二叉搜索树.py
644
3.875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None #学习学习 class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ return...
368a5666061028fd45f09b804ebd9281203ad1ca
devjackluo/Learn-Python
/LearnPython/basics/pythonConditionals.py
876
3.96875
4
# if statement x = 6 y = 9 z = 4 a = 2 b = 6 if x > y: print("x greater than y") if x > z: print('nest statement x > z') if x < y: print("x less than y") if x > z: print('\tnest statement x > z') print("") # python can do multiple conditions at once... wtf if z < y > x > a: pri...
d6d2192ab16613aa3a74ff67560b696972defb1b
KetanChopade/OCFM
/sql_operation.py
345
3.765625
4
import sqlite3 as sql conn = sql.connect("onlineclasse.sqlite2") curs = conn.cursor() def createCourseTable(): curs.execute("create table course(cno number primary key ,course_name text , faculty_name text ,class_date date ,class_time text, fee real , duration number )") conn.close() print("table is creat...
347b8627d410f9d6f5190dfeebbc770eb7a9cd6e
juniorppb/arquivos-python
/ExerciciosPythonMundo1/48. Ordem da Apresentação.py
334
3.71875
4
import random a1 = str(input('Qual o nome do primeiro aluno?')) a2 = str(input('QUal o nome do segundo aluno?')) a3 = str(input('Qual o nome do terceiro aluno?')) a4 = str(input('Qual o nome do quarto aluno?')) nomes = [a1, a2, a3, a4] ordem = random.shuffle(nomes) print('Qual a ordem para a apresentação do trabalho') ...
2f63c4ea2bbf04b5b370a39b63bb382400cee03d
eduardox23/CPSC-115
/lab 03-11-2010/tion.py
671
3.796875
4
# # File: tion.py # Author: Vlad Burca # Lab Section: Wednesday # # Created: 11/03/2010 # Last Modified: 11/03/2010 # # Exercise 1.2 # def isaSuffix(word, suff): if word[len(word)-len(suff):] == suff: return True else: return False def getSuffix(list, suff): suff_list = [] for w...
bd260f44a1128dc5a445b33b9a64d3727b8a0b9a
hupipi96/pyldpc
/pyldpc/ldpc_images.py
10,715
3.578125
4
import numpy as np from .imagesformat import int2bitarray, bitarray2int, Bin2Gray, Gray2Bin, RGB2Bin, Bin2RGB from .codingfunctions import Coding from .decodingfunctions import Decoding_BP_ext, Decoding_logBP_ext, DecodedMessage from .ldpcalgebra import Bits2i, Nodes2j, BitsAndNodes import scipy import warnings __all_...
eb146576d941042e899d27823d966b6161fa0d19
efitr/CS-2-Tweet-Generator
/Practicando Tweet GIT/JC3dictionary.py
772
3.59375
4
import os import sys import random import time def get_words_list(): start_time = time.time() with open("/usr/share/dict/words", 'r') as directory: file_content = directory.read() string_list = file_content.split("\n") return string_list num = 10 def randomize(num, string_list): #''' version ...
1826a2b0036ca8723a843fd0e686891bc57af711
borntyping/diceroll
/diceroll/evaluate.py
2,355
3.5
4
""" The Expression class """ from diceroll.components import UnrolledDice, Operator class Expression (object): """ A diceroll expression object, and the evaluator for it """ def __init__ (self, tokens): self.depth = 0 self.tokens = list(tokens) def __repr__ (self): return repr(self.tokens) def log (s...
da94f8c14bac692267dfec2063b1bcd699eaa827
Jesta398/project
/datastruvctures/polymorphism/quest2.py
276
3.859375
4
class Parent1: def m1(self): print("inside parent1") class Parent2: def m1(self): print("inside parent2") class child(Parent1,Parent2):#chils is inheriting parent1 and parent2 def m3(self): print("inside child") c=child() c.m3() c.m1()
12957cc9783edc931406d64790a6dfc710218ebb
mcxu/code-sandbox
/PythonSandbox/src/misc/string_to_sentence.py
2,203
3.75
4
''' Word Break Problem ? Given a string of words, and a dictionary of words. Turn the string into a sentence and return it. If this cannot be done, then return None. Example: s = "hellothere" dictionary = {"hello", "there} output: "hello there" Example: s = "hellothere" dictionary = {"hello", "the"} output: None (Si...
8aa84971370311efe755e2e59ccd72017310e681
yanivn2000/Python
/Syntax/module3/04_while1.py
73
3.59375
4
count=0 while count < 10: print(f"The count is:{count}") count+=1
2fa7679b67cde147f90900ad9b0bc543f6edc6c2
AlberVini/exp_regulares
/aulas_exemplos/aula07.py
1,274
3.796875
4
# shorthand # \w para encontrar -> [a-zA-Z0-9À-ú] # \W negação [^a-zA-Z0-9À-ú] # \d para encontrar só números -> [0-9] # \D negação [^0-9] # \s [\r\n\f\t] # \S negação, bom para eliminar espaços de strings # \b borda, capta uma palavra com determinado começo ou final # \b para encontrar uma palavra com determinado núm...
3622642192c03e6e654acde4bc9d8253f24e42a2
AGauchat/clase01
/58052-agustin-gauchat/clase01/test_decimal_numbers.py
2,408
3.671875
4
import unittest from decilam_numbers import decimal_to_roman class TestsDecimalNumbers(unittest.TestCase) : def test_decimal_1_to_roman(self): roman_number = decimal_to_roman(1) self.assertEqual(roman_number, "I") def test_decimal_2_to_roman(self): roman_number = decimal_to_roman(2) ...
51bea350d440603b53f13ae8f38ef5c07b445792
annaymj/LeetCode
/PerfectSubString.py
975
3.515625
4
``` # find the perfect substring that has each characater appear exactly k times s = '1102021222' k = 2 # return the number of perfect substring, expected return 6 # s[0:1] = 11 # s[0:5] = 110202 # s[2:5] = 0202 # s[1:6] = 102021 # s[7:8] = 22 # s[8:9] = 22 ``` def isPerfect(substring, k): s_dict = {} for cha...
c50f0dd256ac6d76f74a7e77b64b90f2b617bdb8
shaikhAbuzar/Diffie-Helman
/ShiftCipher.py
1,415
4.03125
4
# importing numpy library import numpy as np # function for shift cipher def shift(string, key): # list to store ascii values of characters ascii_list =[] for i in string: # converting the characters to 0-255 # using ord to get ascii values ascii_list.append(ord(i)) # -65) # a...
813d14537199669b319549eecab8186c3a47dd74
princemathew1997/random-python
/Day 10/d10-11.py
122
3.96875
4
#multiplication table a = int(input("Enter a number:")) for i in range(1,11): m = a * i print(a,'*',i,'=',m)
555f6123d898cae15a6ec478ac2cf9bf8448ab7e
Portfolio-Projects42/UsefulResourceRepo2.0
/GIT-USERS/TOM2/cspt19long/comp.py
562
3.890625
4
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"Name: {self.name}, Age: {self.age}" def __repr__(self): return f"<Person: {self.name}, {self.age}>" dave = Person("Dave", 67) dave2 = { "name": "Dave", "age": 67 } s...
9241564b470a8df518cbbaf650428c2a0a35e792
tagler/Maryland_Python_Programming
/chapter9_files7.py
467
3.71875
4
import sys import os if len(sys.argv) == 3: file1 = sys.argv[1] file1 = sys.argv[2] else: file1 = "text1.txt" file2 = "text2.txt" list_names1 = [] list_names2 = [] with open(file1,'r') as f1: for line in f1: list_names1.append(line.strip()) with open(file2,'r') as f2: for line in f...
ae288ea2eb97c5f7bd77c30a096434fd649baadd
jjspetz/PyGames
/characters.py
2,792
3.65625
4
''' To Do: add lifes and final death when lifes up add leader board ''' import pygame, random class Sprite: def __init__(self, filename): self.img = pygame.image.load(filename) self.pos = random.choice([[50,50],[50,420],[420,420],[420,50]]) self.colorkey = [0, 0, 0] self....
838c6676073bb5bc04df39ac47a3260c2048e29e
abelidze/JentuBot
/archive/using_multiprocessing/settings.py
514
3.546875
4
def to_ascii(h): strs = "" for i in range(len(h)//2): strs += chr(int(h[(i*2):(i*2)+2], 16)) return strs def drink(message): message = to_ascii(message) for i, v in enumerate(message): message = message[:i] + chr(ord(v)+12) + message[i+1:] return message vodka = "..." #def to_hex(s): # strs = "" # for i in...
a43e1ae5f4ea8488d955b7b7535d1d662687ff64
SusanaPavez/zoo-python
/clases/Ornitorrinco.py
1,010
3.78125
4
from clases.animal import Animal class Ornitorrinco(Animal): #por qué se me ocurrió un nombre tan largo? def __init__(self, nombre,edad,nivelsalud,felicidad): super().__init__(nombre,edad,nivelsalud,felicidad) super().alimentacion() self.alimentacion() self.nivelsalud = nivelsalud ...
7d23919d6688962e3ef50c253f3c0b9ee067452f
ericdegan/Curso-em-Video
/ex062.py
524
3.765625
4
pt = int(input('Diga o primeiro termo: ')) rz = int(input('Diga a razao: ')) d = pt + (10 - 1) * rz pa = 0 c = 1 z = 1 while c < 11: f = pa + pt pa += rz print(f) c += 1 if c == 11: prox = int(input('Você gostaria de ver mais quantos termos: ')) if prox != 0: ...
a5c49b3cfa43207f81b43808054c6bd34a279e79
sakthi5006/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python-2
/Ch04. Recursion/towersOfHanoi.py
355
3.90625
4
def printMove(start, end): print("Moving from " + start + " to " + end) def towers(number, start, spare, end): if number == 1: printMove(start, end) else: towers(number - 1, start, end, spare) towers(1, start, spare, end) towers(number - 1, spare, start, end) ...
5ed3082108fa5eb11b1219bc12aac204818c09fa
daniel-reich/turbo-robot
/8gE6FCdnWbECiR7ze_19.py
3,101
3.75
4
""" In numbers theory, a positive composite integer is a Smith number if its digital root is equal to the digital root of the sum of its prime factors, with factors being counted by multiplicity. Trivially, every prime is also a Smith number, having just one prime factor that is equal to itself. If two Smith numbers...
0101e6c4edbb24f6a519138a28146f670dae5ef4
mmkhaque/LeetCode_Practice
/125. Valid Palindrome.py
1,937
3.53125
4
class Solution: def isPalindrome(self, s: str) -> bool: if s == reversed(s): return True if len(s) == 1: return True left = 0 right = len(s) - 1 while left <= right: while not s[left].isalnum...
dd919792838b2778fff7f1ea814ba331a5982e2f
ferisso/forloopython
/ex10.py
212
4.125
4
# Faça um programa que receba dois números inteiros e gere os números inteiros que estão no intervalo # compreendido por eles x = int(input('> ')) y = int(input('> ')) for x in range(x, y + 1): print(x)
c03b88fe247f1fa1dec0c5738df9e902117b1ab1
tk3/backlog-api-in-action-python
/05_print_date_from_unix_time.py
276
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import time import datetime def print_date_from_unix_time(unix_time): date = datetime.datetime.fromtimestamp(unix_time) print(date) if __name__ == '__main__': now = time.time() print_date_from_unix_time(now)
31473171e6785d1133a6c7a900473c5fb28e1c16
blane612/lists
/primary.py
5,926
4.6875
5
# name: # author: # -------------------- Section 1 ------------------------- # # ------------------ List Creation ----------------------- # print('# -------------------- Section 1 ------------------------- #') print('Creating an Empty List' '\n') # 1. Creating an Empty List # -----------------------------------------...
f4709cd1d6f3f2f645a9dcf0743a0fefe073014e
jainish-jain/GeeksforGeeks
/Mathematics/Quadratic Equation Root.py
848
3.8125
4
#{ #Driver Code Starts #Initial Template for Python 3 import math # } Driver Code Ends #User function Template for python3 ##Complete this function from math import floor def quadraticRoots(a,b,c): #Your code here s=(b*b)-(4*a*c) r=abs(s)**0.5 if s>0: h=floor((-b+r)/(2*a)) l=flo...
a9f24539c18c537b96a808dabc01506f4733fa5f
handsomm/PythonLearn
/Chapter 4 (list & tuple)/02_list_slicing.py
114
3.671875
4
# List slicing friends = ["shibu", "soumya", "handsomm", "tom", "jerry"] print(friends[0:4]) print(friends[-4:])
fe4a95ff7a5b3e86216fa5dae08e2fe8b918f3d6
PA3EFR/Supermarket_superpy
/report_inventory.py
1,801
3.546875
4
import os import sys import fileinput import csv import math from os import system, name from print_tabel import print_tabel count = 0 sales_price = 0.0 purchase_price = 0.0 sold_counter = 0 expire_counter = 0 value_loss = 0.0 full_path = os.path.realpath(__file__) file_directory = os.path.dirname(full_...
9b3a5d14d59414311b806c799394e04c01f2c5c6
tjperr/aoc2020
/q4/a.py
487
3.515625
4
import re with open("input.txt") as file: entries = file.read().split("\n\n") passports = [] for entry in entries: passport = {} data = re.split("\\n| ", entry) for field in data: if ":" in field: key, value = field.split(":") passport[key] = value passports.appe...
2534c1942f57399c023f519ab67ea0cf4df8fc5a
sainihimanshu1999/Data-Structures
/July2021/BitManipulation/ConsistentStrings.py
259
3.8125
4
'''using basic set''' def consistent(allowed,words): allowed = set(allowed) count = 0 for word in words: for letter in word: if letter not in allowed: count+=1 break return len(words)-count
fde6021ada2e72d88d11c0ab4e99d4277b38b54d
heitorchang/learn-code
/levelup/2018_jun/cracking_the_coding_interview/data_structures/queues_tale_of_two_stacks.py
1,471
4.09375
4
description = """ A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e....
f42fb927e0cdcb26a004b0bca9eafeabc397bb6f
ptrcode/cloudauto
/vmware-automation/python/check_port.py
678
3.9375
4
#!/usr/bin/python # Basic python check to see if a port is open, can be used for many different applications. # Author: Mark Austin <ganthore@gmail.com> # Usage: # ./check_port.py <host/ip> <port> import socket; import sys; import errno; sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def check_host(remote...
4420382055090bec7bfd23ce6ff93dcad1d12449
vivibruce/dailycodingproblem
/max_nonadj_sum/max_nonadj_sum.py
521
4
4
''' Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5 ''' inplst = list(map(int, input().split())) included_sum, e...
42f42ae9d4b0465d37aed32afc0d689b38ed220d
umelly/gf-lesson
/byte-of-python/task_9x9.py
457
3.546875
4
# -*- coding:utf-8 -*- """ 列*行=列行 1*1=1 1*2=2 2*2=4 1*3=3 2*3=6 3*3=0 ... """ for i in range(1,10):#行 for j in range(1,10):#列 if i>=j: print '%s*%s=%s' % (j,i,i*j), print print "\n\n", "="*80 ,"\n" print "".join([ '%s*%s=%s%s' % ( j, i, i*j, "...
4be486c6d63217fb9715040826b75e8b26bbe105
GreatRaksin/TurtleGraphics
/ListsOfNumbers.py
262
3.796875
4
import turtle tina = turtle.Turtle() tina.shape('turtle') screen = turtle.Screen() tina.pensize(2) tina.speed(50) number_list = range(1, 50) tina.color("green") for number in number_list: tina.forward(number * 2) tina.left(60) screen.exitonclick()
9fb8fc13d38b50a44bfb745fc2236709b9a75b67
ayushmad/puzzles
/project_euler/prob64.py
909
3.609375
4
import os import math import sys # This is can be later changed to a library # Takes a number at removes all the square terms def square_term(num): terms = range(2, int(math.ceil(math.pow(num, 2)))); terms.reverse(); for i in terms: if num%(i*i) == 0: num = num/(i*i); return num;...
2f281a4abfcec8c0da69c19f7d80cadab9478f42
nengdaqin/Python
/Study/Python_Basic_Study/file/json_file/qnd_05_josn文件写入.py
323
3.71875
4
# 导入模块 import json # 定义一个字典 my_dict = {"name": "小明", "age": 23, "no": "007"} # 将字典转成json -> 进行编码 json_str = json.dumps(my_dict) # 打印json字符串 print(type(json_str)) # 把json数据写入到文件中 with open("hm.json", "w", encoding="utf-8") as f: f.write(json_str)
a8b2cdd9ab7bcd28eaf23ba397a0e15929c51b4b
robinyms78/My-Portfolio
/Exercises/Python/Learning Python_5th Edition/Chapter 5_Numeric Types/Examples/Bitwise Operations/Example2/Example2/Example2.py
193
3.984375
4
# Binary literals X = 0b0001 # Shift left print(X << 2) # Binary digits string print(bin (X << 2)) # Bitwise OR: either print(bin (X | 0b010)) # Bitwise AND: both print(bin (X & 0b1))
3627fb347bc2450d8d866fe797890347c4cbf03c
LucasPAndrade/_Learning
/_Python/Fundamentos-CursoEmVídeo/Desafio 102.py
706
3.765625
4
print('=' * 10) print('DESAFIO 102 - Fatorial v.3') print('=' * 10, '\n') def fatorial(n, show=False): """ Calcula o fatorial de um número. :param n: Número a ser calculado. :param show: (opcional) Mostrar ou não o cálculo. :return: Valor do fatorial de um número n. """ f = 1 for c in ...
7ec6b92e961c3d382cad95a06531bae6276c81fa
YazzyYaz/codinginterviews
/recursive/sum.py
172
3.625
4
def sum(alist): if len(alist) == 0: return 0 else: return alist[0] + sum(alist[1:]) if __name__ == "__main__": print(sum([0, 1, 2, 3, 4, 5]))
a8e67cbd7935c21ecbac0e46a2598b84faa208fe
soundlake/projecteuler
/problem047/sol.py
1,226
3.53125
4
primes = [2, 3] def extendPrimesUpto(limit): if limit < primes[-1]: return primes def isPrime(n): if n in primes: return True for p in primes: if p > n**.5: return True if n % p == 0: return False return True o1 = (5 - primes[-1]) % 6 o2 = (9 - primes[-1...
dbf4a05aa269427dc735ff81510aed60182b1d3c
RowiSinghPXL/IT-Essentials
/3_condities/oefening3.6.py
375
3.59375
4
basis_prijs = 5 huidig_jaar = 2018 jaar = int(input("Van welk jaar is de film: ")) rating = int(input("Welke rating heeft de film (1 - 5): ")) prijs = basis_prijs if huidig_jaar - jaar < 2: prijs += 1 if rating == 4 or rating == 5: prijs +=2 elif rating == 3 or rating == 2: prijs +=1 if prijs > 7: pr...
0576b4505c8e0f08bb2470d81baf02264e632282
LizinczykKarolina/Python
/Regex/ex30.py
927
4.3125
4
#46. Write a Python program to find all adverbs and their positions in a given sentence. import re sample_text = """ Clearly, he has no excuse for such behavior. He was carefully disguised but captured quickly by police. """ pattern = r"\w+ly" for a in re.finditer(pattern, sample_text): print "{0}-{1}: {2}".form...
85fac8915b3bf2c1e96a52f197aefdd55f885d87
mrmoore6/Module-4-Py-2
/Card_Game.py
803
3.53125
4
""" Name: Michael Moore Date: 2/11/2021 Program: Card_Game.py Description: This game randomizes a 6x6 array and manipulates for each players hand and sums the total \ for winner. """ import numpy as np my_array = np.arange(1, 37) np.random.shuffle(my_array) my_array = np.array(my_array) my_array.resize(6, 6) x = np.i...
6977fbc400c6f6f5af433c8f0b9a9278449eff95
Zenglinxiao/ReinforcementLearning
/session_2/agent.py
5,102
3.609375
4
import numpy as np from scipy.special import gamma np.random.seed() """ Contains the definition of the agent that will run in an environment. """ class RandomAgent: def __init__(self): """Init a new agent. """ def choose(self): """Acts given an observation of the environment. ...
3adcc28caccac8e55a2be53e1fdcd20fc60e3be0
elizabethdaly/pands-project
/get-data.py
3,389
3.890625
4
# Elizabeth Daly # HDip Data Analytics 2019 pands-project # # get-data.py # Script to read in & analyse the iris data set. # # ########################################################### # Import Pandas data analysis library. import pandas as pd # Import matplotlib for 2D plotting. import matplotlib.pyplot as plt # ...
8f2100cb292fd30dd7c7caf712b82c12cc67d7d4
iayoung85/2ndsandbox
/postage3.py
201
3.640625
4
#figure 3 program def postage(weight): import math costfig3=49 if weight>1: costfig3=costfig3+22*math.ceil(weight-1) if weight>3.5: costfig3 +=49 return costfig3/100
78cfc50c70cc9c75ed3e413c4f499bbe26c56100
sarias12/AirBnB_clone
/console.py
6,923
3.515625
4
#!/usr/bin/python3 """ The command interpreter """ import cmd import sys import shlex import models from models.base_model import BaseModel from models.user import User from models.place import Place from models.state import State from models.city import City from models.amenity import Amenity from models.review import...
c2321344bbe7ee6e338a879bceb69a39bed73f1d
danielthorr18/forritun_git
/FUNCTIONS/7.1.functions.py
326
4.15625
4
def find_min(num1, num2): if num1 < num2: return(num1) else: return(num2) # find_min function definition goes here first = int(input("Enter first number: ")) second = int(input("Enter second number: ")) minimum = find_min(first, second) # Call the function here print("Minimum: ", mi...
eb0212d3c2443b4266f51b9d7de4b4fba0daa6df
dwaq/advent-of-code-solutions
/2022/01/1-feed.py
442
3.625
4
txt = open("input.txt", "r").readlines() #print(txt) # store each elf's calories elf = [] count = 0 for line in txt: # when not a newline if (line != '\n'): # add that to the elf's count count += int(line) else: # put that elf's count into the list elf.append(count) ...
c06423f62784888a5ba0591ae6a1e3a41861beaf
ct61632n/CS3612017
/Python/Exercise7.py
484
4.1875
4
#prints list def List(): list = ['a','b','c','d','e'] for i in (list): print (i) List() print("\n") #prints list reversed def Listrev(): list = ['a','b','c','d','e'] for i in reversed(list): print(i,) Listrev() print("\n") #prints len of the list def Size(): ...
706307c2d91b068ad301f3ebcba3cce0a443edcd
rajlath/rkl_codes
/Miscellaneous/Trie2.py
1,422
4.125
4
from collections import defaultdict class Trie(object): ''' implements Trie data structrue methods include Insert Search Prefix ''' def __init__(self): self.root = defaultdict() def insert(self, word): ''' @param {String} word @return void inserts a word ...
3022f5cc163a8ff72cf17333a5a414eafff86c0f
JakubKazimierski/PythonPortfolio
/AlgoExpert_algorithms/Medium/Permutations/test_Permutations.py
1,004
3.703125
4
''' Unittests for Permutations.py February 2021 Jakub Kazimierski ''' import unittest from Permutations import getPermutations class test_Permutations(unittest.TestCase): ''' Class with unittests for Permutations.py ''' def SetUp(self): ''' Set Up input list. ...
e09c72db774177b13819ffbcbdc494380d2ddd59
DT2004/Python2
/app.py
424
3.96875
4
character_name = "Murasame" # this is the first variable character_age = "8" # this is the second variable print("There once was a boat named "+ character_name + ", ") # vatiables are not enclosed by strings print("She was "+ character_age + " years old.") print(character_name + " really liked helping her friends,") p...
4871ef2ea79f5369e27673b1efd60a0fc76a85a4
jovemsabio/CPF-Calc
/main.py
299
3.53125
4
from validador import validaCPF if __name__ == '__main__': while True: cpf = input('Informe o CPF (apenas números), \'q\' para sair: ') if cpf == 'q': break if validaCPF(cpf): print('CPF válido') else: print("CPF Invalido")
cbc46e1c31476dd41006abe275a8f8bdc9280361
MasKong/Algorithms
/sort.py
6,851
4.0625
4
class Sort(): def __init__(self, l = None): if l is not None: assert type(l) == list,("please input a list") else: l = self._generate() self.l = l self.result = None def insert_sort(self): l = self.l #add new reference to self.l, change l wo...
127712ac25c36d95dd83f0068133051413a4fe14
thedegar/thinkful-data-science-webscrape
/education.py
8,041
3.859375
4
##################################################### # Tyler Hedegard # 6/21/2016 # Thinkful Data Science # GDP + Education Web Scrape Project ##################################################### from bs4 import BeautifulSoup import requests import sqlite3 as lite import pandas as pd import matplotlib.pyplot as plt ...
3a66367816e3083caa9befbdc5c4f6b0ecd891cb
ricvo/argo
/word_embeddings/test/nearest_words_from_analogy.py
5,107
3.578125
4
""" Testing of a word embedding, answers to queries a:b=c:d. It is possible to specify a, b and d; so to obtain the word embedding nearer to a-b+d, i.e. the best approximation for c. """ import argparse import numpy as np import os, sys from utils import * parser = argparse.ArgumentParser(description='Testing of a ...
06dcd0f4a45110a1787fe570577304e85c3eb0c9
k4t0mono/regex-to-code
/MinimizaAuto/class_auto.py
2,799
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re class Auto: def __init__(self, arq): arquivo = open(arq, "r") linhas = arquivo.read().strip().splitlines() # Achar estados # O estados tem que conter pelo menos uma letra seguido por pelo menos um digito e = re.compi...
be8f6441dc947ec146d8f5573a5754d50f9a7b4b
xieh1987/MyLeetCodePy
/Sqrt(x).py
294
3.5625
4
class Solution: # @param x, an integer # @return an integer def sqrt(self, x): head, end = 0, x/2+1 while end>=head: mid=(head+end)/2 if mid**2>x: end=mid-1 else: head=mid+1 return int(end)
f0f9321e8400115c351327461f821a261e7eff93
Fuerfenf/Basic_things_of_the_Python_language
/data_type/collections/UserList.py
1,212
4.40625
4
# Python supports a List like a container called UserList present in the collections module. # This class acts as a wrapper class around the List objects. This class is useful when one wants to create a list # of their own with some modified functionality or with some new functionality. # It can be considered as a way ...