blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7f69c4d7035594b4d72f9e8143b1996ca238dd53
godmoves/Poker_CFR
/example_strategy.py
4,000
4.03125
4
# coding: utf-8 import numpy as np def random_distribution(n_items): """ Returns a random probability distribution over n items. Formally, we choose a point uniformly at random from the n-1 simplex. """ return np.random.dirichlet([1.0 for i in range(n_items)]) def uniformly_random_strateg...
d06ad9a95412bf05d093c4fcbebb52c9727aae9c
Alexidis/python_basics
/lessons/lesson4/lesson4_6.py
1,687
3.71875
4
from itertools import count, cycle def count_iter_creator(start_elem, repeats=5): """Не бесконечный итератор последовательности""" # вычисляем максимальное количество повторений max_repeats = start_elem + repeats for i in count(start_elem): # т.к. идем с шагом 1 то дополнительный счетчик не вв...
90783794511cc5a75625dd95f845ab379d0e763d
KALALIZ/PythonCode
/Term1/Lab04/Lab04_4_610510670.py
1,008
3.84375
4
#!/usr/bin/env python3 # ศิลาลักษณ์ แก้วจันทร์เพชร # 610510670 # Lab 04 # Problem 4 # 204111 Sec 001 def round_to_int(x): if x < 0: m = 1 #ให้ 1 = ค่าจำนวนลบ else: m = 0 #ให้ 0 = ค่าจำนวณบวก a = abs(x) #ทำให้เป็นจำนวณเต็มบวกโดยเก้บค่าไว้ที่ a if (a%...
a6fcb4e0e61aa3da89ef96a0ad2c45e75807d4ae
henrynferg/AStar_Visualization
/AStar/Square.py
846
3.625
4
class Square: blue = "#0000F0" green = "#00F000" grey = "#909090" def __init__(self, side, x, y, color=blue): self.side = side self.x = x self.y = y self.color = color self.neighbors = [] self.isImpassible = False # Can pass thru any square by ...
81fd3a05921b22b8cd1bcd8a430c862a36da24d6
Emanoel580/Algoritmos
/1 Atividade Semana 02/q06media2.py
200
3.609375
4
A = float(input()) B = float(input()) C = float(input()) peso1 = 2 peso2 = 3 peso3 = 5 peso_total = 10 media = (A * peso1 + B * peso2 + C * peso3) / peso_total print('MEDIA = {:.1f}'.format(media))
0152c4ef3ae174ada27f4a22c0a97bad699f84c4
minamh/Python-Fundamentals
/Strings and Collections/Strings.py
706
4.375
4
#Example of string conctenation concatinatedString = "First""Second" print(concatinatedString) text= """This is a multiline string""" print(text) #Another way to do it text2 = "This string \nspans \nmultiple lines. " print(text2) #This is a raw string rawString = r"C:\Users\minah\OneDrive\Pictures" print(rawString)...
b253d9d3d3b3eb9666cb093af5cb3a751aec9053
gdiman/flask
/sql/sql_rand.py
353
3.828125
4
import sqlite3 import random import sqlite3 conn = sqlite3.connect("newnum.db") c = conn.cursor() brk = 4 while brk <> 5: print("\n\n") print("Select a SQL operation on 100 random numbers (enter 6 to quit:\n") print(" 1. AVG()\n") print(" 2. COUNT()\n") print(" 3. MAX()\n") print(" 4. MIN()\n") print(" 5...
65ae315d20c8d4b7a3d7596bd07fc442d4319d7e
tugba-star/class2-functions-week04
/10.unique list.py
318
4
4
def unique_list(list1): #function to get unique values list_set=set(list1) #insert the list to the set,Since the number cannot be repeatedly written to the set list2=(list(list_set)) #convert the set to the list print(list2) list1 = [1,2,3,3,3,3,4,5,5]# driver code print("unique list is") unique_list(list1)
f5877f0ff43e8eec007836e35e267e67cd91f1c6
Shershebnev/BioInfo
/DNAtotal.py
23,993
3.609375
4
# list of possible nucleotide changes mutations = {'A' : ['T', 'G', 'C'], 'T' : ['A', 'G', 'C'], 'G' : ['A', 'T', 'C'], 'C' : ['A', 'T', 'G']} # Counts number of times pattern appears in the text def PatternCount(genome, pattern): ''' (str, str) -> int >>> PatternCount("GCGCG", "GCG") 2 ''' ...
f99564313e3aed3de044b9c53b11ff0d6ed759bc
ibianco91/curso_em_video
/exercicios/desafio 34.py
211
3.75
4
s = float(input('qual o seu salario? \nR$')) if s> 1250: print('o seu salario passara a ser R${:.2f}'.format(s+(s*10/100))) else: print('o seu salario passara a ser R${:.2f}'.format(s + (s * 15 / 100)))
fe914b91f1526b7bb568a3bd2494e31db04b1dd9
Aasthaengg/IBMdataset
/Python_codes/p03455/s904226012.py
101
3.921875
4
A,B = input().split() A = int(A) B = int(B) if A * B % 2 ==0: print ('Even') else : print ('Odd')
1ca1f7a6055cdfb11a8327fca5c736ea65a7b42b
AliceCryer/siv-texture-analysis
/texture/analysis/autocorrelation_function.py
6,507
3.515625
4
import numpy as np from PIL import Image class ACF: """ Class used to compute the autocorrelation function of an image and some related statistical parameters. It computes the autocorrelation matrix and texture parameters of directional memory, mean values, moments. An instance of the ACF class holds...
afb2879c27fb90f70a6b42f270531d46f173f9fc
jacoloves/python_tool
/opt/src/atcoder/past/b1.py
371
3.640625
4
def main(): num = int(input()) str = input() array = [] for i in range(len(str)): change_str = ord(str[i]) over_num = change_str + num if (over_num > 90): over_num = over_num - 90 + 64 array.append(chr(over_num)) str2 = ''.join(array) ...
c6b9fb0d2522c14611776ac84059823d1d24466b
qhuydtvt/C4E3
/Assignment_Submission/sondp/lab/water_pump_lab.py
306
4.125
4
import datetime n=input("Water is available or not? ") now=datetime.datetime.now() hour=now.hour if n== "available": if hour >=5 and hour <=10: print("Pump is turn on ") elif hour >=20 and hour <=22: print("Pump is turn on") else: print("Pump is turn off") if n=="not": print("water is not")
0c94c1966aa84a7c331e94b1aa1d51459ab6a6ed
cafeunder/zero-DeepLearning
/chapter6/optimize.py
782
3.703125
4
import random # テスト関数 def function(x, y): return (1 / 20) * x * x + y * y # テスト関数の勾配 def gradient(grads, x, y): grads["x"] = 1 / 10 * x grads["y"] = 2 * y def optimize(optimizer): epsilon = 1e-4 limit = int(1e+5) gen = 0 noOfTrial = 10 # 10回試行の平均 for trial in range(noOfTrial): # 最適化メイン...
f116a3b721304f47925896f7c2a5e78335b4af31
YifengGuo/python_study
/data_structure/random/common_apis_random.py
357
4.1875
4
import random for i in range(10): x = random.random() print(x) # The function randint takes parameters low and high and # returns an integer between low and high (including both). for i in range(10): x = random.randint(5, 10) print(x) # To choose an element from a sequence at random, you can use choice: t = [1,...
a267b6fb8d293151aa421d43a75c68624b35fabb
gauravvjn/Python-DSA
/sort/quick_sort.py
1,243
4.0625
4
""" Sort the array using quick sort algorithm >>> mylist = [17, 87, 62, 55, 42, 42, 5, 37, 50, 88] >>> quick_sort(mylist) >>> mylist [5, 17, 37, 42, 42, 50, 55, 62, 87, 88] >>> """ def partition(alist, start, end): """ This function assumes last element as pivot, places all smaller (smaller than pivot) to ...
6f9f46afb188adacacb690de492a03479557ef20
HugoGustavo/Criptografia-Python
/vignere-cipher.py
1,467
3.65625
4
import pyperclip LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def encrypt_message(key, message): return translated_message(key, message, 'encrypt') def decrypt_message(key, message): return translated_message(key, message, 'decrypt') def translated_message(key, message, mode): translated = [] key_index = ...
c6f0b086e958184221c287b1e35ed35a6c460173
bsdharshini/Python-exercise
/assignment one.py
2,537
3.796875
4
"""GCD of 2 numbers""" n1=int(input("number 1: ")) n2=int(input("number 2: ")) i=1 while(i<=n1 and i<=n2): if(n1%i==0 and n2%i==0): gcd=i i=i+1 print("GCD of {} and {} is".format(n1,n2),gcd) """prime number u=10 l=2 print("Prime") for i in range(l,u+1): if i>1: for j in ...
d1dd5f67c25acfa3ee4e4ce68cbb0fe49669bf66
jayfallon/python-the-jay-way
/ex4.py
841
4.09375
4
# assigns cars the value of 100 cars = 100 # number of spaces per car space_in_a_car = 4.0 # number of drivers drivers = 30 # number of passengers passengers = 90 # calculates numbers of cars that don't have drivers cars_not_driven = cars - drivers # calculates number of cars that have drivers cars_driven = drivers # c...
ca34decec4aa90b6ad8272e70f725da718b79efd
MrHamdulay/csc3-capstone
/examples/data/Assignment_2/mbmthe007/question1.py
233
4.125
4
x=eval(input("Enter a year:\n")) if x<=0: print(x,end=' ') print("is not a leap year.\n",end='') elif x%400==0 or x%4==0 and x%100!=0: print(x,"is a leap year.") else: print(x,"is not a leap year.")
77ebf4617d03cb1821e1ed22f10a2d0d8174d3af
develmusa/PyQt5-MVC-Template
/tests/test_app.py
903
4.1875
4
import unittest from src import app # With unittest, tests are grouped as methods of classes. # Each such class must be a sub-class of 'unittest.TestCase'. # And that's about all you need to know about these classes! class TestHelloWorld(unittest.TestCase): """Tests for the hello_world() function""" # Eac...
9b2c05c086b16d42697a6abfe2540df1beff52a1
ahill-shopatron/shebang
/col-quotes.py
415
3.546875
4
#!/usr/bin/env python # Consumes a newline-separated list on standard input, spitting it back out on # standard output with each line surrounded by single quotes. # # Useful if you've got a column from a spreadsheet in the paste buffer, and need # to quote it for some reason. from sys import stdin def quote(s): if ...
79c1fb44fe0ba1228ab7e906577ff6a1d9250715
fabianobati/Meu-Primeiro-Repositorio
/calc.py
207
3.859375
4
#!/usr/bin/python3 num1 = int(input('Digite o primeiro Numero ')) num2 = int(input('Digite o segudo Numero ')) operador= input('Qual operacao deseja fazer ') print (eval(f'{num1} {operador} {num2}))
19bb21d98fc4865e6d97038a398770d81e6dbb4f
215836017/LearningPython
/code/009_string_case.py
821
4.0625
4
print('字符串内建函数') ''' 1. 字符串的大小写 ''' message = 'today is Sunday' msg = message.capitalize() # 将字符串的第一个字符转为大写 print('message.capitalize = ', msg) msg = message.title() # 将字符串中每个单词的首字母大写 print('message.title = ', msg) print('message.istitle = ', message.istitle()) print('msg.istitle = ', msg.istitle()) msg = message...
12ada0203b4602a1226e8b93c39ed7de14054bc8
ijpq/CMU15213
/attacklab/rec_attack/rec5/inputs/hex2raw
2,819
4.59375
5
#!/usr/bin/env python3 """ This program converts hex-encoded bytes into raw bytes, or "binary form". For example, the character "a" is represented in ASCII by 0x61, so in order to output that raw byte, you would provide the input "61" to this program. This program provides the same functionality as "xxd -r -p", but ...
8d5da44fb3d4d4c1b35c3aa9384779e126784948
crycket/hyperskill_projects
/Rock-Paper-Scissors/task/rps/game.py
1,569
3.921875
4
import random def get_rating(): name = input('Enter your name:') print(f'Hello, {name}') with open('rating.txt', 'r') as f: for line in f.readlines(): if name in line: return int(line.split()[1]) else: return 0 def get_win_dict(options): win_di...
96324cdc8ccaabc3aa7e7bddabaaa280e9d20945
deadline1314/Python-SelfLearning
/Python3 Tutorial/7. if state.py
151
4.125
4
x = 5 y = 8 z = 5 a = 3 if z < y > z > a: print('y is bigger than z and x, z is bigger than a') if z <= x: print('z is less and equal to x')
97b52716c4dc6ebedfdae36e454a7219732a4a59
ArtemAkulov/CodinGame
/Community Puzzles/divide_the_factorial.py
2,878
3.578125
4
################################### # # # CodinGame Community Puzzles # # Divide the Factorial # # # ################################### a, b = [int(i) for i in input().split()] def erathosphenes(upper_limit): primes_to_limit = [] ...
32b9bdf34dc9489d36253ac5077efd17e9a863ee
bpbirch/scraping_NBA
/src.py
11,328
3.578125
4
""" The following code allows us to crawl basketball-reference.com and scrape data pertaining to team and/or individual player data, for a specified year range. """ #%% import pandas as pd import random import numpy as np import re from urllib.request import urlopen from bs4 import BeautifulSoup, NavigableString, T...
8955760c5850aa005023c76c0c6db1d563620fa2
aryanchordia/LeetCode-Questions
/reverse-integer.py
494
3.5
4
class Solution:    def reverse(self, x: int) -> int:        if -10 < x < 10:            return x        if x > 0:            s = str(x)            r = int(s[::-1])            if r < pow(-2,31) or r > pow(2,31) - 1:                return 0            return r        x = -x        s = str(x)        r = int(s[...
e3c12bae6c29a237d0ff4eb4badda1ef82dcf91e
monadyn/monadyn.github.io
/Code/2Pnt-Leetcode0350-两个数组交集.py
766
3.671875
4
import collections def solution1(nums1, nums2): print(collections.Counter(nums1)) print(collections.Counter(nums2)) print(collections.Counter(nums1) & collections.Counter(nums2)) return list((collections.Counter(nums1) & collections.Counter(nums2)).elements()) def solution(nums1, nums2): res = [...
074a85a2748a19eba2f28b4913d708db78b5a310
Miss-tian/Study
/python/python文件/Area.py
151
3.78125
4
R=int(input("请输入一个半径:")) Area=3.14*R*R Circle=2*3.14*R print("半径为",R,"的圆的面积为Area:",Area,"圆的周长是:",Circle)
cefa0ab456e34760172908d493ed79050f2a3109
caioandre15/CursoEmvideo-Python
/ex024.py
121
3.9375
4
cidade = str(input('Digite o nome de uma cidade: ').strip()) cidade = cidade.split() print('SANTO' in cidade[0].upper())
09b168a6d01674780e07d068a42a039ae7c3fd11
chrisjdavie/compsci_basics
/dynamic_programming/pick_from_top_or_bottom/recursive.py
1,073
3.671875
4
import unittest from parameterized import parameterized class Test(unittest.TestCase): @parameterized.expand([ ("provided example 0", [5, 3, 7, 10], 15), ("provided example 1", [8, 15, 3, 7], 22), ("one number", [1], 1), ("two numbers highest", [1, 2], 2), ("three numbers",...
a0c3da7e4616c2d72716ea9a92bd38b2b9576baf
prinathaker/python-challenge
/PyBank/main.py
1,943
3.546875
4
import os import csv # dictionary for greatest increase and decrease great_inc = {"month": "", "value":0} great_dec = {"month": "", "value" : 0} #lists for various calculations monthly_change = [] month_count = [] profit = [] chg_profit = [] # specify input file name and path currt_dir = os.getcwd() read_path = './R...
8e7eba9b310a7f4670a035388f549f2912338167
frapez1/Algorithmic-Methods-of-Data-Mining
/HW-3/exercise_4.py
1,368
4.15625
4
############ # This is the part for the theorical question: # You are given a string, s. Let's define a subsequence as the subset of characters # that respects the order we find them in s. For instance, a subsequence of "DATAMINING" # is "TMNN". Your goal is to define and implement an algorithm that finds the length ...
7e0ea34d34c2bde9def4bde2724eb0a9b0be2859
vinitjha1993/Python-programme
/python_simple_programme/Algorithm/Anagram_1.py
839
4.21875
4
def insertion_sort_str(list): # insertion_sort_int() for i in range(1, len(list)): item = list[i] j = i - 1 while j >= 0 and list[j] > item: list[j + 1] = list[j] j = j - 1 list[j + 1] = item return list str=input("enter 1st string") str2=in...
5cc1614f04b817982a58d9a84e2d4bdb45f2b822
lekuid/Practice
/weird2.py
314
3.90625
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 29 23:17:12 2020 @author: Lekuid """ num = int(input()) if num % 2 == 0 and num in range(2, 5): print ("Not Weird") elif num % 2 == 0 and num in range(6, 20): print ("Weird") elif num % 2 == 0 and num > 20: print ("Not Weird") else: print("Weird")
4337d05a72684cdfc0bdef255ccfcce72d5f6432
ridhamaditi/tops
/Assignments/Module(1)-modules/I2.py
188
4.375
4
# Aim: Write a Python program to convert degree to radian. pi=22/7 try: degree = float(input("Input degrees: ")) radian = degree*(pi/180) print(radian) except: print("Invalid input.")
8fc55f72b199d29fe32ab0b99c6b95b362ee6a40
Wahid259/Anisu-lslam
/AnisulIslamPython/PythonCode/series 2.py
239
3.734375
4
# 2 + 4 + 6 ......... + n n = int(input("Enter the lase number : ")) sum = 0 for x in range(2, n+1, 2): # 2 thekay suru hobe (n+1) deaci karon na delay n er agar value porjonto nebay, 2 babadhan deay cholbe sum = sum + x print(sum)
4e7bd907db2e3f67944e453014595ff773535531
joaootavio-gc/Computacao-Inspirada-pela-Natureza-Algoritmos-Geneticos
/venv/Algoritmos determinísticos/Recozimento_Simulado.py
1,320
3.515625
4
import random from math import sin, pi, exp def recozimentoSimulado(maximoIteracoes): T = 10 x = inicializar() t = 1 ultimasSolucoes = [] while t < maximoIteracoes and not(convergiu(ultimasSolucoes)): xl = perturbar(x) if avaliar(xl) > avaliar(x): x = xl ulti...
e4aed6869177ec4162aa718ff0a51e7cdf21ba6e
pramodsmurthy/practicepython
/OnlineExamples/beginner/evendivisor.py
224
4.0625
4
""" Prints all the divisors of user's input. """ num = int( input ("Enter the number: ") ) num2 = (int(num/2))+1 print(num2) numlist = range(1, num2) divisors = [n for n in numlist if num % n == 0 ] print(divisors)
225e09b90298be1b820e40634bbb11c5697c482c
lishulongVI/leetcode
/python3/79.Word Search(单词搜索).py
2,472
3.796875
4
""" <p>Given a 2D board and a word, find if the word exists in the grid.</p> <p>The word can be constructed from letters of sequentially adjacent cell, where &quot;adjacent&quot; cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.</p> <p><strong>Example:</stron...
00578f1ead089a80e43c6c9b07d3a70bbc19259b
yasmineElnadi/python-introductory-course
/Assignment 2/2.3.py
164
4.09375
4
#convert feet into meter feet = float(input("Enter a value for feet:")) meter = feet * 0.305 print(format(feet,".2f"), "feet is", format(meter, ".4f"), "meters")
30c95de8762ba700bcca2225883709f2e4ddb4be
AlexRuadev/python-bootcamp
/14 - Advanced Python Modules/timing_code.py
567
3.625
4
def func_one(n): return [str(num) for num in range(n)] print(func_one(10)) def func_two(n): return list(map(str,range(n))) print(func_two(10)) import time # Current time before code start_time = time.time() # running code result = func_two(1000000) # Current time after code end_time = time.time() # Elap...
0b0230124b2f7dd3d2cb06a6ff44e380a7f1458e
github-solar/pyworks-eduwill
/ch09_re/py12_re_compile3_findall.py
336
4.0625
4
#12일이론 #정규표현식 import re str = "Two is too." f1 = re.findall("T[ow]o", str) # findall() 은 대소문자를 구별한다. print(f1) f2 = re.findall("T[ow]o", str, re.IGNORECASE) #findall() 에서 대소문자 구별하지 않도록 옵션 설정 print(f2) f3 = re.findall("t[^w]o", str, re.IGNORECASE) print(f3)
431a5410ac3b76d05bed67878a8b617be0fc6df7
TroyTianzhengWang/alphago0
/mcts.py
1,207
3.609375
4
class MCTS(): """Perform MCTS with a large number of simluations to determine the next move policy for a given board """ def __init__(self, board, simluation_number = 1000): """Initialize the MCTS instance Args: simluation_number: number of simluations in MCTS before calculat...
b55b159cc113ad741d164e203bb41e7cd7b05b63
VaibhaviMandavia/pythoncodes
/db_query.py
407
4.0625
4
import sqlite3 # create a connection to access database conn = sqlite3.connect('mytodos.db') # declare a cursor c = conn.cursor() # command to select todos that are to be displayed c.execute("SELECT rowid,todo FROM todos") # fetchall() fetches all the rows from the last executed statement todos = c.fetchall() print(to...
c78b6d90db9aa1ea733040bbc80092a6d9f786cb
TimTheFiend/Python-Tricks
/pyFiles/4.5_abstract_base_classes_keep_inheritance_in_check.py
617
4.0625
4
from abc import ABCMeta, abstractmethod # Abstract Base Class (ABC) class Base(metaclass=ABCMeta): @abstractmethod def foo(self): pass @abstractmethod def bar(self): pass class Concrete(Base): def foo(self): return 'foo() called' concrete = Concrete() # Output: TypeError:...
beb48323b3e14c9bdc4304ba4f8b09a3b506b358
Vincent105/python
/01_Python_Crash_Course/0401_operate_the_list/040101_go.py
596
3.515625
4
# for循環,從列表magicians中取出一个名字,并将其存储在變數magician。 magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician) # for循環,每個縮排的代碼行都是循環的一部份,且將針對列表中每個數值都執行一次。 for magician in magicians: #for循環後需要冒號: print(magician.title() + ", that was a great trick!") print("I can't wait to see your next tricks,"...
392d916b394ec75c68681b82c7014fe85007e76a
abiassantana/KNN-loja-de-roupas
/projeto_IA.py
2,699
4.09375
4
import csv from math import sqrt #Recebe uma string e carrega o arquivo com este nome def carregar_arquivo(nome_do_arquivo): return open(nome_do_arquivo, 'r').readlines() #Gera uma lista com sublistas que representam uma posição em um plano cartesiano def treinamento(dados): plano = [] for i in range(1,l...
4ca04ef8e8296d07cade0d433146e5df2bcc63c4
nhzaci/LeetCode
/two-sum.py
1,466
3.78125
4
class Solution: def twoSum(self, nums, target: int): ''' Use a hashtable storing an array of indices with keys being the value of item in nums If there are more than one key in the array, use the key that is not equal to the current index Time complexity: O(n) ''' # i...
33fd97fec9ef2a4f7b1c644c89c281e373e8970f
AllanXu00/SHORTS-GENERATOR
/Basic Conversions(Number Systems).py
331
3.84375
4
#Given a number and a base convert it into base 2, 8, 10, 16 import random as r print "Convert the following numbers into bases 2, 8, 10, and 16: " for j in range (20): lim = r.randint(2, 10) leng = r.randint (2, 10) b = "" for i in range (leng): a = r.randint(0, lim-1) c = str(a) b += c print b, "( base", ...
efe015bd806c1c219f339033057d1551f111943b
L1ves/pythonNaPrimere
/strings_post_index.py
389
3.84375
4
#strings_post_index.py """ Предложите пользователю ввести его почтовый индекс. Выведите первые две буквы слова в верхнем регистре 1 . """ postAdress = input("Введите почтовый адрес: ") start = postAdress[0:2] print(start.upper()) #print(postAdress[0:2].upper()+""+ postAdress[2:])
0722246782f61b4bfd52d6272d444cb2ab166f2c
merileewheelock/algorithms-practice
/big-oh/bigo-examples.py
1,489
4.28125
4
# BIG O EXAMPLES # 0(1) # Means the side of the date set is irrelevent. The number of steps/space required to execute code will remain constant. def first_element(the_list): return the_list[0]; a_list = [1,2,3,4,4,3,53,7,435,47,365,] b_list = [1]; b_list = range(1,100000000); # Only one step is requred, no matter ...
5515c5b432d40937ecc787dc88b72b19d5346c49
leandro-alvesc/estudos_python
/guppe/loop/breaks.py
358
3.765625
4
""" Saindo de loops com break Funciona da mesma forma que em C e Java - Sair de loops de maneira projetada # Exemplo 1 for numero in range(1,11): if numero == 6: break else: print(numero) print('Saí do loop') """ # Exemplo 2 while True: comando = input("Digite 'sair' para sair: ") ...
677eeeaa1b1c34d9bed9f3c23286b0e3b0aa7724
savfod/d16
/common/permutation.py
575
3.625
4
class Permutation: def __init__(self,A): self.A=A def f(self,n): return self.A[n-1] def __str__(self): return (str(self.A)) def __len__(self): return len(self.A) def __mul__(X,Y): A=[] for i in range(1,len(X)+1): A.append(X.f(Y.f(i))) return Permutation(A) def __pow__(X,n): if n==1: return X...
ddf58e8558d7d37a65ceeb06608bbbf5a12054de
Azure-Whale/Kazuo-Leetcode
/Company/Guidewire/429. N-ary Tree Level Order Traversal.py
1,254
4.0625
4
n_tree = [0,1,2,3,4,5,6] """ N-ary Tree means a tree has no more N children for a single root/parent , binary tree is 2-ary Tree Given an n-ary tree, return the level order traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated ...
3e76f3ac969b8316dd99ddccb24c5f4114113219
abhisheksaini129/python
/primecheck.py
220
4.125
4
x=int(input("enter the number")) y=int(x/2) for a in range(2,y+1): if (x%a==0) : print("%d is not a prime number"%x) break if (x <=1) : print("%d is not a prime number"%x) else: print("%d is a prime number"%x)
5323e4a53b3346ba48f4fdcce9ffeaa6cfb95066
Ellie1994/Easy_Games
/paper_scissors_rock.py
1,192
3.953125
4
import random import time player_1 = input("The first player enters a number of tosses: ") player_2 = input("The second player enters a number of tosses: ") tosses = ["toss..","toss..","toss.."] for t in tosses: print(t) time.sleep(1) variants = ["scissors", "paper", "rock"] player_1 = random.choice...
2f992680b0b7191caaaee194e0f1dfcfded043f9
Hieumoon/C4E_Homework
/Session03/While_sample.py
658
3.8125
4
# while True: # print('hi') # while False: # print('hi') # for v in range(10): # print("Hi", v) # dem = 0 # while True: # print('hi', dem) # dem += 1 # dem = dem + 1 # if dem >= 10: # break # print('end') # mat_khau = input('Moi ban nhap pass:') # while True: # Lenh nhap cu lap lai ...
6755fea3da7304af6dfa09eb323e6656a7f4f636
pavstar619/HackerRank
/Algorithms/Implementation/ViralAdvertising.py
363
3.71875
4
class Main: def __init__(self): self.n = int(input()) self.li = [2] def calculate(self): for i in range(self.n - 1): self.li.append(3 * self.li[i] // 2) return sum(self.li) def output(self): print(self.calculate()) if __name__ == '__...
6157ad88a11325e46d4d7e47c6d4239afa41eb93
LouiseSimeonov/MadMathsQuiz
/draft.py
725
4
4
import random import operator #for x in range(1): #print random.randint(1,101) symbol = ['+', '-', '*', '/'] opstype = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.div} num1 = random.randint(0,12) num2 = random.randint(0,10) operation = random.choice(symbol) print(num1) print(num2) print...
bb1798977a24dd1feccb725d1ccf6e2a1a9b5e73
Bytewaiser/Bioinformatics
/3. complementing_a_strand_of_dna/main.py
255
4.0625
4
def reverse_complement(string): string = string[::-1] d = {"A": "T", "T": "A", "C": "G", "G": "C"} return "".join(list(map(lambda x: d[x],string))) with open("data.txt", "r") as f: string = f.read()[:-1] print(reverse_complement(string))
d41b2b9f8891366c2e97ece752ab5ded356fa6ef
kgroenke/sorting_algorithms
/quick_sort.py
606
3.578125
4
def quickSort(ar): def partition(pivot, eidx): if pivot == eidx: return else: lSidx = pivot for idx in range(pivot+1, eidx): if ar[idx] < ar[pivot]: temp = ar[idx] ar[idx] = ar[pivot+1] a...
e67a6d0a455d897310ba09edc0e77a7984357bf0
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_34/558.py
1,878
3.5
4
hits = 0 class SearchTreeNode: def __init__(self): self.children = {} self.letters = set() self.hits = 0 def add_word(self, word): letter, tail = word[0], word[1:] if letter not in self.children: self.children[letter] = SearchTreeNode() self.lett...
ef6daf28af421dda3170fd36cf3d0f488199895b
Fischer-L/Puzzles
/MagicDictionary/solution.py
1,318
3.921875
4
import re class MagicDictionary: def __init__(self): """ Initialize your data structure here. """ self.countMap = {} def buildDict(self, dict): """ Build a dictionary through a list of words :type dict: List[str] :rtype: void ""...
3d70772ac2e404016ed154d92dac34bdfff6bd2d
rohinizade27/Program
/PycharmProjects/pythonprograms/StringReplace.py
282
4.34375
4
template = "hello <<username>>!! how are you?" print(template) username = str(input("Enter the user name:")) if len(username) > 3: result = str(template.replace("<<username>>", username)) print(result) else: print("please ensure you have entered string greater 3 char")
979a4b4bf63712ccfbc9dd7dd80586dc37ef1e96
wan-catherine/Leetcode
/problems/N529_Minesweeper.py
1,397
3.609375
4
class Solution(object): def updateBoard(self, board, click): """ :type board: List[List[str]] :type click: List[int] :rtype: List[List[str]] """ if board[click[0]][click[1]] == 'M': board[click[0]][click[1]] = 'X' return board rows, co...
408229e40414bae69fe1ec36764c0630365e15f0
ZahraAhmed1/qa-python-assessment-2
/questions/__init__.py
1,647
3.828125
4
# def two(number): # prime = True # if number < 1: # prime = False # if number > 1: # for i in range (2, number): # if number % i == 0: # prime = False # return prime # print( two(3)) # print (two(16)) # print( two(19)) # def three(a): # return (a*1111...
15339642a72d39998eaaf5a8681bc7ef02668201
jdh2358/py4science
/examples/skel/distributions_skel.py
2,992
3.90625
4
""" Illustrate the connections bettwen the uniform, exponential, gamma and normal distributions by simulating waiting times from a radioactive source using the random number generator. Verify the numerical results by plotting the analytical density functions from scipy.stats """ import numpy import scipy.stats from py...
e7b3cafaba864fe65888c8aad83ca1d01653bb02
davidthomas5412/gravitysimulator
/simulate.py
16,305
3.8125
4
from random import randint from pygame import display, draw, event, quit, QUIT, KEYDOWN from math import sqrt, pi, pow from itertools import combinations from sys import exit import jsonpickle as json ################################### ### ### State Classes ### ################################### class Universe(obje...
a98b3a4192118e6d798a9cd964ff9d9a1fe52f77
pkdism/leetcode
/30-day-leetcoding-challenge/d17-number-of-islands.py
944
3.75
4
""" Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. """ class Solution: def numIslands(self, grid: List...
0e0f2fb08f9dbf4130248c71dc90828256c8c49d
nathanrod98/TrabalhoPython
/aula5/cadastromercado.py
278
4.09375
4
produto = input('digite o nome do produto: ') categoria = int(input('digite a categoria do produto: 1- Alcoolico 2- Não Alcoolico')) if categoria == 1: print(f'\nProduto: {produto}\nCategoria: Alcoolico') else: print(f'\nProduto: {produto}\nCategoria: Não Alcoolico')
8214ea6858069fa6aebd51ec6cbdaed8f01ff8e1
ReynoK/LeetCode
/List/2_Add_Two_Numbers.py
4,018
3.875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'reyno' import itertools # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None #class Solution(object): # def addTwoNumbers(self, l1, l2): # """ # :type l1: ListNo...
8cffc7217b6d214dd4614fcc1981290b09d25a81
kmakeev/puzzle
/utils/turple_repl.py
407
3.5625
4
""" Замена элемента в кортеже Вход: t - исходный кортеж new_el - элемент для вставки в кортеж pos - позиция для вставки Выход: Кортеж со вставленным элементом """ def turple_repl(new_el, pos, t): assert isinstance(t, tuple) pos = int(pos) return (t[:pos]+(new_el,)+t[pos+1:])
3b7f146ff4a7d590622ec7b6737358a69987fcaa
mrthawee/training
/python/ThinkingWithPython/singly_linked_list.py
1,767
3.921875
4
# ADT: insert and delete class Node: # constructor def __init__(self): self.data = None self.next = None def __init__(self, data=None, next=None): self.data = data self.next = next def setData(self, data): self.data = data def getData(self): return ...
67e16ffa21acce41796e06ea32907c4bd64a43a1
Dgonzalez44/Ejercicosciclo
/Ejercicio7.py
273
3.71875
4
def precio(): cantidad=0 valor=0 Cantidad = int(input("Ingrese la cantidad que va a comprar del articulo")) for i in range(Cantidad): Precio = int(input("Ingrese el valor del articulo tomado")) Total = Precio * Cantidad print(f"el precio total es ${Total}")
6851db99a848b709aca4c6321f28f54b32ebfacd
rajkiran485/Coding-Problem-Solutions
/breadth_first_search.py
1,116
3.984375
4
#!/bin/env python from collections import defaultdict, deque class Graph(): def __init__(self, v): self.graph = defaultdict(set) self.v = v def addEdge(self, u, v): self.graph[u].add(v) def BFS(self, src): """ Performs breadth first traversal for directed unweight...
46ff0a888a7403332c317724e515375147fd1a66
strawhatasif/python
/exception_palooza.py
1,031
4.4375
4
# Handling and throwing various exceptions. A party, indeed! def divide_by_zero(): number = 100 / 0 # Can't divide by zero. This handles that error try: divide_by_zero() except ZeroDivisionError as error: print('Cannot divide by zero...handling this exception: ', error) # If someone doesn't enter an ...
8795f42a1be74f6af05b1d5563d403cb20cc64d1
mxmoca/python
/demo_spiral.py
448
3.765625
4
import turtle def draw_spiral0(t, length): min_length = 5 while length > min_length: t.fd(length) t.rt(90) length-= min_length def draw_spiral(t, length): min_length = 5 if length > min_length: t.fd(length) t.rt(90) draw_spiral(t, length - min_lengt...
2fbea152d98c3646525d235474e52424c0c65430
davetheflashguy/py-code-school
/lists.py
651
4.21875
4
# an empty list empty = [] print(empty) # list of string str = ['Dave', 'Angela', 'Chloe', 'Charlotte'] print(str) # list of number nums = [36, 34, 6, 3] print(nums) # list of mixed item mixed = ['Dave', 20, 'hello', 1.765] print(mixed) # indices and slicing greetings = ['aloh', 'hello', 'hola'] print(greetings[0])...
fc9a0d9467a2603acd745e8c6a86509ebf41bdf6
mxor111/Animal-Trading-Cards
/rock paper scissor starter code.py
3,301
4.625
5
#!usr/bin/env python3 """This program plays a game of Rock, Paper, Scirssors between two Players, and reports both Player's score each round.""" moves = ['rock', 'paper', 'scissors'] """The player class is the parent classt for all the Players in this game""" class Player: def move(self): return 'rock' ...
15aa4a072ad204667058d33e4683adde239c730a
kksgandhi/comp-130
/text_generation.py
5,667
3.75
4
""" This project contains functions used to turn a dictionary of markhov instructions into a markhov chain string It contains functions that develop the string in different ways for testing purposes """ import re import random # from sets import Set def pick_key_random(keys): """Returns a random one of the given ...
664355f00ad9ecc57c7714ae13b67a3356f07485
ketulsuthar/Leetcode
/476.py
1,419
3.84375
4
''' 476. Number Complement Easy 685 76 Add to List Share Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. Example 1: Input: 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement ...
7e0bd914def56777cd8cebc6531a5bf0910dcdad
really-that-lazy/cs116
/assignments/2/a02q4.py
486
3.921875
4
## Question 4 import check ## remainder takes two integers a & b, & returns the equivalent of a%b, the ## remainder of a/b ## remainder: Int Int -> Int ## ie remainder(5, 2) => 1 def remainder(a,b): if(a == b): return 0 elif(a < b): return a else: return remainder(a-b, b) if(__name__ == "__main__"): ...
ae2ef2ab21843c2a15556e458e6cbbc11097712d
mqueiroz1995/algorithms
/data_structures/src/Heap.py
3,130
4.15625
4
''' Heap (aka PriorityQueue): In a Heap, for any given node C, if P is a parent node of C, then the key (the value) of P has a priority greater than or equal to the priority of C. The node at the "top" of the heap (with no parents) is the node with biggest priority and is called th...
136e827585fca620bfbb3e954973b55bfb815fce
th3fall3n0n3/my_first_calc_extended
/modules/calc250_250.py
857,617
3.53125
4
def calc(num1, sign, num2): if num1 == 250 and sign == '+' and num2 == 250: print('250+250 = 500') if num1 == 250 and sign == '+' and num2 == 251: print('250+251 = 501') if num1 == 250 and sign == '+' and num2 == 252: print('250+252 = 502') if num1 == 250 and sign == '+' and num2...
036b77aaad95033adbcb0a775ec85aaa370b419b
singham3/python-programs
/test tkinter-.py
439
3.734375
4
from tkinter import * import time counter=0 def counter_label(): counter=0 def count(): global counter counter += 1 label.config(text=time.ctime()) label.after(1000,count) count() root = Tk() root.title("counting Seconds") label=Label(root, fg="dark green") label.pack() coun...
b1be99edac6e83d86b08dfd48fe65c7d0e7c18de
gargi98/Introduction-Programming-Python
/number variable/intFormat.py
192
3.75
4
#print integer number either using %d luckyNumber=54 print("My lucky number is %d" %luckyNumber) #or using "{0:d}".format(luckyNumber) print("My lucky number is {0:d}".format(luckyNumber))
ccaea07f7fb0db1c0ef6f64b94625a7d259f05a8
WeijieH/ProjectEuler
/PythonScripts/Pandigital multiples.py
1,194
4.09375
4
''' Take the number 192 and multiply it by each of 1, 2, and 3: 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4,...
162f03edae6ae17006792a533acc87e752e18144
ALMTC/Logica-de-programacao
/Python/18.py
97
3.6875
4
print 'Temperatura em Fahrenheit' f=input() c=(f-32)*(5/9.0) print str(c) + 'graus ceucios'
bbdc2d9cf24737a43a5dff4faebc6e603c645034
operation-lakshya/BackToPython
/MyOldCode-2008/JavaBat(now codingbat)/Array2/sum67.py
485
3.546875
4
from array import array a=array('i') sum,j=0,0 n=int(raw_input("enter length of array")) for i in range(n): a.append(input("enter values in array")) while (j<n): if a[j]==6: if 7 in a[j:]: while (a[j]!=7): sum=sum j+=1 j+=...
e96d2d86da017eab89716437bc16e05cb2ee963c
mdhatmaker/Misc-python
/interview-prep/techie_delight/array/find_duplicate.py
968
3.703125
4
import sys # http://www.techiedelight.com/find-duplicate-element-limited-range-array/ # Given a limited range array of size n where array contains elements in # range 1 to n-1 with one element repeating, find duplicate number. # using xor :: O(n) O(1) space def find_duplicate(arr): print(arr) xor = 0 fo...
71d6c005a095aaf04455ab43c176266881210657
vishalsingh8989/karumanchi_algo_solutions_python
/Dynamic Programming/cutrod.py
1,304
4
4
""" Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then the maximum ...
a5178d4d5747430cddf35b0499aeefbce8eba921
rafaelperazzo/programacao-web
/moodledata/vpl_data/10/usersdata/137/10428/submittedfiles/testes.py
307
3.65625
4
# -*- coding: utf-8 -*- from __future__ import division import math a=input('a:') b=input('b:') c=input('c:') d=input('d:') maior=a menor=a if menor>b: menor=b if menor>c: menor=b if menor>d: menor=d if maior<b: maior=b if maior<c: maior=c if maior<d: maior=d print menor print maior
658badea02c44b1f533b791a645143a238a5f7c6
mattfrankjames/ms-software-development
/intro-to-programming/final-project/adventure-game.py
4,982
3.75
4
from random import * class Character: def __init__(self, name): self.name = name self.horcruxes = [] self.lifePoints = 100 def attack(self, enemy): damage = randrange(1, 10) enemy.lifePoints = enemy.lifePoints - damage def collect(self, horcrux): # Check to s...
aa62465c09609c7ea4de042512e10b9dbad22539
Peppone-Zuo/tempcode
/temp.py
237
3.515625
4
str = "ab" dic = {"a":1, "b":2, "c":3, "d":4} def position(str): res = 0 length = len(str) for index, s in enumerate(str[::-1]): res += dic[s] * (4 ** (length - 1 -index)) return res print position("ababacd")
9f5bed1a042d1b9d1e674abc3ab98f8c90167e5a
sherlockloveming/Python_Practice
/sorting_algorithm_practice.py
447
3.5625
4
#Selection Sort c=[5,9,3,6,10,4,2,25,15,1] for j in range(0,len(c)-1): smallest=j minvalue=c[smallest] for i in range(j+1,len(c)): if c[i]<minvalue: smallest=i minvalue=c[smallest] c[j],c[smallest]=s[smallest],c[j] #=================================================# #Insertion Sort a=[4,1,...