blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d20d83e3811c57dafa56630c2413e727c444ec10 | medamer/cs-module-project-hash-tables | /lecture/fib.py | 306 | 3.53125 | 4 | # 0 1 1 2 3 5 8 13 21 34 55 ...
#
# fib(0): 0
# fib(1): 1
# fib(n): fib(n-1) + fib(n-2)
#
cache = {}
def fib(n):
if n <= 1: return n
if n not in cache:
cache[n] = fib(n-1) + fib(n-2)
return cache[n]
for i in range(100):
print(f'{i:3} {fib(i)}')
"""
def foo(a, x, b):
cache[(a,x,b)] = ...
"""
|
3e65667502f49752e3731b9551442e20ddcfd287 | livneniv/python | /Week 10 - Tuples/assn-10_2.py | 574 | 3.671875 | 4 | fname = raw_input ("Enter file name to be examined: ") #getting the file name from the user
fhand=open(fname)
counts = dict()
for line in fhand:
line = line.rstrip()
if line =='' : continue #guardian pattern (checking if a line is blank)
words = line.split()
if words[0] != 'From' :continue
time = words[5]
hours... |
892b5628d15e7603ac4f91745077b7c2c77027ce | Lalitaeranki/UCI-Work | /06-Python-APIs/2/Activities/11-Ins_WorldBankAPI/Unsolved/Ins_WorldBankAPI.py | 424 | 3.625 | 4 |
# coding: utf-8
# In[2]:
# Dependencies
import requests
url = "http://api.worldbank.org/v2/"
format = "json"
# Get country information in JSON format
countries_response = requests.get(f"{url}countries?format={format}").json()
# First element is general information, second is countries themselves
countries = coun... |
5fc75b9f016f34471e3cfa24113b2703d9799e57 | ssshow16/tetris_ri | /othello/square.py | 829 | 4.125 | 4 | class Square(object):
"""
Represents one square of an othello board.
Instance variables:
value - If a disk is placed, its value, else None
is_valid_move - boolean if the current player can play here
flipped_disks - if the current player plays here,
which disk... |
cb766307ed33ed927bdddfc9f7268cc4c7b0fdc4 | lizhihui16/aaa | /pbase/day19/shili/myinteder.py | 419 | 3.578125 | 4 |
class MyInteger:
def __init__(self,value):
self.data=int(value)
def __int__(self):
'''此方法必须返回整数'''
return self.data
def __float__(self):
return float(self.data)
a1=MyInteger('100')
i=int(a1) #将MyInteger类型转为整数
print(i)
f=float(a1) #a1.__float__()
print(f)
c=complex(a1)... |
ff88055a5ef82696d5e13b35c1e711b032736500 | nelsonmpyana/Espoir333--A6-grade-average-calculator | /calc.py | 331 | 3.90625 | 4 |
n=int(input("Amount of grades entering?: "))
a=[]
for i in range(0,n):
elem=int(input("Enter Dave's grade: "))
a.append(elem)
avg=sum(a)/n
print("Dave grade average",round(avg,2))
for i in range(0,n):
elem=int(input("Enter Sara's grade: "))
a.append(elem)
avg=sum(a)/n
print("Sara's grade average",round ... |
7f72a2798b6b7ef850679f27546c0043eff6ec08 | htutk/python | /mergePdf.py | 3,404 | 4.25 | 4 | #! python3
# mergePdf.py - merges PDF files together to make a single pdf
import PyPDF2, os, sys
if len(sys.argv) < 2:
print("""
To use mergePdf.py,
Enter mergePdf <pdf1.pdf> <pdf2.pdf> ... <pdfn.pdf>.
NOTES:
1. Make sure to include .pdf extension.
2. Merge the files in order give... |
5a0c9b8b5bb0acda50a4298b910522974c1d7729 | PrestonFawcett/Pig_Game | /pig.py | 1,851 | 4.125 | 4 | #!/usr/bin/env python3
""" Pig game written in Python. """
__author__ = 'Preston Fawcett'
__email__ = 'ptfawcett@csu.fullerton.edu'
__maintainer__ = 'PrestonFawcett'
import time
from player import Player
from functions import error
from functions import rearrange
from functions import start_turn
def main():
""" ... |
00753e89471e7a431fb581755336c8494875ce75 | vikramlance/Python-Programming | /hackerRank/day11-2DArrays.py | 1,893 | 4.21875 | 4 | '''
Objective
Today, we're building on our knowledge of Arrays by adding another dimension. Check out the Tutorial tab for learning materials and an instructional video!
Context
Given a 6×6 2D Array, A:
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
We define an hourglass in A to be a subse... |
0bfceb8a70068e598fed045ccb48db716d3acc58 | robertpatrick6/PathfindingMaze | /MazeMaker/maze_creation.py | 6,770 | 3.9375 | 4 | import random
def create_maze(size):
''' Creates a maze within the given grid.
Grid elements are 0s and 1s, with 0s being the path
and 1s being the start_walls '''
GRID_SIZE = size
# Create grid
grid = []
for i in range(GRID_SIZE):
grid.append([])
for j in ... |
fb16cad572a746ca1bb1bfce07e47b71e5ebe0cd | dorbengoose/Python-Challenge | /PyPoll/main.py | 3,770 | 4.4375 | 4 | # # 1 .- Import Modules from Python Library (as in the Classroom)
# #Allows to create the Open to Destination for the Bank.csv File to main.py
import os # As in the Classroom
# # Import Module to be able to read a CSV File in Python save as bank_statement
import csv # As in the Classroom
import col... |
b019d7e94d47f5dd0b983ef74de88adb13f4a283 | Sunflower411/complex-network-course-work | /hw6/Xing An Ass 6/Round6_centrality-measures-for-undirected-networks (1).py | 15,712 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Round 6. Centrality measures for undirected networks
#
# In this exercise, we get familiar with some common centrality measures by applying them to undirected networks (although these measures can all be generalized also to directed networks).
#
# Below, we list and define t... |
646c429ff71aec515083c840a9375a170e153d21 | Kieran-Egan/GlobalHack | /rps.py | 1,138 | 4.1875 | 4 | import random
print("Welcome to Rock Paper Scissors! Type the number that corresponds to the item you want to choose.")
player = input("1 = Rock, 2 = Paper, 3 = Scissors, Shoot! ")
print("Your choice is:")
if player == 1:
print("Rock")
elif player == 2:
print("Paper")
elif player == 3:
print("Scissors")
els... |
2ff8bacfe89d668e90b6cd3bd0304a339ded9c03 | caspar/PhysicsLab | /10_Midterm/least_squares_fit.py | 1,117 | 4.125 | 4 | # Lab 0
# Linear Least Squares Fit
# Author Caspar Lant
import numpy as np
import matplotlib.pyplot as plt
# load csv file
DATA = "MidtermSheet.csv";
measurement, pressure, temperature, uncertainty = np.loadtxt(DATA, skiprows=1, unpack=True, delimiter=',');
# plot temperature vs. pressure + error bars
plt.ylabel("Pr... |
e3c5b84cf361f8b972431ab7a4747506c9ede2ce | bssrdf/pyleet | /T/TaskScheduler.py | 1,936 | 3.984375 | 4 | '''
Given a characters array tasks, representing the tasks a CPU needs to do, where each
letter represents a different task. Tasks could be done in any order. Each task is
done in one unit of time. For each unit of time, the CPU could complete either one
task or just be idle.
However, there is a non-negative integ... |
bbc89cd0cc9700d89cb9eab55afa8e340bdbc814 | alexandraback/datacollection | /solutions_2464487_1/Python/xmk/circle.py | 904 | 3.515625 | 4 |
f=open("input")
ff=open("output", "w")
readint=lambda :int(f.readline())
readintarray=lambda :map(int, f.readline().split())
T=readint()
def slow(r,t):
s=n=0
while True:
s += 2*(r+2*n) +1
if s<=t:
n+=1
else:
return n
def isqrt(x):
if x < 0:
raise Val... |
f6264000ce5b47699b3cb627f8548ccbb14d5184 | mulays/PythonPractise | /PythonPractise/RegEx.py | 705 | 3.78125 | 4 | import re
# Refered link : http://www.thegeekstuff.com/2014/07/python-regex-examples
string = "this is my new name \nplate"
stringreg = r"this is my new name \nplate"
print string
print stringreg
re.match(r'dog','dog cat dog mouse dog')
match = re.match(r'cat','dog cat dog mouse dog')
print match
match... |
d17b9895fe5c0d05370dae7c23251c8c899223c7 | godringchan/Python_base_GodRing | /old/异常的处理.py | 267 | 3.515625 | 4 | class BigError(BaseException):
pass
def big():
b = input("int")
b = int(b)
try:
if b > 100:
raise BigError
else:
print("right")
except BigError:
print("cuowu")
if __name__ == "__main__":
big() |
5e0ba62968c405d003d2dc67c1141206c6887c4f | tharunsai241/python_ds | /selection_sort.py | 693 | 3.953125 | 4 | print("selection sort")
ar=[176,-272,-272,-45,269,-327,-945,176] #->[0,1,6,64,12]->[0,1,6,12,64]
#swap 1st element ->last
#increment counter
#considering the first element itself min index as it is sorted
for i in range(len(ar)):
min=i #we assumed the first element is in right place(sorted)
#print(min)
#t... |
a413996c648729400a710513c30e381f0b081242 | Lishitha/python-projects | /ifexmpl.py | 390 | 3.953125 | 4 | """num = int(input("enter a number"))
if num < 0:
print("nmbr is negtv")
elif num == 0:
print("nmbr is zero")
else:
print("nmber id postv")"""
menu = ["meals","biriyani","ghee rice"]
print(menu)
order =int(input("menu number : "))
if order == 1:
print("meals")
elif order == 2:
print("biriyani")
el... |
d2f6c5b3932a3bc65cc50eb30bbee08e117705ba | zarkle/code_challenges | /fcc_pyalgo/03_largest_sum.py | 801 | 3.9375 | 4 | """
Largest Sum
Take an array with positive and negative integers and find the largest continuous sum of that array.
https://leetcode.com/problems/maximum-subarray/
"""
def largest_sum(nums):
if not nums:
return
largest = temp = nums[0]
temp = nums[0]
for num in nums[1:]:
if temp + num... |
e754afd1fa6bde7bebad7c632da837e626230d46 | keepangry/ai_algorithm | /ProbabilisticGraphicalModel/MaximumEntropy/character_tagging.py | 1,323 | 3.546875 | 4 | # encoding: utf-8
'''
@author: yangsen
@license:
@contact: 0@keepangry.com
@software:
@file: character_tagging.py
@time: 18-10-2 下午1:03
@desc:
迈向 充满 希望 的 新 世纪 —— 一九九八年 新年 讲话 ( 附 图片 1 张 )
==>
迈/B 向/E 充/B 满/E 希/B 望/E 的/S 新/S 世/B 纪/E —/B —/E 一/B 九/M 九/M 八/M 年/E 新/B 年/E 讲/B 话/E (/S 附/S 图/B 片/E 1/S 张/S )/S
... |
135e79eeba26824596c4524b22c127ce2d76080b | davychiu/brainfood | /project_euler/problem7.py | 302 | 3.765625 | 4 | def sqrt(n):
return n**0.5
def isprime(n):
for x in range(2, int(sqrt(n))+1):
if n % x == 0:
return False
return True
primes = [2,3,5,7,11,13]
n = max(primes) + 2
while len(primes) < 10002:
if isprime(n):
primes.append(n)
n = n + 2
print primes[10000]
|
55d38a18dd2fa1aa5e7209ca72c06baf85299fae | Darshnadas/100_python_ques | /DAY13/day13.49.py | 581 | 4.1875 | 4 | """
Define a class named Shape and its subclass Square. The Square class has an init function which takes
a length as argument. Both classes have a area function which can print the area of the shape where
Shape's area is 0 by default.
"""
class Shape:
def __init__(self):
pass
def area(self):
... |
ceebe6d12081a58b9854972b9848a315575a443e | saltosaurus-zz/PUMA | /Functions/SLDTperceptron.py | 1,687 | 3.859375 | 4 | ## A single-layer, dual-target perceptron
### INPUT: numAttributes is the number of features we're looking at
# Examples is a list of feature vectors
# Targets is a list of binary (0 or 1) target values for the given examples
### OUTPUT: A list of weights that has a length equal to numAttributes
im... |
d4f879560088a06b251b25eb95eba9aa137f6bb1 | niranjan-nagaraju/Development | /python/codechef/collatz.py | 282 | 3.671875 | 4 | #!/usr/bin/python
def collatz(n):
len = 0
while n != 1:
if (n & 1):
n = 3*n + 1
else:
n = n / 2
len = len + 1
return len+1
max = 0
for i in range(1,1000001):
num = collatz(i)
if (num > max):
max = num
maxnum = i
# print i, num, max, maxnum
print max, maxnum
|
6fff9f57b22b14a265bf6d347d6e45a6c6332700 | JakeHuneau/ProjectEuler | /PE55.py | 632 | 3.5625 | 4 | def check_palindrome(st):
return str(st) == str(st)[::-1]
def add_reverse(i):
return i + int(str(i)[::-1])
def check_lychrel(i, iterations):
lychrel = True
i = add_reverse(i)
for n in range(iterations):
if check_palindrome(i):
lychrel = False
bre... |
bfcadc65357ebbb36757e88777ace60d3c5f339d | Einar-Storvestre/min-python | /kem e best .py | 1,513 | 3.5 | 4 | import turtle
wn = turtle.Screen()
bird = turtle.Turtle()
bird.speed(13)
bird.pensize(4)
bird.color("black")
bird.setpos(-75, 0)
bird.fillcolor("pink")
bird.begin_fill()
for i in [0, 1, 2]:
bird.circle(30, 360)
bird.forward(1)
bird.forward(174)
bird.left(120)
bird.end_fill()
bird.penup()
bird.forward(... |
db0072f363dda67b8a66117c8e3444c06b4ed0ac | Devlan/learn_python | /double_num().py | 169 | 3.640625 | 4 | # coding: utf-8
def double_num():
j =1
while j <= 100:
if j%2 == 0:
print(j)
j +=1
else:
j += 1
|
2f494fc42df03821cda5598c6fed49a10253354d | FernandoPicazo/sfdc_api | /sfdc_api/utils/string_utils.py | 241 | 3.5 | 4 | import re
def camel_to_snake_case(in_string):
regex_str = r"(.+?)([A-Z])"
def match_to_snake(match):
return match.group(1).lower() + '_' + match.group(2).lower()
return re.sub(regex_str, match_to_snake, in_string, 0)
|
1049a5173800efb9d7777eab12d9ba9c306b1788 | neeraj-haresh-harjani/Python-Image-Classification | /Image_Classification.py | 11,628 | 3.59375 | 4 | import numpy as np
from sklearn.datasets import fetch_openml
#mnist_784 is the dataset of images that are 28x28
#Bunch is a dictionary containing objects, key-data container pair
mnist = fetch_openml('mnist_784')
#data table is 2 by 2 array with 70,000 images, each image is represented by a
#row of 784 numbers, why ... |
cc6eed1656c5f7fe6e675aa79af467b33ac7dfbf | Greensly/InfoGeneral | /Python Exercise/Exercises N°1/longitudCadena.py | 454 | 3.96875 | 4 | matriz = []
filas = int(input("Cantidad de Filas: "))
Columnas = int(input("Cantidad de Columnas: "))
for i in range(filas):
matriz.append([0]*Columnas)
for x in range (filas):
for y in range(Columnas):
matriz[x][y]= int(input("Ingrese número para fila: [%i] columna [%i]"%(x,y)))
print (matriz)
print... |
255d7a66f4b37947bd99e0ab8515898b72b6e77f | meghnaraswan/PythonAssignments | /Ch4_Strings/palindrome2.py | 679 | 4.21875 | 4 | #palindromes
import string
#get user input
original_str = input("Input a string: ")
#process string for plaindrome check
#make string lowercase
modified_str = original_str.lower()
#remove punctuation and whitespace
bad_chars = string.punctuation + string.whitespace
for char in bad_chars: #iterate over bad characte... |
919d34d7ba37773c9010445fea6e9d77d073c41f | Pau1Robinson/asteroids | /main.py | 4,386 | 3.71875 | 4 | #!/usr/bin/env python3
'''
###########################
# #
# PyGame Asteroids #
# #
###########################
'''
import pygame
import asteroids_var
import asteroids_classes
#### Set everything up ####
# initialise pygame
pygame.init()
#Define... |
353c79d58ce0f80691b93ea06445b7e8ac8c5952 | jmachuca131281/Python | /pythonProject/algoritmo4.py | 255 | 4.1875 | 4 | caracter = str(input(print("Ingrese un caracter: ")))
if "a" == caracter or "e" == caracter or "i" == caracter or "o" == caracter or "u" == caracter:
print("El carácter ingresado es Vocal")
else:
print("El carácter ingresado NO es una vocal")
|
a4e9a651ca5c2140249d55b2b94e82e81ad9653e | jfgr27/Decision-Tree-Assignment | /eval.py | 9,241 | 3.890625 | 4 | ##############################################################################
# CO395: Introduction to Machine Learning
# Coursework 1 Skeleton code
# Prepared by: Josiah Wang
#
# Your tasks:
# Complete the following methods of Evaluator:
# - confusion_matrix()
# - accuracy()
# - precision()
# - recall()
# - f1_score(... |
3f1b1a66f0dd81481b450284fe218176a01b8080 | JacobAMason/DnD | /BinaryEncodings.py | 1,450 | 3.53125 | 4 | # BinaryEncodings.py
# Below are some Binary encodings for various client/server interactions
import re
class BinaryEncodings:
"""
returns True or False based on whether or not data is one of the binary encodings.
"""
def __init__(self):
self.DISCONNECT = bytes("DIS", "utf-8")
self.CONN... |
107e7c06cc78dba43eec43594b0828a78afaa088 | nandadao/Python_note | /note/download_note/first_month/day16/exercise02.py | 521 | 4.125 | 4 | # 练习1:使用迭代思想,获取元组中所有元素("a","b","c")
tuple01 = ("a", "b", "c")
iterator = tuple01.__iter__()
while True:
try:
item = iterator.__next__()
print(item)
except StopIteration:
break
# 练习2:使用迭代思想,获取字典中所有记录("a":1,"b":2,"c":3)
dict01 = {"a": 1, "b": 2, "c": 3}
iterator = tuple01.__iter__()
while... |
9e5e7c3a4ebae93fb0337ad9bac489c04c22b1bd | whitebeard4708/MiniProjectCZ1003 | /Pandas v2.py | 3,064 | 3.796875 | 4 | import pandas as pd
from pandas import DataFrame
from load_data import *
infocan = infocan.set_index('Canteen')
df = df.set_index(['Canteen'])
#takes in foodtype = ['Food1','food2' etc], pricerange = [lower, higher as floats/int], the search term
# rating = int(1 to 5) or 0 if not specified
def searchfood(food... |
6ac203950aa85af86763098637af1adadb4b5449 | rogeriosilva-ifpi/teaching-tds-course | /programacao_estruturada/20192_166/Bimestral2_166_20192/Parte_1/Klebson e Izequiel/IPVA.py | 502 | 3.890625 | 4 | v_atual = int(input('Digite o valor atual do veículo: '))
ano_fabricacao = float(input('Digite o ano de fabricação: '))
ano= 2020 - ano_fabricacao
if ano <5:
v_fin = v_atual * (2.5/100)
print('é o valor com IPVA a ser pago',v_fin)
elif ano == 5 and ano <11:
des = v_atual * (15/100)
print(des,'é o valor... |
32b615f1d5e11c68d947a3bf96c7e23bc55455b1 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2529/60608/241229.py | 526 | 3.8125 | 4 | def swap(a, b):
tem = array[a]
array[a] = array[b]
array[b] = tem
def func9(start, end):
if start == end:
item = int("".join(array[:]))
if item & (item - 1) == 0:
flag[0] = "true"
else:
for index in range(start, end):
swap(index, start)
f... |
1482e6d12e8fd8898b5f624c4a07654e5def740f | young24601/leetcode | /archive pre 2021/013. Roman to Integer.py | 1,163 | 3.78125 | 4 | #13. Roman to Integer
#Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
#use similar strategy to #12
romanvalues = ["M", "CM", "D", "C... |
f6fdd2df57892d1eaebdad5567bb87bdb0c75943 | AartiBhagtani/Algorithms | /recursion/sort_array.py | 389 | 3.65625 | 4 | from sys import stdin
n = int(stdin.readline())
y = [int(x) for x in (stdin.readline().split())]
def rec_sort(arr):
if len(arr) == 1:
return
temp = arr.pop()
rec_sort(arr)
insert(arr, temp)
def insert(arr, temp):
if(len(arr) == 0 or arr[-1] <= temp):
arr.append(temp)
return
temp2 = arr.po... |
8447c6afee790c022be93a0d947c679a82bf1491 | WangYue7477/Python3Learn | /Base/SortedLearn.py | 352 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/10/11 23:35
# @Author : WangYue
# @File : SortedLearn.py
# @Software: PyCharm
l = [21,54,-98,32,-5]
print(sorted(l))
print(sorted(l,key=abs))
name = ['bob', 'about', 'Zoo', 'Credit']
print(sorted(name))
print(sorted(name,key=str.lower))
print(sorted(n... |
1ad61adad79cb2e5c64106daf7ee4597cbc000b4 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/gmdnom011/question4.py | 3,294 | 4.0625 | 4 | # Program to find all palindromic primes in a given range
# Nomsa Gamedze
# 7 May 2014
import sys
sys.setrecursionlimit (30000)
import math
def reverse_word(word, word2):
if len(word2) < len(word):
x = len(word) - len(word2) - 1
word2.append(word[x])
reverse_word(word, word2)
... |
ff517b4c477e7804891df08606d1a025c3a929ac | jvalen92/Analisis-Numerico | /SolucionDeSistemasDeEcuaciones/tareas/grajales_alzate/matriz.py | 987 | 3.609375 | 4 | import numpy as np
class MatrizUtilities:
# Libreria para realizar calculos cientificos eficientes.
def __init__(self):
pass
def get_matriz_aumentada(self, A, b):
"""
Retorna la matriz aumentada Ab.
"""
_b = np.array(b, dtype=float)
_A = np.array(A, dtype=floa... |
d2784e5819e4b446fab0b7a7bd246bf1da4ae8ef | saiswaruprath/PYTHON | /half.py | 255 | 3.875 | 4 | hrs = input("Enter Hours:")
rate = input("Enter Rate:")
h = float(hrs)
r = float(rate)
def computepay(h,r):
if h == 40:
return h * r
elif h > 40:
return (40 * r + (h-40) * 1.5 * r)
p = computepay(h,r)
print("Pay",p)
|
387b8f42674dcf41df9a110c2ded1ed1fc215e4b | Sidharth4032/CSCI-1100 | /HW/HW06/hw6Part1.py | 5,849 | 4.125 | 4 | """
Homework 6 Part 1
The purpose of this program is to read the name of two files: the first containing a dictionary of words and the second containing a list of words to autocorrect. The program will go through the list of words of the input file and decide whether the word preexists in the dictionary file, a letter ... |
777e60fd4bffd3938c6ab62ac21d5f310c8855ec | Madhuram-S/python-challenge | /PyParagraph/main.py | 1,970 | 4.0625 | 4 | # task is to create a Python script to automate the analysis of any such passage using these metrics. Your script will need to do the following:
# 1. Import a text file filled with a paragraph of your choosing.
# 2. Assess the passage for each of the following:
# 1. Approximate word count
# 2. Approximate sentence co... |
75e967620a4d3d60563d4178262231ec334b3dc3 | LeaneTEXIER/Licence_2 | /S3/Codage/TP2/Answers2(Tp2).py | 14,632 | 3.96875 | 4 | ##TEXIER Léane
##Groupe 1
import struct
#Question 1:
#La procédure print imprime les nombres entiers en base décimale.
#Le format d'impression {:x} imprime les nombres entiers en base hexadécimale avec les lettres en miniscules.
#Le format d'impression {:X} imprime les nombres entiers en base hexadécimale avec les le... |
b29641c98a73b2c7a44a4045f95ce2af2d8dcd3b | cgsarfati/CodingChallenges-Insertion-Sort | /insertionsort.py | 1,386 | 4.28125 | 4 | """Given a list, sort it using insertion sort.
For example::
>>> from random import shuffle
>>> alist = range(1, 11)
>>> shuffle(alist)
>>> insertion_sort(alist)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> shuffle(alist)
>>> insertion_sort(alist)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> shuf... |
76dfab596528e9f7f61031cbd7a917ac001429c0 | borko81/python_fundamental_solvess | /examples/10Mach2019_1/HelloFrance.py | 1,708 | 4.25 | 4 | '''
Create a program that calculates the profit after buying some items and selling them on a higher price.
In order to fulfil that, you are going to need certain data - you will receive a collection of items and
budget in the following format:
{type->price|type->price|type->price……|type->price}
{budget}
The prices f... |
4d35185ba390bb1602cbf732c77d31bcf02cd9d7 | Cuick/traversing | /shared/utils/random_pick.py | 1,878 | 3.65625 | 4 | # -*- coding:utf-8 -*-
"""
created by server on 14-7-16上午10:25.
"""
import random
import copy
def random_pick_with_weight(items):
"""
根据权重获取随机item
:param items: {1:50, 2: 50, ...}
1:id
50:权重
:return id list:
"""
pick_result = None
random_max = sum(items.values())
x = random.ran... |
0cf2a7db2a61af66d5bf0e52b6c287d8216c3cfa | utsav8670/spychat | /main.py | 1,375 | 4.0625 | 4 | print"hello buddy"
print"let's get started"
spy_name = raw_input(" what is your spy name?? ")
if len(spy_name) > 2:
print "welcome " + spy_name
spy_salutation = raw_input("what should i call you(mr. or ms. )?")
if spy_salutation == "mr." or spy_salutation == "ms.":
spy_name = spy_salutation + " " + ... |
b5b66795a67f8336fb8658cc361a0937d86ac112 | 10Jack2/lucky_unicorn | /11_number_checker.py | 828 | 4.34375 | 4 | # sets the error statement for the if statement to follow
error = "please enter a whole number between 1 and 10\n"
# keeps the if statement looping until an appropriate answer is entered
valid = False
while not valid:
# This try statment makes it so the program does not crash if a float is entered rather the... |
57a341136fa91d90c17748dc237229c3034e12e9 | isaquemelo/contests | /Lista 1 - Aquecimento e revisão de ED @ ATAL2020.2/URI 2049.py | 276 | 3.734375 | 4 | instanceCounter = 1
while True:
signature = input()
if signature == '0':
break
number = input()
if instanceCounter != 1:
print()
print("Instancia", instanceCounter)
if signature in number:
print("verdadeira")
else:
print("falsa")
instanceCounter += 1
|
ea07922666eeaefa247a36580d8ed8c33fcd34d0 | rasithasreeraj/python | /abstract class/Multiple Inheritance.py | 1,164 | 4.3125 | 4 | class Water_living:
def __init__(self, is_water, name):
self.name = name
self.is_water = is_water
class Land_living:
def __init__(self, is_land, name):
self.name = name
self.is_land = is_land
class Amphibian(Water_living, Land_living):
def __init__(self, name, is_water, ... |
4a48189ea702f9b763fd8bf2c7324cbfb0aed022 | vendulabezakova/pythonProject1 | /main.py | 4,396 | 3.71875 | 4 |
"""item = {"title": "Čajová konvička s hrnky", "price": 899, "inStock": True}
item["price"] = 929
print("Název položky je " + item["title"] +"." + "Jeho cena je " + str(item["price"]) + " Kč.")
print(f"Cena položky je {item['price']} Kč.")
item["weight"] = 0.5
if "weight" in item:
print(f"Hmotnost je {item['weight... |
d5a6842a78c14e29ad58a9ce25d1986f2da1a07c | NTR1407/python | /Clases/Caja.py | 526 | 3.890625 | 4 | class Caja:
def __init__(self,largo,alto,ancho):
self.largo = largo
self.alto = alto
self.ancho = ancho
def perimetro(self):
return self.largo * self.alto * self.ancho
print("Hola, a continuacion calcularemos el perimetro de una caja.")
largo = float(input("Ingrese el largo de ... |
024b3e43e7555dda42d85ae322596cd5a674a29f | jerrizzy/auto-messenger | /silly.py | 4,372 | 4.0625 | 4 | import random
import words
import datetime
import time
import threading
import schedule
# section 1
def silly_string(nouns, verbs, names, templates):
# Choose a random template.
template = random.choice(templates)
# We'll append strings into this list for output.
output = []
# Keep track of whe... |
b350e74105ae8a3abb05f7109ee28a69e1615b64 | AlexeyBazanov/algorithms | /sprint_4/odd_mapping.py | 657 | 3.84375 | 4 | import sys
def is_odd_equal(str1, str2):
map1 = {}
map2 = {}
str1_len = len(str1)
str2_len = len(str2)
if str1_len != str2_len:
return False
for i in range(str1_len):
let1 = str1[i]
let2 = str2[i]
if let1 in map1 and map1[let1] != let2:
return Fa... |
8ad32135505e72cc2faf826853e250deda5d6252 | finndai/jianzhioffer | /Singleton.py | 1,023 | 3.765625 | 4 | # -*-coding:utf-8-*-
# 1.使用__new__方法实现
class Singleton1(object):
def __new__(cls,*args,**kwargs):
if not hasattr(cls,"_instance"):
cls._instance = object.__new__(cls,*args,**kwargs)
return cls._instance
class TestClass()
a = 1
# 使用装饰器
def Singleton2(cls,*args,**kwargs):
instanc... |
5573525323f85b1f00ece7acfe85376386d9b9a4 | bharatanand/B.Tech-CSE-Y2 | /applied-statistics/lab/experiment-1/experiment1.py | 3,661 | 3.640625 | 4 | # EXPLANATION:
# The dataFrame has the following fields:
# Name, Marks, CGPU & Quality of Assignment
# The Name field is of Nominal datatype since each record is a nominee of the field. Mode can be found out.
# The Marks field is of Ordinal datatype since it can be sorted and comparison operations can be performed. ... |
ccfda18329956ae35ec92e3d4a938569ac6884c9 | jshk1205/pythonPractice | /10987.py | 192 | 3.65625 | 4 | text = list(str(input()))
count = 0
for i in range(0, len(text)):
if text[i] == 'a' or text[i] == 'e' or text[i] == 'i' or text[i] == 'o' or text[i] == 'u':
count += 1
print(count) |
208ac09d36f8cccdadbc24fa57826c80c8232a6d | charlysl/MIT-6.009-Python-Self-Learning | /tutorials/tutorial_3/lab.py | 2,027 | 4.09375 | 4 | """
Data structures:
----------------
music := list of "genomes", each of which is a list of integers in [0,1]
music is therefore a list of lists of integers
likes := list of song_id integers corresponding to songs (genomes) in music
dislikes := same as above
"""
def next_song(likes, dislikes, music):
# play the... |
d75765cdd06ad98b09bc91a4299152e5f067059c | prathammehta/interview-prep | /MaximumSumIncreasingSubSequence.py | 570 | 3.9375 | 4 | # https://www.geeksforgeeks.org/printing-maximum-sum-increasing-subsequence/
def get_subsequence(arr):
l = len(arr)
max_sum = [arr[i] for i in range(l)]
max_sum_seq = [[arr[i]] for i in range(l)]
for i in range(1,l):
max_value = 0
max_index = 0
for j in range(0,i):
if arr[j] < arr[i] and max_value < ma... |
9d47e4d07855501b08d524d9db2c15d3921318a7 | artodeschini/First-steps-in-Python | /variables.py | 73 | 3.65625 | 4 | a = 5
b = 6
c = 7
print(' {0} + {1} + {2} = {3} '.format(a,b,c, a+b+c) ) |
bc0f0f9629f5fa2c482b60e69fca49f59e97998f | febinv/DS_ALGO | /checkstringpermutation.py | 217 | 3.984375 | 4 | def checkpermutation(str1,str2):
if len(str1)!=len(str2):
return False
else:
return sorted(str1)==sorted(str2)
print(checkpermutation('febin','nibef'))
print(checkpermutation('febi','ibef'))
|
ed5ec78e4280558316d359219c4a759e635837b0 | CowFu/GoatHouse_Bot | /cards.py | 1,451 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 26 18:10:21 2018
@author: spaeh
"""
import random
class Cards:
def __init__(self):
self.newDeck()
self.hands = []
self.players = []
def newDeck(self):
values = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q... |
38a54b3d4f9dfe5a301c6a2260da5399593fd26b | Emerson53na/exercicios-python-3 | /035 Análise Triângulo.py | 547 | 3.75 | 4 | n = 's'
while n == 's':
print('=-'*20)
print(' \033[33m Analiser de triângulo\033[m')
print('=-'*20)
s1 = float(input(' Primeiro segmento: '))
s2 = float(input(' Segundo segmento: '))
s3 = float(input(' Terceiro segmento: '))
if s1 < s2+s3 and s2 < s3+s1 and s3 < s1+s2:
... |
675d199a35673fd590a8582f5f2960c8ffbb32a1 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/prime-factors/e2d8b0ef712b435e887d846f6b67b5e2.py | 267 | 3.671875 | 4 | def prime_factors(number):
result = []
factor_test = 2
while number > 1:
if number % factor_test == 0:
result.append(factor_test)
number /= factor_test
else:
factor_test += 1
return result
|
2332a18e0c9d5e800fd1c346a680164bb0ed53c2 | TrejoCode/python | /03-loops/loops.py | 478 | 3.65625 | 4 | """
Bucle FOR
continue: Salta el valor
break: Rompe el ciclo, finaliza
"""
def run():
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
for letra in "palabra":
print(letra)
for x in range(6):
print(x)
else:
print("Finally finished!")
f... |
7e27684984b844b9295cdf260a2e9226f4986131 | LPetrova/Python | /Saturday_task/sum_of_evens.py | 227 | 4 | 4 | n = input('Enter n: ')
n = int(n)
start_number = 1
sum = 0
while start_number <= n:
if start_number % 2 == 0:
print(str(start_number) + ' is even' )
sum = sum + start_number
start_number += 1
print(sum) |
01b10ad3d3f4b181a2c6dc8d8b9c5314aee8d9aa | kimsungbo/Algorithms | /백준/유니온파인드/1976_여행가자.py | 732 | 3.609375 | 4 | # 1976 여행 가자
# 유니온 파인드로 두 정점이 연결되어 있는지 확인
cities = int(input())
travel = int(input())
parents = [i for i in range(cities+1)]
def Find(x):
if x == parents[x]:
return x
else:
y = Find(parents[x])
parents[x] = y
return y
def Union(x, y):
x = Find(x)
y = Find(y)
... |
f6ee0d2cb5369fe65fa505fdc8186465492273d1 | luizfmgarcia/uctp_ufabc | /uctp_ufabc/src/uctp.py | 51,584 | 3.59375 | 4 | # UCTP Main Methods
import objects
import ioData
import random
# Set '1' to allow, during the run, the print on terminal of some steps
printSteps = 0
#==============================================================================================================
# Create the first generation of solutions
def start(s... |
a2aa369bfa01c7d624e218b27557229d1b06ae31 | myf-algorithm/Leetcode | /Huawei/99.自守数.py | 202 | 3.640625 | 4 | while True:
try:
a, res = int(input()), 0
for i in range(0, a + 1):
if str(i ** 2).endswith(str(i)):
res += 1
print(res)
except:
break |
1bfb82d2f12f93926611a622d08054d9cbac9d3c | brayanjav28/brayanjav28.github.com | /Escritorio/Manipulación de imagenes - Python/codigo05.py | 306 | 3.75 | 4 | from time import time
valor = input ('valor:')
palindromo = 'Es palindromo'
tiempo_inicial = time()
for pos in range(0, len(valor)//2):
if valor[pos] != valor[-(pos + 1)]:
palindromo = 'No es palindromo'
break
tiempo_final = time()
print(palindromo)
print('tiempo:', tiempo_final - tiempo_inicial) |
491fe172789ea0017ebce97c780c992feeb4dca2 | RobertNguyen125/PY4E | /ex_06_string/1_Banana.py | 411 | 3.96875 | 4 | # fruit = 'banana'
# letter = fruit[1] # the result is a because python starts counting from 0
# print(letter)
'''fruit = 'banana'
length = len(fruit)
last = fruit[length]
print(last)'''
# this is wrong as there is no banana with index 6 because Python
#start counting from 0 - 5
fruit = 'banana'
length = len(fruit)
pr... |
aa8fbe17326e9aa3bb5b96b2da6edc64f8e6d457 | Aasthaengg/IBMdataset | /Python_codes/p02392/s854074606.py | 118 | 3.71875 | 4 | a = raw_input().split()
x = int(a[0])
y = int(a[1])
z = int(a[2])
if x < y and y < z:
print "Yes"
else :
print "No" |
a0dde5a2669101289dfff1943acec326a42a16d5 | kklove0502/JDTempRepository | /JD_FactorFactory01/tools/compute.py | 576 | 3.53125 | 4 | import numpy as np
def computeCorrelation(x,y):
"""
计算功能函数,计算简单线性回归相关系数的函数
:param x,y: series,计算相关系数的两个序列
:return: r:float,相关系数
"""
import math
xBar = np.mean(x)
yBar = np.mean(y)
SSR = 0.0
varX = 0.0
varY = 0.0
for i in range(0,len(x)):
diffXXbar = x[i] - xBar
... |
2363bf98712cf942e28ebbac29509c3a210bd432 | gabriel-tavares/python-exercicios | /lista I/exercicio-02.py | 523 | 3.9375 | 4 | #Escreva um programa que leia um valor em metros e o exiba convertido em milmetros
print 'Exerccio-02'
print ''
print 'Converso de Metros em Milmetros'
metros = raw_input('Metro(s): ')
if not metros:
print 'Campo em branco, por favo digite de novo'
elif ',' in metros:
print 'Use o . (ponto) como separador de... |
470c14c98ce7578a4c47539a2266f7e1e7c16b1b | jainsiddharth99/Basic-Coding-Problems | /reversestring2.py | 787 | 4.15625 | 4 |
def reverse(s):
str = ""
for i in s:
# here str=i+str means all elements in s are added in way
# where we add elements in the beginning
# so first g is inserted, than e, then e, thek k .......
#if it was str +i then elemnt is added in back
str =i+str
return ... |
d8425d37ca8aa56303b185ea9dc66b40abc79877 | jeff-diz/coregistration_project | /count_files.py | 494 | 3.5625 | 4 | import argparse
import os
def count_subdir_files(src_dir):
pairs = os.listdir(src_dir)
for p in pairs:
files = os.listdir(os.path.join(src_dir, p))
if len(files) > 1:
print('{}: {}'.format(p, len(files)))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('src_dir'... |
d8eb83c84a0a87d48fc66ae8da57159664871e60 | ogerasymenko/sample | /My_Py_Code/triangle.2.py | 288 | 3.96875 | 4 | print()
s = ''
for i in range(1, 6):
s += str(i)
s += ' '
print (s)
print()
j = ''
for i in range(1, 6):
j += str(i)
j += ' '
print (j)
print()
n = int(input('Введите n: '))
num = ''
for i in range(1, n+1):
num += str(i)
num += ' '
print(num) |
5da622d01c0f231eed76301ef9cb559dbdc3149d | HegnerCarvalho/algoritmos | /Algoritmos/zzz.py | 347 | 3.921875 | 4 | idade=input("Digite sua idade:")
idade=int(idade)
if idade>=18:
print("Você é maior.")
print("Entrada permitida...")
else:
print("Menor detectado...")
print("Entrada negada!")
print('Fim')
if "Rafael"=="rafael":
print("Letras maiúsculas não importam")
else:
print("Letras maiúsculas são diferen... |
5aea98f3fb31f9f9beb8bf9b6b42548096742c09 | lfteixeira996/Coding-Bat | /Python/String-1/make_abba.py | 695 | 4.125 | 4 | import unittest
'''
Given two strings, a and b, return the result of putting them together in the order abba,
e.g. "Hi" and "Bye" returns "HiByeByeHi".
make_abba('Hi', 'Bye') -> 'HiByeByeHi'
make_abba('Yo', 'Alice') -> 'YoAliceAliceYo'
make_abba('What', 'Up') -> 'WhatUpUpWhat'
'''
def make_abba(a, b):
ret... |
13a391ec62029ac52ed2f19110ef60114210fd1b | jedzej/tietopythontraining-basic | /students/barecki_andrzej/lesson_02_flow_control/L3_Knight_move.py | 801 | 3.640625 | 4 | # Chess knight moves like the letter L. It can move two cells horizontally and one cell vertically,
# or two cells vertically and one cells horizontally. Given two different cells of the chessboard,
# determine whether a knight can go from the first cell to the second in one move.
# The program receives the input of f... |
8250eadeaffdb192f60877616fae8948f96fcf81 | KIMJINMINININN/Python | /Pandas/source/Basic/test15.py | 571 | 3.578125 | 4 | import pandas as pd
exam_data = {'이름' : ['서준', '우현', '인아'],
'수학': [90, 80, 70],
'영어' : [98, 89, 95],
'음악' : [85, 95, 100],
'체육' : [100, 90, 90]}
# df.set_index('이름', inplace=True)
df = pd.DataFrame(exam_data)
print(df)
print('\n')
# 특정 열을 index로 만들어주기
ndf = df.se... |
c1a052769236ebcfbc2daf1b3d41be47e1bdf57d | marikaSvensson/Knightec | /pythonProgs/code170515/mainSubsets_Permutations_Combinations.py | 208 | 3.75 | 4 | # prime
def is_prime(n):
for i in range(2,n):
if n % i == 0:
return False
else:
return True
n = 21
a = []
for i in range(2,n):
if (is_prime(i)):
a.append(i)
print a
|
d5ef95a411e9c7463712fe8ae5d5150b3b540652 | maxstrano/jpmorgan-simplestocks | /main.py | 13,225 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Massimo Strano, PhD
# NOTES:
# - Requires python 3
# - There were ambiguities in the provided formulae.
# - I made a number of assumptions in order to provide code that can be run as is.
# Please refer to the comments in the code for more information.
... |
1796c20dcac3c1adb0a8d8508531a6dc2e19e7ac | Donggeun-Lim3/ICS3U-Unit3-06-Python | /try.py | 793 | 4.25 | 4 | #!/usr/bin/env python3
# Created by Donggeun Lim
# Created on December 2020
# This program is number guessing game
import random
def main():
# this function checks if number is not 5
# input
integer_as_string = input("Enter your number ")
print("")
# process
random_number = random.randint(... |
0eaf8d9d3fe88dadceafc87fe97f9e923d70dd2b | RedRem95/AoC2019 | /Day04/task.py | 723 | 3.515625 | 4 | from typing import List
from Day04 import INPUT
from helper import partner_check, only_increase, int_to_iter, atleast_one_pair_check
from main import custom_print
def create_passwords(min_pw=min(*INPUT), max_pw=max(*INPUT)) -> List:
return [i for i in range(min_pw, max_pw + 1, 1) if partner_check(int_to_iter(i))... |
726ea99dad70b9b1bafe2ca5baa550fcd45bbfbb | MyCatWantsToKillYou/TimusTasks | /Volume 11/src/Grant.py | 276 | 3.90625 | 4 | # task #2056
# Difficulty 58
grades = []
for i in range(int(input())):
grades.append(int(input()))
if 3 in grades:
print('None')
elif sum(grades)/len(grades) == 5:
print('Named')
elif sum(grades)/len(grades) >= 4.5:
print('High')
else:
print('Common')
|
ac890b226b69fbc626a4b27975eb1f58d359cb1e | lliei/learn-python | /twl/c5.py | 331 | 3.765625 | 4 |
# reduce
from functools import reduce
list_x = [1,2,3]
list_y = [1,2,3,4,5,6,7,8]
list_xy = [(0,0),(1,2),(2,2),(-1,-2)]
# def func(x):
# return x * x
r = reduce(lambda x,y:x*y,list_x) # 集合列表与参数要相同
# print(r)
print(r)
# 扩展
# 大数据
# map/reduce 模型 函数式编程 映射 归约 并行计算 |
6cc664cc5105cd3ea20f7eadcaec25ef063d09af | leninesprj/Python_Sketches | /CollatzHypothesis.py | 764 | 4.03125 | 4 | # Writing Collatz's hypothesis
# In 1937, a German mathematician named Lothar Collatz formulated an
# intriguing hypothesis (it still remains unproven) which can be described
# in the following way:
# take any non-negative and non-zero integer number and name it c0;
# if it's even, evaluate a new c0 as c0 ÷ 2;
#... |
8ae4f2edd42f227efc7cf0f753e68a4f649e2212 | Yumingyuan/algorithm_lab | /minmax.py | 1,383 | 3.8125 | 4 | # -*- coding: utf-8 -*-
import random
import time
def min_max_method1(search_data):#穷举搜索
length=len(search_data)
temp_max=search_data[1]
temp_min=search_data[1]
for i in range(2,length):#从第二个元素进行对比
if search_data[i]>temp_max:
temp_max=search_data[i]
if search_data[i]<temp_min:
temp_min=search_data[i]
ret... |
0f93d8803a87e9cbae3dc98bcfe7566f6f7a52ee | fanyichen/assignment6 | /mz775/assignment6/assignment6.py | 7,406 | 4.34375 | 4 |
from interval import *
import sys
def no_space(interval_string):
'''
use this function to get rid of white space in intervals from users
'''
no_space_str = str()
for element in interval_string:
if element != ' ':
no_space_str += element
return no_space_str
def mergeInterv... |
1822c620f7bb4a3f9fd1c43410144d0a335055d0 | Fake45mar/Python | /convertIntToRom.py | 3,931 | 3.5 | 4 | varNum = int(input("Enter number"))
arrayList = ['I', 'V', 'X', 'L', 'C']
def lessThanTen(number):
if number >= 1 and number < 4:
print(arrayList[0] * number)
elif number == 4:
print(arrayList[0] + arrayList[1])
elif number == 5:
print(arrayList[1])
elif number > 5 and number < 9:
print(arrayList[1] + array... |
7d56bac8179de5144b155e8bb80eb8d11e8f46e3 | Graph-Algorithms-Visualizations/graph-algorithms | /NPAlgorithms.py | 7,185 | 4 | 4 | from modify import Graph
def intToBinary(number, size):
"""
Converts a decimal number to binary form
Parameters:
==========
number: Integer
The Number to be converted into binary form
size: Integer
The maximum length of the returning binary list
Returns:
=======
l... |
6efa4ac39ed59d0464e9addecac3784bd3e7f071 | surendragalwa11/data-structures | /sorts/insertion-sort.py | 714 | 4 | 4 | def insertionSort(fullList):
listLen = len(fullList)
for i in range(1, listLen):
keyVal = fullList[i]
j = i-1
while j >= 0 and keyVal < fullList[j]:
fullList[j+1] = fullList[j]
fullList[j] = keyVal
j -= 1
return fullList
if ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.