blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a9caabb7d64a398881bbc8c2d25fb8413ac8e1ef
AnoopMasterCoder/python-course-docs
/10. Chapter 10/03_classattributes.py
559
4.09375
4
# A very basic sample class class Employee: name = "Harry" # A class attribute marks = 34 center = "Delhi" def printObj(self): print(f"The name is {self.name}") @staticmethod def greet(): print("good day") Employee.name = "HarryNew" # Setting a class attribute for Employe...
1ccd710129f3409d35ad493e4cecb3271daffb7d
n-ramadan/assignment-aug-2020
/question1.py
600
3.546875
4
# Split a file which has n number of schema def. And store them in a dict of lists(no 3rd party imports) # File to read: to_read.txt / question1_text.txt #Set first field value as dictionary key dic1 = {} with open("question1_text.txt", "r") as file: for line in file: line_split = line.split(',') ...
206f6b89072b98935e7076fc1e1d0c1493c6930f
svoges/hw8
/parks_path.py
682
3.515625
4
def algorithm(G, l, k): dist = [m][m] seen = {m} for each vertex v in V: dist[v][v] = 0 #distance from v to v is 0 for each edge (u, v) in l: dist[u][v] = l[u][v] for a = 1...|V|: for b = 1...|V|: for c = 1...|V|: if dist[b][c] > dist[b][a] + dist[...
fb1f7fc1e470e9f0c38cfca9c1f0d8b60a853c86
YogeshSingla/balia
/3_genetic_algorithms/gen_mln.py
2,873
3.78125
4
import numpy as np from matplotlib import pyplot as plt #training set datasetxor = np.array([ [0,0,0], [0,1,1], [1,0,1], [1,1,0], ]); def sigmoid(val): res = 1/(1+np.exp(-val)); return res; def predict_xor(row, w): activation = w[0];#for bias for i in range(len(ro...
3d61c23cf750a552bae4770d67e8f12f587b43b4
green-fox-academy/Angela93-Shi
/week-03/day-01/paperback_book.py
821
3.640625
4
# It should have the following fields: title, author, release year, page number and weight. # The weight must be calculated from the number of pages (every page weighs 10 grams) plus the weight of the cover which is 20 grams. # It must have a method that returns a string which contains the following information about t...
41919dbd3918fdc77ba9d0dde91f941e96154225
RusyaDeWitt/ICT
/task_1/10.py
235
3.734375
4
import math a = int(input()) b = int(input()) print("Sum is",a+b) print("Difference is",a-b) print("Product is",a*b) print("Quotient is",a//b) print("Remainder is",a%b) print("A log10 is",math.log10(a)) print("A power of b is",a**b)
171e248744a609517eea1ec2d7b96400a26bf4c0
Daniyar-Yerbolat/university-projects
/year 2/semester 1/programming languages/labs/question J - Daniyar Nazarbayev [H00204990].py
2,318
4.125
4
# answers to other questions are in .docx file. # Question J #5 def even(n): return [x for x in range(n*2) if x%2==0] # after thinking for a while i realized that after every even number there is # and odd number, and after every odd number there is an even number # and that's how i made the program display firs...
8a0fecb7a60d22e7c10a43e9546caf655808fac4
TheSergiox/introprogramacion
/Quiz/QuizGraficod.py
2,788
3.734375
4
import matplotlib.pyplot as plt #--------Punto 1-------# #---constantes---# Saludo = "Hola profe este es mi quiz 4" Soborno = "profe si gano el quiz nos vamos por unas polas" despetida = "ahi esta su quiz, *se voltea indignado por la dificultad del quiz*" Pregunta_snacks = " Ingrese por favor sus snacks favoritos : " P...
817d51e2dbece1d2028797d5663cc83000a4ee1b
emanoelmlsilva/ExePythonBR
/Exe.Funçao/Fun.09.py
221
3.953125
4
def inverso(n): # n = list(str(n)) # n.reverse() n = str(n) for i in range(len(n),0,-1): print(n[i-1],end='') print() num = int(input("Digite o numero: ")) #print(inverso(num)) print("Inverso",end=' ') inverso(num)
baecbd435f16d0ac63cc6cf409df86dcc2c38ed2
EtoKazuki/python_practice
/ex10.py
663
3.890625
4
year = int(input("年>")) month = int(input("月>")) day = int(input("日>")) weekday = (year + (year // 4) - (year // 100) + (year // 400) + ((13*month+8) // 5) + day) % 7 if weekday == 0: weekday = "日曜日" elif weekday == 1: weekday = "月曜日" elif weekday == 2: weekday = "火曜日" elif weekday == 3: weekday = "水曜日"...
c7dfba2a6b679a92b9f4f4b5c59196ac13d19771
SakuraGo/leetcodepython3
/ZS/ZS158_01.py
1,135
3.859375
4
# 5222. 分割平衡字符串 显示英文描述 我的提交返回竞赛 # 题目难度 Easy # 在一个「平衡字符串」中,'L' 和 'R' 字符的数量是相同的。 # # 给出一个平衡字符串 s,请你将它分割成尽可能多的平衡字符串。 # # 返回可以通过分割得到的平衡字符串的最大数量。 # 输入:s = "RLRRLLRLRL" # 输出:4 # 解释:s 可以分割为 "RL", "RRLL", "RL", "RL", 每个子字符串中都包含相同数量的 'L' 和 'R'。 class Solution: def balancedStringSplit(self, s: str) -> int: lcnt = ...
2a12acb6dd57fb0d0b900657ccd4d3670630fb56
KevinAS28/Python-Training
/solo7.py
414
3.8125
4
#!/usr/bin/python print "penggunaan if" aku = 9 if aku > 7: print("five") if aku < 100: print("buset") print ' ' print 'pake else' kamu = 90 if kamu == 900: print 'pas' else: print 'nga pas' print ' ' print ' ' print "ADVANCED PEMAKAIAN IF DAN ELSE DENGAN CHAIN" masa = 12 if masa == 90: print 'sembilan pu...
8f1eaa9413cc70b8769d07a95d5a4b9788f54d34
katheroine/languagium
/python/scopes/functions_and_scopes.py
438
3.5625
4
#!/usr/bin/python3 # g is in the global namespace g = 5 print(f"{g}\n") def some_function(): # f is in the local function namespace f = 6 # g is readable but not modifiable print(f"{g}, {f}\n") def some_nested_function(): # nf is in the nested local function namespace nf = 7 ...
a983bb72ed6cdd239924a307868159c91d329edd
tpt5cu/python-tutorial
/language/python_27/built_in_types/sequence_/list_/comprehension/performance.py
1,454
3.921875
4
# https://portingguide.readthedocs.io/en/latest/iterators.htmo # https://stackoverflow.com/questions/1247486/list-comprehension-vs-map - gory details import timeit numbers = [1, 2, 3, 4, 5, 6, 7] powers_of_two_map = map(lambda x: 2**x, numbers) powers_of_two_comp = [2**x for x in numbers] ''' The results are surp...
360418d0ae259dbce9f752a7c59814a2606d7c3c
ytreeshan/BeginnerPython
/ShadesofBlue.py
242
3.546875
4
#Name: Treeshan Yeadram #Date: 9/27/18 import turtle turtle.colormode(255) tess = turtle.Turtle() tess.shape("turtle") tess.backward(100) for i in range(0,255,10): tess.forward(10) tess.pensize(i) tess.color(0,0,i)
2a0869b85589c5ad7b883fc51775f84f84f7a0ba
EpicureanHeron/courseraIntroPython
/rps.py
1,726
3.8125
4
# http://www.codeskulptor.org/#user29_iZ09AlcCpR_40.py import random def name_to_number(name): if name == "rock": name_number = 0 return name_number elif name == "Spock": name_number = 1 return name_number elif name == "paper": name_number = 2 return na...
225e0f494add75997fa09e0a1e5c368a26ffbe89
william-schor/e2eLan
/ecdhe.py
3,846
3.703125
4
#!~/.pyvenvs/elliptic_curve # -*- coding: utf-8 -*- """A simple implementation of Diffie Hellman Elliptic Curve Crypto Functions ----------- f(str, int): finds the int in the str and returns the index """ import os import sys import secrets import time # Curve constants secp256k1_P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF...
364e5d94320977aa500266cf1c9acd4817a3e632
sunwenbo/python
/1.面向对象/类/面向对象第一个类.py
2,228
3.890625
4
#__author: Administrator #date: 2019/12/8 ''' 设计类 类名:见名之意,首字母大写,其他遵循驼峰原则 属性:见名之意,其他遵循驼峰原则 行为(方法/功能):见名之意,其他遵循驼峰原则 创建类 类:一种数据类型,本身并不占内存空间,根所学过的number,string,Boolean等类似。 用类创建实例化对象(变量),对象占内存空间 格式: class 类名(父类列表): 属性 行为 ''' # object:基类,超类,所有类的父类 #一般没有合适的父类就写object class Person(object): #...
3a10df1a353c11fd8bb4ef3105b4e844ca462fc1
youngheon/DataStructureExample
/src/com/youngheon/stack/Stack.py
245
3.578125
4
#-*- coding:utf-8-*- __author__ = 'Heon' def Main(): stack=[] # stack 생성 stack.append(1) stack.append(2) stack.append(3) stack.append(4) print stack while stack: print "POP > ", stack.pop() Main()
f8d690a1c2490517b3ff26bf66356eef88208b6e
nababanyogi/python-OOP
/oop2.py
714
3.625
4
#03 - Class dan Instance variables class Hero:#template #class variable jumlah = 0 def __init__(self,inputName,inputHealth, inputPower, inputArmor): # instance variable self.name = inputName self.health = inputHealth self.power = inputPower self.armor = inputA...
e4275a8ed2d35e8de70ecb8c68d51506c0742659
Paprok/Training_Logbook
/log.py
4,395
3.96875
4
# log book - open it when on the gym. PrintOut exercises and get results. import time import datetime import os class LogBook: '''This class work as a diary/log book for user. Workout results can be logged in and saved to file.''' def __init__(self, workout_for_today,): self.workout_for_today = work...
c9e356140d0ae9d0e56ad62da59503cbdaed62a2
LiuFang816/SALSTM_py_data
/python/pfnet_chainer/chainer-master/chainer/functions/activation/maxout.py
1,874
3.703125
4
from chainer.functions.array import reshape from chainer.functions.math import minmax from chainer.utils import type_check def maxout(x, pool_size, axis=1): """Maxout activation function. It accepts an input tensor ``x``, reshapes the ``axis`` dimension (say the size being ``M * pool_size``) into two dim...
ec7835ad3d669c961eed7be9f2f8a057dbfd9488
Mahirkhan3139/python_code_beginners
/list-demo.py
1,135
3.796875
4
list1 = ["A", "B", "C", "D"] print(list1) print(type(list1)) list2 = ["A", "B", 1, 2.0, ["A"], [], list(), True] print(list2) print(type(list2)) print(list2[0]) print(list2[-1]) print(list2[:9]) print(list2[::2]) print(list2[4][0]) print(list2[4][-1]) print(type(str(1+1))) list1[0] = "Y" print(list1) del list1[0] ...
5873a595676623161108971cb893d09d437719e7
Team-BeanCat/Python-Game
/reader.py
1,112
3.703125
4
from os import path from json import load, dump class user(object): #Object for s uer def __init__(self, username): self.file = f".\\saves\\{username}.json" self.read() def read(self): #Read from the user's json file if path.exists(self.file): with open(self....
fcfaa028a7a766f622fc4db2cf084b30e9ffd642
omkar-javadwar/Recognition_Module
/speech<->text/text_to_speech_using_pyttsx3.py
407
3.59375
4
# Import the required module for text to speech conversion import pyttsx3 # init function to get an engine instance for the speech synthesis engine = pyttsx3.init() # Taking input from user. str = input() print(str) # say method on the engine that passing input text to be spoken engine.say(str) ...
6b810fbd255e44b7d0b0f78595f0efd3b3b74e0b
Rahul4269/Python-star
/multilevel inheritance.py
562
3.65625
4
class student: def getstudent(self): self.name=input("name :") self.age=int(input("age :")) class testMarks (student): def getMarks(self): self.english=int(input("English :")) self.Maths=int(input("Maths :")) self.physics=int(input("Physics :")) class resul...
a959e2f4f293ec49d9dfab8487f8a6cc24cd948f
MatiwsxD/ayed-2019-1
/Labinfo_6/punto_3.py
375
3.96875
4
def domino(n): list_1 = [0] * (n + 1) list_2 = [0] * (n + 1) list_1[0] = 1 list_1[1] = 0 list_2[0] = 0 list_2[1] = 1 for i in range(2, n+1): list_1[i] = list_1[i - 2] + 2 * list_2[i - 1] list_2[i] = list_1[i - 1] + list_2[i - 2] return list_1[n] def main...
59b5d2016865f4b96384df2a1a523243ab42a46d
MenonFOSSTest/Python-2
/KM2MILES.py
83
3.953125
4
km=int(input("Enter Kilometer")) m1=0.621371*km print(km,"is equal to",m1,"miles")
83fc2c9673aeb2936fb1827eda08dd1875c7c13e
favera/python-course
/string.py
1,864
4.03125
4
string1 = "Cisco Router" #se puede acceder a los indices de un string, cada caracter representa un indice #el ultimo caracter de puede acceder con -1 #para leer un string del reves se comineza con -1 y va decrenciendo en negativo string1[1] string1[-1] #para saber el lenght de un caracter usar la funcion len len(stri...
ae85144467ed5d9a9ea310e689298a65bf435bb2
chrispewick/advent_of_code_2020
/day01/part_2.py
1,180
4.125
4
from typing import Tuple from utils.performance_utils import get_the_avg_time_to_do_the_thing SUM_GOAL = 2020 def get_numbers_basic(entries) -> Tuple[int, int, int]: for index, x in enumerate(entries): for y in entries[index+1:]: for z in entries[index+2:]: if x + y + z == 20...
b25a878ed7c7a7e6f60c8de1943f6dd6fcb4b74b
allenwhc/Algorithm
/Company/Google/PeakElement.py
610
3.53125
4
class Solution(object): def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums)<=1: return 0 return self.binary_search(nums,0,len(nums)-1) def binary_search(self,nums,s,e): if s<=e: mid=(e-s)/2+s if (mid==0 or nums[mid]>nums[mid-1]) and (mid==len(nums)-1 or nums...
0bc6bac8d0cc73e7dc07eafa0c0cd5930d2c5bfc
MiniBug/Guess-The-Number
/guess_the_number.py
2,059
4.25
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random # initialize global variables used in your code num_range = 100 # helper function to start and restart the game def new_game(): g...
92ea6d9cbb37ae2b7147f164867f813125992ef3
cklat/Particle-Swarm-Optimization
/Code/helper.py
690
3.703125
4
"""reads a tsp file and returns a list of vertices and a dict of edges with their corresponding costs""" def read_tsp(tsp_file): import xmltodict vertices = [] edges = {} with open(tsp_file) as file: data = xmltodict.parse(file.read(), dict_constructor=dict) vertices...
b9c176c51bd6335deffcc68c0c6c13ea797e733e
karimeSalomon/API_Testing_Diplomado
/RolandoMamani/Python/Practice7_SumAllNumbers.py
745
4.1875
4
""" Practice 7: Write a function sum_to(n) that returns the sum of all integer numbers up to and including only until any value lower than 35. So sum_to(10)wouldbe1+2+3...+10which would return the value 55, but if n=40 only until sum to 35 need to be returned. . """ def sum_to(n): ...
d64dd69f6f74792c20a839a15874bc1993a0efdf
BuntyBru/SortingAlgorithms
/mergeSort.py
513
3.796875
4
def mergeSort(alist): if len(alist) >1: mid = len(alist)//2 left = alist[:mid] right = alist[mid:] mergeSort(left) mergeSort(right) i=0 j=0 k=0 while i < len(left) and j < len(right): if left[i]< right[j]: alist[k] = left[i] i=i+1 else: alist[k] = right[j] j=j+1 k=k+1 ...
4c4d7323126348dd3a9a60a966fcfef3d382ca80
nazmosh/data_structures
/CircularLinkedList.py
2,878
3.90625
4
class CircularLinkedList: def __init__(self): self.head = None def append(self, node): if self.head == None: self.head = node self.head.next= self.head else: current_node = self.head while current_node.next != self.head: c...
2880b9e2783cf7214f3048af20c0334b1f341943
VishalGupta2597/batch89
/evenodd1to10.py
189
4
4
n = 6 if n%2==0: print("even=",n) else: print("odd=", n) i=1 while i<11: if i % 2 == 0: #print("even=", i) pass else: print("odd=", i) i=i+1
cbbc7346250217eb7b744e9fa3eafcf15b93596e
etihW/Sandbox
/Reddit/RPS.py
1,356
4.25
4
import time from random import randint def comp_pick(): val = randint(1,3) if val == 1: hand = "rock" elif val == 2: hand = "scissors" elif val == 3: hand = "paper" return hand def compare_hands(comp, you): if comp == you: winner = "tie" elif comp == ('rock...
809ec304ff7203847ebc5bec10c96006cee3f17c
romanticair/python
/basis/tkinter-demo/tk-color-change-and-grow.py
1,026
3.984375
4
""" Build GUI with tkinter with buttons that change color and grow """ import random from tkinter import * FontSize = 25 Colors = ['red', 'green', 'blue', 'yellow', 'orange', 'white', 'cyan', 'purple'] def reply(text): print(text) popup = Toplevel() color = random.choice(Colors) Label(popup, text='Po...
0e413abbc21e5556343d325a8a77411951fe8939
maxim371/Unit3_Sprint2_Database
/northwind_sprint.py
1,164
3.625
4
#!/usr/bin/env python import sqlite3 CONN = sqlite3.connect('northwind_small.sqlite3') def queries(): expensive = 'SELECT * FROM Product ORDER BY UnitPrice DESC LIMIT 10;' avg_age = 'SELECT AVG(HireDate - BirthDate) FROM Employee;' city_age = ('SELECT City, AVG(HireDate - BirthDate) FROM Employee ' ...
a45788a86b28033d9b5e615e57904704a4ef063e
Andrey-Strelets/Python_hw
/Practica_1.py
126
3.890625
4
print ("Insert the number") a = int(input()) if a % 2 == 0: print("Четное") else: print ("Нечетное")
2e7086888642bce52ab736a07e56b7e160fa1c7c
jong1-alt/Lin
/demo61.py
388
4.125
4
def factorial(number): if not isinstance(number, int): raise TypeError("Sorry, number should be integer") if not number >= 0: raise ValueError("sorry, number should positive") def inner_factorial(number): if number <= 1: return 1 return number * inner_factorial(n...
e6c7b82359d241fc68f2690aba4646b9ff26110f
AlexanderIvanofff/Python-Fundamentals
/Lists/declipher_this.py
589
4.09375
4
def parse_to_chr(text): digits = '' for digit in text: if not str(digit).isdigit(): break digits += digit ascii_value = int(digits) chr_value = chr(ascii_value) new_word = text.replace(digits, chr_value) return new_word def replace_in_text(text): temp = list(t...
315ab03926276c1dcb73dc73f14552a318b72dde
daniel-reich/turbo-robot
/6FaERG8x8Y6MYmoYF_12.py
1,479
4.3125
4
""" Greed is a dice game played with five six-sided dices. Your mission is to score a throw according to these rules: Three 1's => 1000 points Three 6's => 600 points Three 5's => 500 points Three 4's => 400 points Three 3's => 300 points Three 2's => 200 points One 1 => ...
2848df562b787e72ba7c6948b09742935f373330
shayanbeizaee/python-challenge
/PyBank/main.py
1,952
3.6875
4
#Shayan Beizaee # Financial Analysis import os import csv csvpath = os.path.join('..', 'Resources', 'budget_data.csv') with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') csv_header = next(csvreader) #Total number of the months included in the datat set totalMo...
c4b02f96e393a0558adadd07e6c2350da97177b2
noob-cod/DataSturcture-python
/pythonDataStructure/graph.py
832
3.625
4
""" @Date: Friday, March 12, 2021 @Author: Chen Zhang @Brief: 图数据结构的实现 """ import numpy as np class ArrayGraph: def __init__(self, sourceCollection=None): self._num = 0 self.graph = np.zeros((self._num, self._num)) def __len__(self): return self._num def is_Empty(self): r...
1aabab5d44535d72abf7da02e8346b7092cfd148
mcxu/code-sandbox
/PythonSandbox/src/leetcode/lc553_reverse_words_in_string_3.py
980
4.09375
4
''' https://leetcode.com/problems/reverse-words-in-a-string-iii/ Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" Note: In the strin...
0e9d7d2932323728b9a906cd927a4f90ec8474e4
sanskarlather/100-days-of-code-with-python
/Day 8/better_caeser_cypher.py
641
3.53125
4
from caeser_cypher_logo import logo print(logo) n=0 def salad(n): test="" if n==3: print("Thank You for trying this out") elif n==1: s=input("Enter the string\n") a=int(input("by how much\n")) for i in range(0,len(s)): if ord(s[i])+a>122: test+=chr(ord(s[i])+a-26) else: test+=chr(ord(s[i])+...
acba88bbacc6f321242325305af66f9af59e35f9
franciscoG98/ws-python
/ej3.py
242
3.765625
4
# EJERCICIO 3 # Preguntarle al usuario su edad actual e informale la edad que tendra le año que vien(?????????) userAge = int( input('How old are you?\n')) newAge = userAge + 1 print('Next year you will have ' + str(newAge) + ' years old')
4cc251643d5402e0efcf329d49cae419353e212a
AntnvSergey/EpamPython2019
/13-design-patterns/hw/4-chain_of_responsibility/chain_of_responsibility.py
2,995
4.34375
4
""" С помощью паттерна "Цепочка обязанностей" составьте список покупок для выпечки блинов. Необходимо осмотреть холодильник и поочередно проверить, есть ли у нас необходимые ингридиенты: 2 яйца 300 грамм муки 0.5 л молока 100 грамм сахара 10 мл подсолнечного масла 120 грамм сливочного масла В и...
f8e103d632ba902ff340c732e23432f95b21d0f4
brandoneng000/LeetCode
/easy/1037.py
769
3.609375
4
from typing import List class Solution: def isBoomerang(self, points: List[List[int]]) -> bool: from math import isclose first = tuple(points[0]) second = tuple(points[1]) third = tuple(points[2]) if first == second or first == third or second == third: return ...
4e41163bec478ac8781840319fbdaa461b3c6fdd
lenakchen/Hadoop
/project/mapper2.py
1,110
3.6875
4
#!/usr/bin/env python """ Final Project Task Two: Post and Answer Length Find if there is a correlation between the length of a post and the length of answers. Write a mapreduce program that would process the forum_node data and output the length of the post and the average answer (just answer, not comment) length for...
11525d23678820fedea2e8974c45414254c91f8c
XMK233/Leetcode-Journey
/py-jianzhi-round3/JianzhiOffer34.py
2,589
3.75
4
''' [剑指 Offer 34. 二叉树中和为某一值的路径 - 力扣(LeetCode)](https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof) 输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。   示例: 给定如下二叉树,以及目标和 sum = 22, 5 / \ 4 8 / / \ 11 13 ...
60775997ad0724710d9c34fd28f8d16bf6eed060
DeepakSunwal/Daily-Interview-Pro
/solutions/islands.py
1,093
3.859375
4
def is_valid(grid, r, c): rows, cols = len(grid), len(grid[0]) if r < 0 or c < 0 or r >= rows or c >= cols: return False return True def count_islands(grid): count = 0 for row in range(len(grid)): for col in range(len(grid[0])): if grid[row][col] == 1: c...
493d6055be9305c5013acaca759c513e079260d7
bboz862/correlated-cost-online-learning
/Generate_data_cost/Generate_data_cost_logisticregression/rs12.py
2,916
3.609375
4
import random import numpy as np from scipy.optimize import brentq # This is a generalization of RothSchoenebeck12, where we apply our # importance-weighting framework, but we get the probabilities of # purchase by drawing prices as prescribed by RothSchoenebeck12. # RS12 assumes knowledge of the prior distribution ...
c6a50f0596aa30a62802a92ae7b8095e13b44eef
Madanfeng/JianZhiOffer
/python_offer/53_20~n-1中缺失的数字.py
787
3.625
4
""" 一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。 在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。 示例 1: 输入: [0,1,3] 输出: 2 示例 2: 输入: [0,1,2,3,4,5,6,7,9] 输出: 8   限制: 1 <= 数组长度 <= 10000 """ def missingNumber(nums): """ :param nums: List[int] :return: int """ n = len(nums) left, right...
51ae7c3b3d1e9f1b7153c6a2fdfe565ed5eaedcb
Coliverfelt/Desafios_Python
/Desafio063_a.py
542
4.15625
4
# Exercício Python 063: Escreva um programa que leia um número N inteiro qualquer # e mostre na tela os N primeiros elementos de uma Sequência de Fibonacci. # Ex: 0 - 1 - 1 - 2 - 3 - 5 - 8 n = int(input('Quantos elementos da sequência de Fibonacci você deseja visualizar?')) i = 0 while i < n: if i == 0 or i == 1...
898893814eda9f044ab6c1e37892271823834c8e
shankars99/willy-wonka
/vanilla ciphers/affine-substitute.py
747
3.734375
4
#compute mod inverse def modinv(a, m): mod_inv = pow(a, -1, m) return mod_inv def enc(text, key): return ''.join([chr(((key[0]*(ord(t) - ord('A')) + key[1]) % 26) + ord('A')) for t in text.upper().replace(' ', '')]) def dec(cipher, key): return ''.join([chr(((modinv(key[0], 26...
dc2030016ca6376458cf7bb8c0675adf0144dc91
mariajosearias/Esctructura-de-control-selectivas
/ejercicios/E8.py
348
3.890625
4
""" Entradas valor entero 1-->int-->x valor entero 2-->int-->y salidas valores de x u y """ x=int(input("Digite el valor del entero: ")) y=int(input("Digite el valor del entero: ")) expre=(x**3+y**4-2*x**2) if (expre<=680): print("X y Y satisfacen la expresión "+str(expre)) elif(expre>=680): print("la ...
6d2668871e8429c389b08d4781e5fea70dcdfa55
aiifabbf/leetcode-memo
/528.py
2,207
3.578125
4
""" .. default-role:: math 实现带权采样 大致原理是把给你的权重array ``weights`` 看作是非归一化的概率密度函数,然后积分/前缀和算出非归一化的概率分布函数 ``cdf`` , ``cdf[i + 1] - cdf[i]`` 是取第 `i` 个元素的权重。 采样的时候,在 `[0, \sum w)` 区间里按均匀分布随机取一个整数 `k` ,再去 ``cdf`` 里面找一个 ``cdf[i]`` 使得 `k` 在 ``[cdf[i], cdf[i + 1])`` 区间里。此时 `i` 就是最终要返回的样本。 举个例子,比如权重是 ``[3, 14, 7, 1]`` ,那么非归一化概率...
85282cc5dffd44f1df84585030b5fb1591c26721
Jorza/arcade-games-tutorial
/Playground.py
164
3.859375
4
months = "JanFebMarAprMayJunJulAugSepOctNovDec" n = int(input("Enter a month number: ")) start_index = 3*(n - 1) print(months[start_index:start_index + 3])
db50a687b9cb5d2e557824ecb4c70040eda8f915
saurabh-pandey/AlgoAndDS
/leetcode/linkedList/singly_linked_list/intersection_a1.py
3,483
3.640625
4
#URL: https://leetcode.com/explore/learn/card/linked-list/214/two-pointer-technique/1214/ # Description """ Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null. For example, the following two link...
dfb8e76f0fccedb60e1e39eeb3046d19447bd0fb
artazm/practice-python-sol
/exercise_16.py
578
3.65625
4
# Password Generator # weak (1-3) medium (4-6) strong () import random passw = ['write', 'a', 'password', 'generator', 'python', 'creative', 'mix'] num = list(str(range(0, 10))) symbols = ['!', '@', '#', '$', '%', '&', '*'] pass_gen = passw + symbols + num i = 0 strength = input('How strong you want you...
4b27fb23fd526d509e40dfa0f1626f8914fd21c0
JACKSUYON/TRABAJO5_PROGRAMACION_1_B
/verificador_16.py
575
4.03125
4
#verificador 16: calcular el tiempo de enuentro tiempo_encuentro, distancia, velocidad1, velocidad2=0.0, 0.0, 0.0, 0.0 #asigancion de valores distancia=int(input("mostrar distanccia:")) velocidad1=int(input("mostrar velocidad:")) velocidad2=int(input("mostrar velocidad 2")) #calculo tiempo_encuentro=(distancia)/(veloci...
249535b0aee56265f5c5db10b297cdad64127b63
Junhao-He/PythonUpUp
/Algorithm/isValidSudoku.py
2,082
3.59375
4
# coding = utf-8 # @Time : 2021/7/26 20:04 # @Author : HJH # @File : isValidSudoku.py # @Software: PyCharm class Solution: def isValidSudoku(self, board) -> bool: check = [] # for i in board: # for j in i: # if not j == '.': # check.append(j) ...
567f48193baa3d139cbb3b0f96eedfd4f047e710
FelixZFB/Python_advanced_learning
/02_Python_advanced_grammar_supplement/001_2_高级语法(装饰器-闭包-args-kwargs)/012-函数闭包_1_闭包定义.py
3,479
3.90625
4
# 闭包的定义 # 定义:闭包是由函数及其相关的引用环境组合而成的实体(即:闭包=函数+引用环境(数据))(# 闭包=函数块+定义函数时的环境) # 下面这个就是一个简单的闭包函数 def ExFunc(n): sum = n def InsFunc(): return sum + 1 return InsFunc myFunc_1 = ExFunc(10) print(myFunc_1()) myFunc_2 = ExFunc(20) print(myFunc_2()) # 函数InsFunc是函数ExFunc的内嵌函数,并且是ExFunc函数的返回值。 # 我们注意到一个问题:内...
b7affcc6410e3c13833490112976c52ffe8f74d1
kariane/projectsPython
/project1.py
238
3.875
4
from random import randint def rand(): return randint(1,6) rep = True while rep: print("came out the value:",rand()) print("would you like to roll the dice again?") rep = ("yes") in input().lower() print("Game Over")
adf81dcf49c70d4fd2e944d41632a014f9ff938e
mastan-vali-au28/My-Code
/coding-challenges/week06/Day03/Q2.py
564
4.15625
4
''' Given a number , find if the number is a perfect square root or not ? Also , find Time and space Complexity example : Input : n = 4 output : - True Input : n = 10 output : - False Explanation : since square root (4) =2 (perfect square ) --true Square root(10) = 3.35 (Not perfect square) -- false Sample : Def find_p...
c702788844f9c09543c08ff75bf0221098d60dd9
shobhakharpy/CTI-110
/HDCoockout_Calculator.py
1,180
3.84375
4
# CTI 110 # Shobhakhar Adhikari # Practice Assignment # define varaibles and get the input def HDCookout (): Num_ppl = int(input("Enter the number of people attending the cookout:")) # Calculations and decision structure x = Num_ppl//10 # gives the number without decimal after div...
60edd08e3982f0f93fa3a8258b5ac688038dc406
secretdsy/programmers
/level2/practice/12949.py
442
3.578125
4
def solution(arr1, arr2): # 결과 리스트를 0으로 초기화 answer = [[0] * len(arr2[0]) for _ in range(len(arr1))] # matrix_size = (i,k) * (k,j) = (i,j) for k in range(len(arr1[0])): for i in range(len(arr1)): for j in range(len(arr2[0])): answer[i][j] += (arr1[i][k] * arr2[k][j]) ...
27918f7a20e38214c841735e03ae850b58ab1d25
edisonkolaj/Prework-REPO
/Assignment 1.py
100
3.703125
4
#Edison Kolaj #Assignement #1 Name = input("Hello User. What is your name?") print("Welcome", Name)
2e09618979b589c36c8dc04fad1e0186d5528810
quarkgluant/boot-camp-python
/day03/ex02/ScrapBooker.py
3,691
3.640625
4
#!/usr/bin/env python3 # -*-coding:utf-8 -* import numpy as np class ScrapBooker: """All methods take in a NumPy array and return a new modified one. We are assuming that all inputs are correct, ie, you don't have to protect your functions against input errors. In this exercise, when speci...
382c5bc363285cf4ed5d2ee8edcd30e3d33d4fa8
tonyechen/python-codes
/reduceFunction/main.py
444
4
4
# reduce = apply a function to an iterable and reduce it to a single cumulative value. # performs function on first two elements and repeats process until 1 value remains # # reduce(function, iterable) import functools letters = ["H", "E", "L", "L", "O"] word = functools.reduce(lambda x, y: x + y, letters) ...
6591cfb2a328efc8a9ac4d4069886d42f4b2adf4
vincepay/Project_Euler
/python/21-30/Prob29.py
1,561
3.765625
4
##Consider all integer combinations of a^b for 2 <= a <= 5 and 2 <= b <= 5: ## ## 2^2=4, 2^3=8, 2^4=16, 2^5=32 ## 3^2=9, 3^3=27, 3^4=81, 3^5=243 ## 4^2=16, 4^3=64, 4^4=256, 4^5=1024 ## 5^2=25, 5^3=125, 5^4=625, 5^5=3125 ## ##If they are then placed in numerical order, with any repeats removed, ##we get the ...
96f6b1ef3e0b9141759a68b2bd6a895de45fc47e
carlos-andrey/programacao-orientada-a-objetos
/listas/lista-de-exercicio-07/questao06.py
913
3.53125
4
class Retangulo: def __init__(self, base, altura): self.base = base self.altura = altura def mudar_valor_lado(self, nova_base, nova_altura): self.base = nova_base self.altura = nova_altura def retornar_valor_lado(self): return self.base, self.altura def calcular_a...
93a59e35851ca5d4e4efc2f633942428e173a521
ErenBtrk/Python-Fundamentals
/Pandas/PandasDataframe/Exercise54.py
339
4.4375
4
''' 54. Write a Pandas program to convert a given list of lists into a Dataframe. ''' import pandas as pd my_lists = [['col1', 'col2'], [2, 4], [1, 3]] # sets the headers as list headers = my_lists.pop(0) print("Original list of lists:") print(my_lists) df = pd.DataFrame(my_lists, columns = headers) print("New Da...
0d4883a8d8d46f1e6b5fb5fd1e9647abac80034e
ftahrirc/Snake1
/snake.py
752
3.859375
4
import turtle,random class Cell: def__init__(self,size,t,x,y): self.x=x self.y=y self.t=t self.size=size def draw_square(self): for side in range(4): self.t.fd(self.size) self.t.left(90) def draw_snake()(self) for side in range(5): cell=cell(10,turtle.turtle...
21fcb74551980e0c9f82758989ed41d42b01c74e
DiegoElizaldeUriarte/Mision_02
/velocidad.py
661
3.859375
4
# Autor: Diego Raul Elizalde Uriarte, a01748756 # Descripcion: Pregunte la velocidad e imprima las distancias en el tiempo requerido y calcule el tiempo en cierta distancia. # Escribe tu programa después de esta línea. #Lectura y calculo de resultados v = int(input("Dame la velocidad a la que viaja un auto en km/h y ...
74eed9c2864d3389ea6ac02f4794c9c84641eb0f
furkanoruc/furkanoruc.github.io
/Python Programming Practices - Daniel Lyang Book/ch10 copy/10_Furkan_36_linearsearch- check.py
440
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Feb 5 14:38:14 2021 @author: furkanoruc """ #Linear Search n = eval(input("Enter number of integers: ")) lst = [] #counter = [0] * n for i in range(n): lst.append(eval(input("Enter the integers, one by one: "))) key = eval(input("Enter the key t...
6f73174520db3b1c3c2b2f394440fe24cb7fca00
llimllib/personal_code
/python/poker/win_prcnt.py
1,402
3.96875
4
""" Doubts, thoughts: o We can calculate, with 5 cards left, how many hands add a 3rd or a 3rd and a 4th to a pocket pair o We can calculate how many hands add a pair to a non-pair Things we need to know: o how many possible hands there are to be dealt o how many of those have >2 hearts o how many of those give eit...
90dc7417a611bcad57aab0ff40c1c8199638a6ed
JeffreyJalal/AdventOfCode
/2015/Day3/PerfectlySphericalHousesInAVacuum.py
941
3.5
4
def getNewLocation(location, direction): newLocation = location.copy() if direction == '>': newLocation[0] += 1 elif direction == '<': newLocation[0] -= 1 elif direction == '^': newLocation[1] += 1 else: newLocation[1] -= 1 return newLocation currentLocationSanta...
89f838a083b2e8e2df8671345087598baed3bb57
Aasthaengg/IBMdataset
/Python_codes/p03252/s883010906.py
273
3.546875
4
s = input() t = input() f = True for (s1, s2) in [(s, t), (t, s)]: d = dict() for c1, c2 in zip(s1, s2): if c1 not in d: d[c1] = c2 elif d[c1] != c2: f = False break if f: print('Yes') else: print('No')
a723d8823451f7b2b780fe4858b7adf30e266197
fxyan/data-structure
/code/剑指/二叉树的下一个节点.py
1,142
4.03125
4
""" 给定一棵二叉树的其中一个节点,请找出中序遍历序列的下一个节点。 注意: 如果给定的节点是中序遍历序列的最后一个,则返回空节点; 二叉树一定不为空,且给定的节点一定不是空节点; 样例 假定二叉树是:[2, 1, 3, null, null, null, null], 给出的是值等于2的节点。 则应返回值等于3的节点。 解释:该二叉树的结构如下,2的后继节点是3。 2 / \ 1 3 这里注意当给出的节点没有右节点的时候还有另一种情况。 """ class TreeNode(object): def __init__(self, x): self.val = x s...
7b8403c1731ec0a1187bd94fa7ef06f56783de7f
psandahl/trio
/trio/tests/utils.py
801
3.640625
4
import math def equal_matrices(m, n): """ Helper function to test if two matrices are somewhat equal. """ if m.shape == n.shape and m.dtype == m.dtype and m.ndim > 1: for row in range(m.shape[0]): for col in range(m.shape[1]): if math.fabs(m[row, col] - n[row, col])...
32c02e161623769b224b135dfdb5bb17e4f55c8a
RichieSong/algorithm
/算法/排序/二分查找.py
3,720
3.96875
4
# coding:utf-8 """ 二分查找的必要条件: 1,必须是数组 2,必须是有序 3,不适合数据量太大或太小的情况,太大可能会申请内存失败(申请内存必须是连续的,而零散的内存会失败),太小没必要,直接遍历即可 """ # 最简单的二分查找 def bsearch(arr, length, value): """ :param length: 数组长度 :param value: 查找的值 :return: """ low = 0 high = length - 1 while high >= low: # 注意一定是大于等于 mid =...
4f7c9801d0e3a31cd6d109dc61b79b05b3629740
KB-perByte/CodePedia
/Gen2_0_PP/Homeworks/geeksForGeeks_isBInaryNumMulOf3.py
381
3.515625
4
#code T = int(input()) for i in range(T): n=list(input()) value=0 for i in range(len(n)): d=n.pop() if d=='1': value=value+pow(2,i) if(value%3==0): print("1") else: print("0") ''' #TODO diff btn the cnt of set bits at odd pos and the cnt of set bits at e...
f5efbc811957fa84134904d78c13444708ab5eb9
Ideaboy/MyLearnRecord
/algo_learn/insertion_sort.py
726
4.0625
4
#!/usr/bin/python # -*- coding:utf-8 -*- # 2019年5月4日14:40:11 # 插入排序 """ 第一个元素设为有序区,选取后面元素,向前遍历比较, 最小的插入在比较元素前。 较大的直接赋值后移,一直比较,直至最小,在上个位置插入赋值即可。 """ def insertion_sort(dlist): for i in range(0, len(dlist)): preindex = i-1 current = dlist[i] while preindex >= 0 and dlist[preindex]...
b51f18c6edf50183d744ac3c3ed62a92fe98d1c9
jhonatanmaia/python
/study/curso-em-video/exercises/049.py
125
4
4
x=int(input('Digite o nmero da tabuada: ')) print('-'*20) for a in range(1,11): print('{} x {} = {}'.format(a,x,a*x))
13dfc5ad116239848ab028874c6393f123f22837
lalit97/DSA
/union-find/z-kruskal.py
1,581
3.984375
4
''' understanding -> https://www.hackerearth.com/practice/algorithms/graphs/minimum-spanning-tree/tutorial/ implementation -> taking help of Graph bfs dfs implementations union find implementations of mine https://www.geeksforgeeks.org/kruskals-minimum-spanning-tree-algorithm-greedy-algo-2/ ''' from collection...
19709ffa1d07c85948c54a939cecc8b42d434e91
RufusKingori/Lecture_2
/assignment_2_1.py
403
3.953125
4
#This program adds 2 to a and assigns the results to b #Multiplies b times 4 and assigns the results to a #Divides a by 3.14 and assigns the results to c #Subtracts 8 from b and assigns the results to a def main(): a = int() b = int() c = int() b = 2 + a print("b:", b) a = b * 4 print("a:"...
5f54febed1313c99101f8a8c0bb7dc891b6df757
mfojtak/deco
/deco/sources/dataset.py
289
3.546875
4
from abc import ABC, abstractmethod class Dataset(ABC): @abstractmethod def __iter__(self): pass def eval(self): res = [] for item in self: res.append(item) if len(res) == 1: return res[0] return res
4217c935c0ab445132452750ac62c56f19f4aa9c
thkim1011/chess-ai
/tests/test_chess.py
1,952
3.65625
4
import chess import unittest class TestBoard(unittest.TestCase): def test_get_piece(self): # Basic Tests board = chess.Board() rook1 = board.get_piece(chess.locate("a1")) self.assertEqual(rook1.name, "rook") rook2 = board.get_piece(chess.locate("a8")) self.assertEqu...
b421bd9515cf8cef2029adb1b139986ed5224036
PROFX8008/Python-for-Geeks
/Chapter04/errors/exception2.py
170
3.5
4
#exception2.py try: f = open("abc.txt", "w") except Exception as e: print("Error:" + e) else: f.write("Hello World") f.write("End") finally: f.close()
91d4caffa5245e68c779cdd68276cecefca8d5a6
ncterry/CryptoSteganography
/xaaaa_primaryColors.py
1,047
3.90625
4
from Functions import create_image, get_pixel from main import * # Create a Primary Colors version of the image def convert_primary(image): # Get size width, height = image.size # Create new Image and a Pixel Map new = create_image(width, height) pixels = new.load() # Transform to primary ...
d095b5b98a05c15b85547c650c2a72e00b321a2c
kgawne/AdventOfCode2017
/day3.py
1,478
3.734375
4
# day 3 # kgawne def TestCompare( case, expected, result): print('Case ' + str(case) + ': ') if expected == result: print("\tSuccess! Result: " + str(result)) return True; else: print("\tFailed :( Expected: " + str(expected) + " Result: " + str(result)) return False; def CalcSteps(squareNum): #generate bl...
f65d8a9a549ead5deff0d953d9a1e795567e6233
Maavcardoso/Python3.9
/Aulas/04_modulos.py
686
4.25
4
# Os módulos servem para adiocionar diferentes funções ao programa python # Como exemplo, usarei o módulo math. # Podemos chamar o método de duas formas: import math # Importa todas as funções de Math from math import sqrt # Importa uma função específica de Math, no caso, raiz quadrada. n = int(input('Digite ...
a41bb0e9a679083c2a54b98008646f04591869c9
ozercimilli/clarusway-aws-devops-workshop
/python/coding-challenges/cc-003-find_largest_number/large.py
443
4.53125
5
3# Python program to find the largest number among the three input numbers # creating empty list lis = [] # user enters the number of elements to put in list #count = int(input('How many numbers? ')) # iterating till count to append all input elements in list for n in range(1,6): number = int(input('En...
3b8ecdc391fb36f4c478a1bfe31b03174b50299f
exploreshaifali/datastructures
/bst_recursive.py
2,021
3.859375
4
class BSTNode: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right class BST: def __init__(self, data=None): if data is None: self.root = None else: self.root = BSTNode(data) def insert(self,...
82bc9987958295582cb1a2744260bb12826373a5
CodePanter/pytut
/Book/Dragon realm.py
2,239
4.125
4
import random import time def displayIntro(): print('Welcome in a world full of pitbulls , some are scary but some are actually sweet.') print() def chooseCave(): cave = '' # A local scope is created whenever a function is called. Any variables assigned in this function exist within the local scop...
bf28667009a14c246e5a85c43e50bfd2b667ab92
dabuu/FluentPython
/chap2/2.2.py
1,464
3.5625
4
# coding:utf-8 """ @file: 2.2.py @time: 2018/8/17 18:19 @contact: dabuwang """ __author__ = 'dabuwang' symbols = '$%&^#()!@' # £$¤¥¨ª'#¥¢¤£ÿ' def list_comprehension(): for y in symbols: print ord(y) print "========" codes = [ord(x) for x in symbols] print codes def list_comprehension_same...