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
5baafa7f1794ce4e3a786074b177503adb545940
Josh-Jo1/Python
/Python Code Challenges - LinkedIn Learning/06 Save a Dictionary.py
818
4.21875
4
# Save Function # Challenge: Write a Python function to save a dictionary to file. # Input: dictionary to save, output file path # Load Function # Challenge: Write a Python function to load the saved dictionary back into Python. # Input: file path to saved dictionary; Output: retrieved dictionary object def SaveFun...
775b960983e0e9bb6b48dceff664f98e2a48b952
corgiTrax/Sparse-Reinforcement-Learning
/agent.py
4,363
3.578125
4
'''reinforcement learning agent''' from config import * class Agent: '''agent class that moves in the 2D world''' def __init__(self, initPos, world): '''2D position of the agent''' self.pos = py_copy.deepcopy(initPos) '''the world this agent lives in''' self.world = world ...
fea5fbb3b0648223cd063c892f5bbab11bb70534
badangle520/Python
/Python小甲鱼/c12_列表BIF_index.py
180
3.9375
4
print(''' list1 = [1, 3, 1, 4, 1, 5, 1, 10] print(list1.index(1)) print(list1.index(1,1,6)) ''') list1 = [1, 3, 1, 4, 1, 5, 1, 10] print(list1.index(1)) print(list1.index(1,1,6))
339a8b11dfaf145ab08256fca12f91f8c567f7ad
ytpessoa/RESTful-APIs-with-Python-and-Flask
/00-codigos/test.py
398
3.71875
4
def listas(): L = [] L1 = [1,2,3] print(L1) L1[0]=2 print(L1) def fString(): nome = "Pedro" idade = 54 print(f"O nome dele eh {nome}. Ele tem {idade} anos") def printPar(fim): print("func2") i=0 while i <= fim : print(i) i+=2 def main(): print("func1:main") x = int(input("Entre com um numero")...
9169af377fef56841f6a1f637e7652c7d7dc0117
dundunmao/lint_leet
/mycode/leetcode_old/6 linked list (8)/medium/141. Linked List Cycle.py
1,132
4
4
# coding:utf-8 # 3级 # 题目: Given a linked list, determine if it has a cycle in it.(不要用extra space)找是否有circle # class Node(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool...
c66ba72fa375d16fc00f5a60052bfe41016a0832
skanda9927/year2020
/38_Write_a_Python_program_to_count_the_number_of_even_and_odd_numbers_from_a_series_of_numbers.py
1,293
4.3125
4
# # 38. Write a Python program to count the number of even and odd numbers from a series of numbers. # #PSEUDOCODE #1:take input total number of numbers in which number of odd or even numbers has tobe calculated #2:initialise even and odd number count to zero #3: input the sequence of numbers #4: using modulus f...
3e73ff3cf16328902fd84f886f6dd4138ff8d4d1
spearfish/python-crash-course
/practice/06.06_investigation.py
412
3.78125
4
#!/usr/bin/env python3 fav_langs = { 'jen' : 'python', 'sarah' : 'c', 'edward' : 'ruby', 'phil' : 'python' } invited = ['jen', 'phil', 'jackie', 'jeffery'] for person in invited : if person in fav_langs.keys() : print("Thank you for participating {}!".format(person.title())) e...
d3b4fbf62328ddd1faef470fe75f5eb84c123afe
prabhatcodes/Python-Problems
/Placement-Tests/Interview-Prep-Astrea/Patterns.py
1,272
3.625
4
# * # ** # *** # **** # ***** # ****** for N def pattern(n): for i in range(1,n+1): for j in range(1,i+1): print ("*", end='') print() # 1 # 12 # 123 # 1234 # 12345 for N def pattern(n): for i in range(1,n+1): for j in range(1,i+1): print(j, end="") pri...
e3a3e72c3be0a82f7226bd59f51e7266408ccfd3
sh999/Python-Study-Snippets
/multithreading.py
471
3.6875
4
''' multithreading.py Reference: ========== http://www.tutorialspoint.com/python/python_multithreading.htm ''' import thread import time def print_time(threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print "%s: %s" % (threadName, time.ctime(time.time())) try: thread.start_new_thread...
1fa514989fb7483addfeee19e284aed49e6d3f34
aprebyl1/DSC510Spring2020
/KAAKATY_RONI_DSC510/Assignment_9_1.py
2,797
4.46875
4
# File: Assignment_9_1.py # Name: Roni Kaakaty # Date: 05/09/2020 # Course: DSC510-T303 Introduction to Programming (2205-1) # This program will do the following: # Open text file and process each line. # Either add each word to the dictionary with a frequency of 1 or update the word's count by 1. # Nicely pri...
ec3675212a301e6a5e8827d0b2a71933b435490b
Carrazza/Tutoriais
/Python/Tutorial/Colections/arrays.py
220
3.609375
4
#https://docs.python.org/3/library/array.html link para saber cada letrinha mágica import array as arr exemplo = arr.array('d', [1,2.5,6.3]) #específico para tipo, como se fosse um array em C mesmo print(exemplo)
d8a009749b8c9ff3232535fca9283b70846e8e38
atwoodng/assignment
/python hw/credit card problem/paydebtoffinoneyearbisectionsearch.py
1,108
3.90625
4
""" similar to pervious program, this program is to calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months using bisection search""" ## for example: ##balance = 320000 ##annualInterestRate = 0.2 def balance_month(balance,pay,annualInterestRate): outcome=(balanc...
8dd08a0a92dc5a448e1de4fe7bcea826078a4901
953250587/leetcode-python
/DecodedStringAtIndex_MID_884.py
3,166
4.0625
4
""" An encoded string S is given. To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken: If the character read is a letter, that letter is written onto the tape. If the character read is a digit (say d), the entire current tape is repeated...
c5d7a2e89edfd00e71c2b8b222d340731630784f
Victorli888/Python-Tutorial-Workbook
/LearnPythonTheHardWay/Exercise_29_What_if.py
637
4.125
4
people = 20 cats = 30 dogs = 15 if people < cats: print("Too many cats! The world is doomed") if people > cats: print("Not many Cats! The world is saved.") if people < dogs: print("The world is drooled on.") if people > dogs: print("The world is dry.") dogs += 5 # this is the same as dogs = dogs...
b59a52137381d0c161f8685cf9c1a8401b7a9f4b
saichandkalva/Quad
/GAME.PY
6,196
3.65625
4
import random playing = False stand1=True chip_pool = 100 bet = 1 restart_phrase = "Press 'd' to deal the cards again, or press 'q' to quit" su = ('H', 'D', 'C', 'S') r = ('A', '2', '3', '4','5', '6', '7', '8', '9', '10', 'J', 'K') card_val = { 'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8'...
f16f5e2ef74608b987f57f14d57312ecb9a9e928
fernandomarques/LaboratorioProgramacao
/Lista Condicional/2_fruteira.py
699
3.6875
4
morango = float(input("Quantos kilos de morango?")) maca = float(input("Quantos kilos de maçã?")) if morango > 5: preco_morango = morango * 2.2 else: preco_morango = morango * 2.5 if maca > 5: preco_maca = maca * 1.5 else: preco_maca = maca * 1.8 preco_total = preco_maca + preco_morango if maca +...
28c474f5d8ccd35cba5e7674426b496e4e417990
jesuszarate/CTCI
/LeetCode/maximum_size_subarray_sum_equals_k_325.py
1,407
3.921875
4
''' Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead. Note: The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range. Example 1: Input: nums = [1, -1, 5, -2, 3], k = 3 Output: 4 Explanation: The su...
ab6a3427236154b20eb832b3ece8f1ef4cb7ad12
martinkozon/Martin_Kozon-Year-12-Computer-Science
/Python/01_intput-output.py
232
4.28125
4
#Program which will ask you for your name and return it in a phrase "Hello, name" #input your name yourName = str(input("What's your name? ")) #print the phrase "Hello, name" print("Hello, " + yourName + ".") ##ACS - Excellent
78718624f534fa689304b9996ceb1c7ae6a94b69
NiceStudentAccount/FirstSemester
/Ejercicios 31-50/34.py
552
3.78125
4
print('---------------PROBLEMA 34---------------') def askArray(): numbers = input('Numeros separados por un espacio: ').split() numbers = set(map(int, numbers)) return numbers def mcm(numbers): num = max(numbers) print(numbers) print(num) while True: flag = True fo...
646b94d71a848cfd99c42717fbc1782e959869e8
bitterengsci/algorithm
/九章算法/基础班LintCode/2.61.Search for a Range.py
2,436
3.90625
4
#-*-coding:utf-8-*- ''' Description Given a sorted array of n integers, find the starting and ending position of a given target value. If the target is not found in the array, return [-1, -1]. ''' class Solution: """ @param A: an integer sorted array @param target: an integer to be inserted @return: a...
39ed81092da3e5f839284dd84e6e5a8b252c1953
QitaoXu/Lintcode
/Alog+/class6/interleaveString.py
1,112
3.875
4
class Solution: """ @param s1: A string @param s2: A string @param s3: A string @return: Determine whether s3 is formed by interleaving of s1 and s2 """ def isInterleave(self, s1, s2, s3): # write your code here m, n, t = len(s1), len(s2), len(s3) if...
bddfaca2c8ec7d865b2fef389d53037c324066ac
Mithun691/SOC_2021
/Week1/Day1_Probability_basics/Q2_Simulation.py
816
3.9375
4
import random import math def simulate(): """ return True if the needle falls on the line , False otherwise """ spacing = 1.0 stick_length = 0.5 #Randomly choose the positon at which it falls pos_x = spacing*random.random() #random number between 0-1 angle = math.pi*random.rand...
ab77a0bad7d816b07af485d8b7aea5440f3ed1ed
kuangtao94/Python
/面向对象编程/ch07_3.py
2,826
4.09375
4
# -*- coding: utf-8 -*- # ------------------------------------- # 继承:派生类可以继承父类的公有成员 # ------------------------------------- # 单继承 # 基类:员工 class Staff: school = '一中' # 类变量,在该类及其子类的实例中共享 def __init__(self, name='', age=25, sex='男'): # 成员变量(实例变量)通常都是在此方法中定义 self.__name = name ...
a289826052eb7b361290b586cf36e5d20597c33e
EviBoelen15/Schooloedeningen
/Hogeschool/Bachelor/Semester 1/IT Essentials/Oefeningen en code/Oefeningen/Oefeningen/ITEssentials(ilias 1TINC)/7_lists/cursus/opgave7_7.py
1,942
3.84375
4
def get_number_of_participants(tabel_list): return len(tabel_list[0]) def get_number_of_tests(tabel_list): return len(tabel_list) def highest_heart_rate(tabel_list): highest = tabel_list[0][0] for i in range(len(tabel_list)): for j in range(len(tabel_list[i])): if tabel_list[i][j...
a4f653aedce33d412a390facb09661377b280f3e
Prabithapallat01/pythondjangoluminar
/pythoncollections/list/list_intro3.py
247
4.0625
4
#Given a two Python list. # Iterate both lists simultaneously such that list1 should display # item in original order and list2 in reverse order lst1=[200,345,122,678,234] lst2=[500,344,800,100,300] for x, y in zip(lst1,lst2[::-1]): print(x,y)
54358fbbb2b02b88560f695c40464a5d9bd09398
godismeandyou/sunfei
/test_01/test_09.py
363
4.34375
4
def top_three(input_list): """Returns a list of the three largest elements input_list in order from largest to smallest. If input_list has fewer than three elements, return input_list element sorted largest to smallest/ """ # TODO: implement this function a = sorted(input_list,reverse=True) pri...
40a30185d17c28f45854cd70fc41f239a2c4d3fb
subinmun1997/my_python
/keys_func.py
206
3.984375
4
d=dict(a=1,b=2,c=3) print(d) for k in d.keys(): print(k,end=', ') for v in d.values(): print(v,end=', ') for kv in d.items(): print(kv,end=', ') for k,v in d.items(): print(k,v,sep=',')
dadac25d1aa7b4bc7a875c4d64cae7f616fd3e38
AkankshaKaple/Python_Data_Structures
/list/greater_word.py
314
4.25
4
# This program finds the list of words that are longer than n # from a given list of words list = ["Akanksha","Rajendra", "Kaple", "Siddhesh"] word = len(list[0]) number = int(input("Enter number : ")) # Take the number from user for i in range(len(list)) : if len(list[i]) > number : print(list[i])
1e5badd95fa9469ef0bdf4c88eacd1c08b771a81
wanderleibittencourt/Python_banco_dados
/Modulo-2/Aula2-2-Classes/aula4.py
1,053
3.765625
4
""" _ protected __ private """ _a = 'Protected' __a = "Privado" class Produto: def __init__(self,nome, valor) -> None: self.__nome = nome self.__valor = valor self.oi = "Oi" # Getter def ler_nome(self): return self.__nome #Getter def ler_valor(self): ...
e8a0db14ed6be68411b5e10e06962d6e78d433dd
Narasimha-anonymous/Programs-on-for-loop
/factorial of a num.py
107
4.0625
4
n=int(input("Enter a num.: ")) fact=1 for i in range(n,0,-1): fact*=i print("Factorial of ",n," is ",fact)
fa02a1ee98c8ea131dafad82931622a54ae77230
Agastyabisht123/Python-Assignment
/Program11.py
342
3.84375
4
# Write a program anti_html.py that takes a URL as argument, downloads the html from web and print it after stripping html tags. import sys import requests from bs4 import BeautifulSoup url = input("Enter a valid URL : ") page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') soup = soup.body pr...
c1e019cbf7980b78e5dfd88c24ddb57f027f60ac
EvertonSerpa/Curso_Guanabara_Python_Mundo01
/Exer_10.py
652
4.25
4
# Exercício Python 10: Crie um programa que leia quanto dinheiro uma pessoa # tem na carteira e mostre quantos dólares ela pode comprar. print() real = float(input('Digite quanto de dinheiro você tem na carteira R$: ')) dolar = real / 5.17 #valor do dolar em 27/07/2021# print('Você pode comprar US$ {:.2f} dolar(s)'.for...
5fa3ed860b8699f922ce8cb57cafd6a91f5bc8ce
ram-2580/ML
/Face-Recognizer/face_recognition.py
4,552
4.09375
4
# Recognize faces using KNN algorithm # Steps # 1. Load the training data (Numpy arrays of all persons) # x - values are stored in the numpy arrays # y = assign values we need to assign for each person # 2. Read a video stream using opencv # 3. Extract faces out of it # 4. Use KNN to find prediction of face(i...
08bd80d2c63d403d0ca3fdba5931cc8961cd35d1
sashakrasnov/datacamp
/13-introduction-to-data-visualization-with-python/3-statistical-plots-with-seaborn/02-plotting-residuals-of-a-regression.py
1,213
4.1875
4
''' Plotting residuals of a regression Often, you don't just want to see the regression itself but also see the residuals to get a better idea how well the regression captured the data. Seaborn provides sns.residplot() for that purpose, visualizing how far datapoints diverge from the regression line. In this exercise...
4cd815bfd633b967fc40a9b947593029279769fc
capt-alien/tweet
/cleanup/text.py
390
3.578125
4
from collections import Counter import sys def histogram(string): words1 = string.lower() words = words1.split() count = Counter() for word in words: count[word] += 1 return count if __name__ == '__main__': filename = sys.argv[1] words = open(sys.argv[1], "r").read() hist = h...
b758ec0cd4d3d6b909edf4367d5b403d608c1947
HY36/searchengine
/queue.py
436
3.53125
4
# -*- coding:utf-8 -*- # __author__ = 'hy' class Queue: def __init__(self): self.items = [] def put(self, item): # 放入数据 self.items.append(item) def get(self): # 取出数据 return self.items.pop(0) def is_empty(self): # 判断队列是否为空 return self.size() =...
a6740fc4ddf711e1eaacc0040772e21eb46299a0
Sam-Coon/Py_Ch_10
/Py_Ch_10_1.py
5,091
3.984375
4
# Py_Ch_10_1.py # Authors: Sam Coon and Tyler Kapusniak # Date: 3/4/15 from tkinter import * class Application(Frame): """ GUI application that creates a story based on user input. """ def __init__(self, master): """ Initialize Frame. """ super(Application, self).__init__(master) ...
47feb2a6796cbee55d9241817cd6f6a993c7971b
gouri-gupta/Joy-of-learning-Python
/Generators_homework.py
1,882
4.46875
4
#rishabhj@nvidia.com #Create a generator that generates the squares of numbers up to some number N. ''' def create_square(n): for i in range(n): yield i**2 n=int(input("Enter a number:")) for x in create_square(n): print(x) ''' #Create a generator that yields "n" random numbers between a low and hi...
b4e74cb235728fdda9b77e9f31a089b836ee44f7
dcormar/pyScripts
/SquaredArrays.py
382
3.75
4
def squaredArrays(a1, a2): return False if a1 is None else False if a2 is None else sorted([x**2 for x in a1]) == sorted (a2) a1 = [121, 144, 19, 161, 19, 144, 19, 11] a2 = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19] print(squaredArrays(a1, a2)) ''' try: return sorted([i ** 2 for i in a...
4347ca8e66b1ff71524df83836c3031857e9696c
karngyan/Data-Structures-Algorithms
/Graph/Boggle.py
1,878
4.03125
4
# Find all possible words in a board of characters """Input: dictionary[] = {"GEEKS", "FOR", "QUIZ", "GO"}; boggle[][] = {{'G','I','Z'}, {'U','E','K'}, {'Q','S','E'}}; Output: Following words of dictionary are present GEEKS QUIZ """ def findWor...
f6c3df760f6daf4b85198985ac8195daa1e8aee0
JustgoodDeal/Different-tasks
/HomeWork/Class 5/Mod/module_2.py
368
3.671875
4
def count_if(A,p1,p2): count_sum = 0 for i in A: for j in i: if p1<=j<=p2: count_sum += 1 return count_sum def Test_count_if(): assert count_if([[4,10,3,6],[8,7,-3,-5],[4,-8,6,-1]],5,15)== 5,'Тест провален' assert count_if([[4,10,3,6],[8,7,-3,-5],[4,-8,6,-1]],0,...
3225896b50f3127cafde0ef117cfb2257edcb305
PeteyS/allPythonStuff
/zip_puzzle.py
2,243
3.65625
4
import shutil import os import re #shutil.unpack_archive('unzip_me_for_instructions.zip','unpackedpuzzlezip','zip') i cant test if i leave this code because it resets that zip file each time, but it just unpacks zip numbers = {} #creating dictionary to display phone number and what text file they were found in ...
8155da53637141b9a76eb07a3168526fed260131
8589/codes
/python/leetcode/array/817_Linked_List_Components.py
665
3.53125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def numComponents(self, head, g): """ :type head: ListNode :type g: List[int] :rtype: int """ mem = set(g) cu...
344dbbf62b6ac78baf0b701e65d5188eb5e1ac20
Shanto75/numerical-method
/Lagrange_s polynomial.py
928
3.734375
4
import sympy from sympy import symbols from numpy import linspace from sympy import lambdify import matplotlib.pyplot as p X = [] Fx = [] size = int(input("Size of array : ")) print("Enter Data for X : ") for i in range(size): X.append(float(input())) print("Enter Data for Fx : ") for i in range...
efa517acb7f2a7e18246174878db9c06b559331b
richardju97/python-scripts
/staminaCalculator.py
638
3.515625
4
# Stamina Calculator for the popular game Puzzles and Dragons from datetime import time from datetime import datetime # dungeonTime = time(3, 30) # print dungeonTime # print datetime.now() # # dTime = dungeonTime - datetime.now() # print dTime dungeonTime = raw_input("Time your dungeon starts (Hour:Minutes AM/PM): ...
355afc3a543841ed526f36fb790ad581ce0e66ed
youngmeezz/Algorithm
/input_test.py
153
3.96875
4
tryCount = input("How many times will you try it?") print('counter is ' + tryCount) for num in range(int(tryCount)): print("Hello {0}".format(num))
97bc1b02c7f21d2565b5f6f441e4227a30854605
MathematicianVogt/Artificialintelligence
/ttt.py
448
3.921875
4
def showBoard(board): print str(board[0]) + "-"+str(board[1]) + "-"+ str(board[2]) print str(board[3]) + "-"+str(board[4]) + "-"+ str(board[5]) print str(board[6]) + "-"+str(board[7]) + "-"+ str(board[8]) def minimax-d(position,board): v=maxValue(position,board) def maxValue(position,board): pass def minVal...
15b49315440fa3fca37fa92ac384b693532bf34b
kyle-cryptology/crypto-algorithms
/Signature/DigitalSignature.py
2,614
3.671875
4
# -*- coding: utf-8 -*- """ .. module:: DigitalSignature :synopsis: The digital signature. .. moduleauthor:: Kyle """ from Encryption.PKEncryption import RSA as PKE_RSA from Essential import Groups, Utilities as utils import abc class DigitalSignature(object): """Digital Signatures""" def __init__(self, ...
5d631b7737415e656a59b9663b85fa0e2b45b653
nickolas-pohilets/bpylist
/bpylist/archive_types.py
3,856
3.875
4
from datetime import datetime, timezone class timestamp(float): """ Represents the concept of time (in seconds) since the UNIX epoch. The topic of date and time representations in computers inherits many of the complexities of the topics of date and time representation before computers existed, an...
6a2da544be8b547947aefa9bee9621056e0991fa
Mrseeyou/python
/爬虫/案例/v5.py
1,076
3.640625
4
''' 利用parse模块模拟post请求 分析百度词典 1.打开F12 2.尝试输入单词girl, 发现每敲一个字母后都有请求 3.请求地址是 : http://fanyi.baidu.com/sug 4.利用NetWork-All-Heardets, 查看, 发现FormData的值 是kw:*** 5.检查返回内容的格式, json ''' from urllib import request, parse import json ''' 流程 1.利用data构造函数, 然后urlopen打开 2.返回一个json格式的结果 3.结果就应该是girl的释义 ...
8cc277416bc4afdf61c3a28a7cd97fd1c75967f3
Dexterv/IMC
/pablovaneliMatosIMC.py
184
3.671875
4
peso=int(input("Por favor,(em Kg) entre com o seu peso.:")) altura=int(input("Por favor,(em Metros) entre com o a sua altura.:")) imc= peso/(altura**2) print("Seu IMC é:",imc,)
93a4aebf7cb8ee6a06eb7bbbf14da7176b6bbd60
vihndsm/Python
/Строка.py
157
3.671875
4
#s='Python' #print(s[2],s[0]) #s = 'Turatbek' #print(s[::-1]) #s='Turatbek' #print(s[-2:]+s[0:2]) """s='Turatbek' b=input('') print(b in s) #True/False"""
a3fc0933045e544fd147bce0ade50eebc3cbedad
ruozhizhang/leetcode
/problems/dynamic_programming/Max_DotProduct_of_Two_Subsequences.py
1,731
3.96875
4
''' https://leetcode.com/problems/max-dot-product-of-two-subsequences/ Given two arrays nums1 and nums2. Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none...
6e1e63474127a53963e2e576a3f976be44a3aca9
cforan99/underpaid-customers
/accounting-edit.py
1,910
4.0625
4
MELON_COST = 1.00 FANCY_LINE = "********** " def underpayment_report(filename="customer-orders.txt"): """ Takes a text file of customer order information, iterates over each line to find the customer name, melon quantitity, and amount payed, determines if the customer underpaid and prints a report listing those ...
b94b578c13f434a485f520104c5aca5b9ff986c9
semreyalcin/CS-Tasks-in-Python
/What if ...(2) - Solutions/What if ...(2) - 5.py
249
3.890625
4
#Python 3 Solution #Get two integers from user num1, num2= map(int,input("Enter two integers:").strip().split()) if (num1 + num2 < 0): print("|(%d)+(%d)| = %d" %(num1,num2,-1*(num1+num2))) else: print("|(%d)+(%d)| = %d" %(num1,num2,(num1+num2)))
9b84b384a60379e631f2e709f6fffca7e7275110
huzaifa786/Assignment
/untitled1/sumAndAvg.py
597
3.9375
4
import itertools counter=0 sum=0 opt=int(input('Press 1 for while loop else 2 for for loop',)) if(opt==1): print("For loop running : ") for i in itertools.count(): inp=input('enter :') if (inp=="done"): break inp=int(inp) sum+=inp counter+=1 ...
c054da8096853c5cc404e00773712f004b03bec9
DikranHachikyan/python-programming-20190318
/ex24.py
324
3.875
4
#!/home/wizard/anaconda3/bin/python def sumNumbers(a, b, d = None): if not d: c = a + b else: c = a + b + d return c if __name__ == '__main__': x,y = 10,2 res = sumNumbers(x,y) print(f'{x} + {y} = {res}') z = 7 res = sumNumbers(x,y,z) print(f'{x}+{y}+{z} = {re...
977b1d839716b35029c073e550e3442a57e46382
MehmetCanYildirim/GlobalAIHubPythonCourse
/Final Project/Final Project.py
5,409
3.90625
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 13 19:25:39 2021 @author: Mehmet Can Yıldırım """ points = [] # Creation of the empty list for points. print("Welcome the knowledge competition!") q1 = input("Q1) What is the capital of Turkey?\n Your answer is: ") # First question of the competition. if q1....
b098c0a0be923b9da7fb06633662a8c62789d258
renan-eng/Phyton-Intro
/methods.py
1,633
4.34375
4
spam = ['hello', 'hi', 'howdy', 'heyas'] indice = spam.index('hello') # index é um método que retorna o indice de determinado valor em uma lista print(indice) # o indice de 'hello' é igual a 0 # index retorna o indice onde localizou primeiro o valor procurado nome = ['Roberto', 'Renata', 'Jose', 'Renata'] nomeIndice ...
f70324522f7b848e7a84fab8862307df516aed98
mahmudgithub/Core-python
/python_programming_drive/__pycache__/OOP.PY
8,204
4.125
4
#....................using simple class class user: name='' email='' password='' login=True def login(self): email=input('enter your email:') password=input('enter your password:') if email==self.email and password==self.password: login=True print('...
a805c4b7f53b4d7a625ea513eed59e3825b0ee82
LarmIg/Algoritmos-Python
/CAPITULO 7/Exercicio P.py
555
4.375
4
# Elaborar um programa que leia uma matriz A com dez elementos do tipo cadeia. Construir uma matriz B de mesma dimensão e tipo que a matriz A. O último elemento da matriz A deve ser o primeiro da matriz B, o penúltimo elemento da matriz A deve ser o segundo da matriz B até que o primeiro elemento da matriz A seja o últ...
5c46d8885d331ab78b9abed91e574c6bff39cc7a
dism-exe/bn6f
/tools/misc_scripts/utils/common.py
394
3.65625
4
def bytes_to_word(bytes): # type: (List[int, 4]) -> int or ValueError """ converts a buffer to an integer :param bytes: buffer of 4 elements :return: the buffer as an integer or ValueError if the buffer doesn't contain enough data for a word """ if len(bytes) < 4: return ValueError ...
3e608f5469e019e2a1716f52d4ce8b94142658fb
gylfinn/python
/Assignment 4/armstrong.py
730
3.78125
4
top_num = int(input("Input a number between 0 and 999: ")) for num in range(0, top_num): if num >= 100: tala1 = num // 100 tala2 = (num % 100) // 10 tala3 = (num % 100) % 10 if ((tala1**3)+(tala2**3)+(tala3**3)) == num: print(num) elif num < 10: num**1==num...
fea17aa56dcce1c5cc4f9f94578cf7807fda3e99
ZAKERR/-16-python-
/软件第七次作业/软件162/2016021022杨燕芳/弹弹球.py
1,546
3.703125
4
'''# !/user/bin/python # -*-coding:utf-8-*- author:杨燕芳 date:20181104 func:生成游戏窗体 ''' from tkinter import * import time import random # 生成小球类 class Ball: def __init__(self, canvas, color, b, l): self.canvas = canvas self.b = b self.l = l # 球大小 self.id = ca...
bf0543480c334dd60ec0eb2cf54d4255adc21633
Saengsorn-Wongpriew/6230403955-oop-labs
/saengsorn-6230403955-lab3/problem10.py
277
4.03125
4
possitive = 1 n_list = [] while possitive: n = int(input("Enter an integer: ")) if n >= 0: n_list.append(n) else: possitive = 0 if n_list: average = sum(n_list) / len(n_list) print(average) else: print("empty integers")
e224be49a66bc6a89e4ae312964cee7df5c7d124
orlova-lb/PythonIntro06
/lesson_14/hw.py
827
3.796875
4
""" |345612| """ # 1 2345 * 10 = 23450 + 1 = 23451 def shift_left(number): tmp = number d = 0 amount = 0 while tmp > 0: d = tmp % 10 tmp //= 10 amount += 1 number = number % (10 ** (amount - 1)) * 10 + d return number # 1234 5 ==> 51234 ==> 5 * 10000 =...
e49cde7aeffde54360d7e85d198da8af3ed3b21d
musram/python_progs
/real_python_tutorails/built_in_functions/built_in_functions_example.py
6,488
4.03125
4
if __name__ == "__main__": #The type() function either returns the type of the object or returns a new type object based on the arguments passed. #type(object) numbers_list = [1, 2] print(type(numbers_list)) numbers_dict = {1: 'one', 2: 'two'} print(type(numbers_dict)) class Foo:...
2cb91fafb2ede31858eebda425e65b3674110cda
schlerp/R-Pee-G
/world/world.py
1,542
3.65625
4
import sys class Direction(): up = ('n', 'north', 'u', 'up') down = ('s', 'south', 'u', 'up') left = ('w', 'west', 'l', 'left') right = ('e', 'east', 'r', 'right') def get(self, direction): if direction in self.up: return 'north' if direction in self.down: ...
3991bd554b937741b3885358286cb9f030067937
mattizatt140/Python
/Space Invaders/alien_bullet.py
932
3.875
4
from bullet import Bullet class Alien_Bullet(Bullet): """A subclass of Bullet used exclusively for alien bullets""" def __init__(self, ai_settings, screen, alien): """Construct alien bullet""" # Construct super bullet class super().__init__(ai_settings, screen) # Move ...
1e27c0c414ec0c9c024e372f02f198a8aae184b6
abbeychrystal/CodingDojo_PythonRepo
/_python/python_fundamentals/selectionSort.py
230
3.953125
4
def selectionSort(lst): for i in range(len(list)-2): for j in range(1,i+1,1): if list(i)<list(j): list(i) = list(j) return lst lst = [5,4,3,2,1] print(selectionSort(lst))
577295f27d125a9b4323fcf9864ec59c5cbd069c
sonukrishna/project--Simple-Pygame
/sample_examples/sample4.py
687
3.640625
4
"""creating a snow man """ import pygame import sys def snowman(screen, x, y): pygame.draw.ellipse(screen, white, [35 + x, 0 + y, 25, 25]) pygame.draw.ellipse(screen, white, [23 + x, 20 + y, 50, 50]) pygame.draw.ellipse(screen, white, [0 + x, 65 + y, 100, 100]) pygame.init() black = (0, 0, 0) w...
da6e8bdb17704a8a8cbe862d6db5ff7e34d6514d
mzal/connectCztery
/draw_board.py
1,013
3.84375
4
from static_values import * from graphics import * def draw_grid(win): win.setBackground(background_color) for i in range(1,COL): l = Line( Point(i*(WIN_X)/COL,0), Point(i*(WIN_X)/COL, WIN_Y)) l.draw(win) for i in range(1,ROW+1): l = Line( Point(0, i*(WIN_Y-BASE)/ROW), Point(WIN_X,...
781041223f322f2d42213f2be3e1479a15aa26ff
lbarazza/RSA-simple
/RSA.py
1,127
3.609375
4
# returns: n, e, d def genRSAkeys(p, q): phi = (p-1)*(q-1) # public key e = findcop(phi) d = modinv(e, phi) return p * q, e, d def encrypt(m, e, n): return (m**e) % n def decrypt(k, d, n): return (k**d) % n def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x ...
0e5bf6e07f28567730192f045277a26c0f328ca7
JacobLayton/code-problems
/hackerrank/Python/greedyFlorist.py
560
3.90625
4
# https://www.hackerrank.com/challenges/greedy-florist/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=greedy-algorithms def getMinimumCost(k, c): cost = 0 multiplier = 1 c.sort(reverse=True) for i in range(len(c)): cost += multiplier * c[i] ...
adbf820b31d73a6a126ed0cd536679d15ac408f3
gaberosser/qmul-bioinf
/utils/excel.py
8,493
3.546875
4
import pandas as pd import string from utils import log import xlsxwriter logger = log.get_console_logger() def pandas_to_excel(sheets, fn, write_index=True, **kwargs): """ :param blocks: Dictionary containing the different comparisons to save. Values are pandas dataframes. :param fn: Output file :pa...
10570866ee0c68069003f2c3257df3ac67bfa5b5
FacundoBasualdo/ejercicios-tecnicas
/ejercicio_3.py
596
3.859375
4
print ("") monto = raw_input(" Escriba Total A Pagar: $") print ("") encendido = True while (encendido): metodo_pago = raw_input(" Ponga --> 1 <-- Si Paga Al Contado, --> 2 <-- Para No: ") print ("") if (metodo_pago == "1"): descuento = int(monto) / 10 total_descuento = int(monto) - int(...
a4abf8ee791ed7f9d2315f2fc136cdcf99b0d9b9
froontown/learn_python
/classes/exercise1.py
2,343
4.03125
4
# Make a restaurant class with number of folk served: [X] # Add a number of customers served to the restaurant: [X] # Add a number of customers via a method: [X] # Use an increment method to the number served: [X] # Make a User class with a first and last name: [X] # Make a method that describes the User...
9da0ae2b438a11333c777a359b6609c1ac13bfd6
Baobao211195/python-tutorial
/String/__init__.py
399
3.671875
4
# string processing print("oanh".capitalize()) print("oanh".casefold()) print("oanh".center(1, "d")) print("oanh" * 3 + "van kem") print('oanh' 'van kem') print('pham van oanh'[-1]) print('pham van oanh'[-2]) print('pham van oanh'[-3]) print('pham van oanh'[-3:-1]) print('pham van oanh'[-13:]) print('pham van oanh'[0:]...
86a3bdf0136e369df2ab4f0f8d17875c7f5d974f
nayana09/assesment4.1
/data abstraction.py
550
4.1875
4
#Data Abstraction for hiding the internal details or implementations of a function and showing its functionalities only. from abc import ABC, abstractmethod class Car(ABC): def __init__(self,name): self.name = name def description(self): print("This the description function of clas...
7c6c02c4cdd9ca67614e26c3bbcc4487ca38550d
alixdamman/memento
/python/functions/model_function_5.py
1,320
3.5625
4
# ====== Keyword arguments ====== # # Exercise 5: call function "projection" using keyword arguments # # * change the second call to "projection" by passing one positional argument and one keyword argument # * change the third call to "projection" by passing arguments in reverse order # (Hint: use keyword arguments) ...
217eeae577a1055067fb7b8776d1d3a03033e8c5
colinquirk/colorblind_screen
/ColorBlindness_Screening.py
4,111
3.875
4
"""Code used to quickly test for color blindness. If participants don't score 100% they may be colorblind and should do the full test. To use, simply open and run the code in psychopy. Alternativly, import and run yourself. The main function is run_colorscreen. Pressing 'q' while the program is expecting ...
d4fb5bb28bd5854ef77e87ba0dec821adb0da1ac
ssmith1992/python-elective-spring-2019
/lesson 17/lambda_students.py
594
4.34375
4
""" From the code below create 3 students and add them to a list. sort the list based on the students age. Print out the Students names from the list (use a list comprehension for this) """ class Student: def __init__(self, name, age): self.name = name self.age = age def __repr__(...
6a5cfa3613e713ee6be6286e9d03bef89abe6f45
Sokolnik21/doesHeSingIt
/PhraseSearcher.py
999
3.890625
4
""" Requires: this module checks whether a mentioned phrase is in proper song """ import Parser import SongText # checks whether larger list contains smaller one def contains(small, big): for i in range(len(big)-len(small)+1): for j in range(len(small)): if big[i+j] != small[j]: ...
1d34016e41832d132ca447168437af8dfd9de74e
Kucika14/pallida-exam-basics
/favouriteanimals/favourite_animals.py
2,208
4.1875
4
# The program's aim is to collect your favourite animals and store them in a text file. # There is a given text file called '''favourites.txt''', it will contain the animals # If ran from the command line without arguments # It should print out the usage: # ```fav_animals [animal] [animal]``` # You can add as many comm...
04474df90e3b31ffaef57015930744fcaa880034
dujiaojingyu/Personal-programming-exercises
/编程/1月/1.15/shopping.py
1,416
3.90625
4
goods = [('Iphone',50000),('mac Pro',12000),('alex python',81),('Bike',800),('Starback latte',31)] print('------- 商品列表如下输入序号即可加入购物车 -------') print('温馨提示:输入q即可退出程序!') salary = input('请输入您的工资:') shopping_list = [] if salary.isdigit(): salary = int(salary) while True: for index,item in enumerate(goods): ...
bfcab6e46db9462479f113e66c96ab2509d05912
AdamZhouSE/pythonHomework
/Code/CodeRecords/2310/60636/245056.py
801
3.609375
4
n_root=input().split(" ") n=int(n_root[0]) root=int(n_root[1]) lists=[] for i in range(pow(2,n)): lists.append("*") sources=[] try: while(True): x=input().split(" ") source=[] source.append(int(x[0])) source.append(int(x[1])) source.append(int(x[2])) sources.appen...
bda3b96ceeacca2d35501025f133e3c10bf111d9
omarsalazars/compiler
/lexer/Rules.py
2,069
3.5625
4
from enum import Enum class TokenType(str, Enum): MAIN = "main" IF = "if" THEN = "then" ELSE = "else" END = "end" DO = "do" WHILE = "while" UNTIL = "until" REAL = "real" INT = "int" BOOLEAN = "boolean" READ = "cin" PRINT = "cout" SFLOAT = "signed float" FLOAT ...
049db7684d016d436241358db2b1b0b634c146ea
zxy-zhang/data-visualization
/scatter_squares.py
1,352
3.6875
4
# import matplotlib.pyplot as plt # x_values=[1,2,3,4,5] # y_values=[1,4,9,16,25] # plt.scatter(x_values,y_values,s=200) # #调用了scatter()函数,并且用s设置了绘制图形使用点的尺寸 # #设置图表标题,并给坐标轴加上标签 # plt.title("Square Numbers",fontsize=24) # plt.xlabel("Value",fontsize=14) # plt.ylabel("Square of Value",fontsize=14) # #设置刻度标记大小 # plt....
fff998d5e01bdaf110da604c0a1aee5de8a4598d
yhx0105/leetcode
/04_chazhaohepaixu/06_全排列.py
1,341
3.640625
4
""" 给定一个没有重复数字的序列,返回其所有可能的全排列。 """ class Solution: #有点递归的味道,不断把后面的数前插, #怎么表示不同的元素放第一个呢 #时间复杂度O(n!) # def permute(self, nums): # def backtrack(first=0): # if first==n: # output.append(nums[:]) # for i in range(first,n): # nums[first],nums[i]...
ee616da9ddd66ce1cb9eb60837ddc5fd21411237
charss/time-calculator
/time_calculator.py
2,196
3.859375
4
def add_time(start, duration, day_of_week=''): to_print = '' week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] class time: def __init__(self, hour, minutes): self.hour = int(hour) self.minutes = int(minutes) class StartTi...
98dd58d6746aa647949e81236870a867b8c5b6ab
janniklasrose/diffusion-models
/diffusion/mcrw/transit.py
2,187
3.6875
4
from abc import ABC, abstractmethod import numpy as np class TransitABC(ABC): def __init__(self): self._rng = np.random.default_rng() @abstractmethod def probability(self, dx_i, dx_j, D_i, D_j, P): pass def _crossing(self, decision, dx_i, dx_j, D_i, D_j): dx_j[decision] *= ...
dd9cb6dd58cde1bcf6fb53675afc5405f396b5a8
iCodeIN/data_structures
/hashing/anagram.py
909
4.53125
5
import collections def find_anagrams(dictionary): sorted_string_to_anagrams = collections.defaultdict(list) for s in dictionary: # Sorts the string, uses it as a key, and then appends the original # string as another value into hash table. # sorted actually splits the string into a lis...
5c57b1dc6aef77c270e78789b2ef59018d7c823a
alexthescott/PythonPlayground
/WEEK3 (str, list, bool)/Questions/first_half_question.py
361
3.828125
4
""" first_half_question.py Alex Scott 2020 taken from https://codingbat.com/prob/p107010 Write a function which returns the first half of a string Assume we want the floor (don't include middle character of odd size string) Bonus consideration: Does this function also work for lists? """ def first_half(word):...
f84376f331da55077788c2459cb8c80a4e254efa
saranyashalya/Python
/Hackerrank_exercises_1.py
9,610
3.796875
4
class Rocket: def __init__(self, name, distance): self.name = name self.distance = distance def launch(self): return "%s has reached %s" % (self.name, self.distance) obj1 = Rocket("Rocket 1", "till stratosphere") print(obj1.launch()) class MarsRover(Rocket): def __init__(s...
0e0d922659125fd07d10215276424f3cd8c457bc
showell/elm-py
/tests/testListPerformance.py
2,686
3.6875
4
""" This takes a few seconds to run. It tests performance for List operations. It doesn't do any actual benchmarks; it's really just testing that List doesn't crash due to recursion for large lists. """ import sys sys.path.append('../src') import List import Maybe import Tuple from testHelper import assertEqual a...
36e365dbe265cf257524b4d232ca87efd93eacef
amit-raut/Project-Euler-Python
/pr37/pr37.py
1,145
4.125
4
#!/usr/bin/env python """ The number 3797 has an interesting property. Being prime itself it is possible to continuously remove digits from left to right and remain prime at each stage: 3797 797 97 and 7. Similarly we can work from right to left: 3797 379 37 and 3. Find the sum of the only eleven primes that ...
cdc3ee5efc52eac849a22d7d405c65592590d056
armsky/Preps
/Facebook/phone/Binary Tree - Minimum Depth.py
1,091
3.984375
4
""" Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. """ class Solution(object): # Recursive def minDepth(self, root): """ :type root: TreeNode :rtype: int """ ...
3d96aa85f83af5d2e93615950f63c96d8b1c8f40
sharanyamarineni/competetive-programming
/week3/day1/5sideddie.py
197
3.75
4
import random def rand7(): return random.randint(1, 7) def rand5(): while True: r = rand7() if r < 6: return r print 'Rolling 5-sided die...' print rand5()
17cf3bc4791a90b6bd7467fc34a6a3edc5a996f2
EMalh/Onepoint
/ceasar.py
1,205
4.4375
4
""" Caesar Cipher """ def ceasar_code(plain_text, n_shift): """ A Caesar cipher is a simple substitution cipher in which each letter of the plain text is substituted with a letter found by moving n places down the alphabet. :param plain_text: plain-text message :param n_shift: number of letters to shi...
bd691e0f3d8a10122502ec91af15a621da4ad35f
chanduchowdary/python_projects
/python_strings/sort.py
280
3.875
4
#take input randomly and dislpay it randomly in sorted order """ sample input: red,black,green output:black,green,red """ words_list = input("enter the words with comma separated values:") words = [word for word in words_list.split(",")] print(",".join(sorted(list(set(words)))))