blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
7cc40139b119b8f77515fb61fc9de5f80161dd36 | lnguyen96/HackTheU-Project | /Class.py | 3,858 | 3.953125 | 4 | import pandas as pd
import csv
import math
import numpy as np
import random
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
class house:
def __init__(self, n, s): #name of house, how many people in the house
self.name = n
self.size = s
#initial usage
self.usage_i = (60*self.s... |
bc0a41fa9afe1925ea285587bbbbceed953380ee | SeanKnowlton/SeanKnowlton.github.io | /python/scrape.py | 339 | 3.6875 | 4 | # a python program to get a list of urls to prep for webscraping
domain = "http://walshbr.com/"
pages = ['about','blog','pedagogy','projects','cv']
# make an empty list
urls = []
# appends pages to a domain to create the new urls
for page in pages:
url = domain + page
urls.append(url)
#method and par... |
d4ea75269ba6a2f6f5c406a6b4ec7e45c1512ed7 | arshmohd/daily_coding_problem | /legacy/daily_coding_problem_31_35.py | 6,907 | 4.15625 | 4 | import numpy as np
def coding_problem_31(s, t, debt=0):
"""
Given two strings, compute the edit distance between them.
The edit distance between two strings refers to the minimum number of character insertions, deletions, and
substitutions required to change one string to the other.
Example:
... |
af3bc83c3fe67d6f321266873a387ac47e4b6309 | petercombs/PythonCourse-2012 | /Utils.py | 3,143 | 3.6875 | 4 | from collections import namedtuple
import progressbar
Gene = namedtuple("Gene", ['chrom', 'start', 'end', 'strand', 'type', 'other'])
def parse_gtf(filename):
""" Parses the GTF in filename into a list of Genes
At the moment, this strips out everything that's a comment or on the F
chromosome, as well as... |
dc265d53b48e17ffe08e9ce98833bd849583a88a | herczy/codega | /codega/indent.py | 3,632 | 4.125 | 4 | '''Indentation helper functions
Dependencies: None
'''
def indent(text, level=1, indent_empty_lines=False, indent_string=' ', strip_result=True):
'''General purpose indentation
Arguments:
text -- Text to indent. The text is split to lines and each line
is individualy indented.
indent_em... |
dd414a496f499ebb326bf0bd8d722325fa216d1c | ellynhan/challenge100-codingtest-study | /hall_of_fame/kimdonghun/[BOJ]10866_Dequeue.py | 1,503 | 3.65625 | 4 | from collections import deque
import sys
N = int(sys.stdin.readline())
class Deque():
q = deque([])
def push_front(self, X):
self.q.appendleft(X)
def push_back(self, X):
self.q.append(X)
def pop_front(self):
if self.empty():
print(-1)
... |
07b9d9e6589dd1ffbaaa8a8969194ecdd0ddfb77 | fffk3045167/ananconda_spyder | /pro_s3.py | 395 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 2 09:12:53 2020
@author: Administrator
"""
"""
反转字符串
输入str = 'hello',输出 'olleh'
"""
str1 = input('请输入字符串:')
str2 = []
str3 = []
for x in str1:
str2.append(x)
while len(str2) - 1 >= 0:
str3.append(str1[len(str2) - 1])
str2.pop()
print('反转之后为:', end = '')
fo... |
8d3f22be8cbaad9a10439c42f6a867ed815c1ded | ap632638/python_codes | /signed.py | 158 | 4.125 | 4 | n=int(input("Enter any number: "))
if n>0 :
print(n," is a positive number.")
elif n==0 :
print(n,"is a zero")
else :
print(n,"is a negative number") |
71560bf743ec9152f74c36379c354b4e20431fc4 | susannah-go/Rosalind | /rosalind-revc.py | 400 | 3.578125 | 4 | # Solution to Rosalind problem revc using sample dataset
input = 'AAAACCCGGT'
# reverse input string
reverse = ''
l = len(input)
for i in range(l):
reverse += input[l - i - 1]
# take complement
output = ''
for c in reverse:
if c == 'T':
output += 'A'
elif c == 'A':
output += 'T'
el... |
e7f835eaf2ae8ce434dcc8249c44697d46f46197 | Gutsu7/copads | /copads/hash.py | 5,593 | 4 | 4 | '''
Hash Generators
Date created: 16th April 2013
Licence: Python Software Foundation License version 2
'''
import hashlib as h
def forward_file_hash(f, fsize, start, blocksize, algorithm):
'''
Forward file hashing. It takes file and generate repeated
hashes to the end of the file in blocks.
Alg... |
64179a309a36528eb4ccfcd30abdea2f8bef93a8 | MrBrN197/Sorting-Algorithms | /sorting.py | 3,459 | 3.734375 | 4 | import math
from time import time
from random import random
def insertion_sort(numbers):
result = numbers[:]
for i in range(1, len(result)):
j = i
while j > 0 and result[j-1] > result[j]:
temp = result[j]
result[j] = result[j-1]
result[j-1] = te... |
9e4ce30f3fb23421d655b60bb69ad906a5a1df26 | MatheusSC23/FUP | /Lista_08/4.py | 1,883 | 3.765625 | 4 | #_*_coding:utf8
#função que calcula os dias
def calc_dias(data_paga,data_venc):
partes1=data_paga.split("/")
partes2=data_venc.split("/")
anos=int(partes1[2])-int(partes2[2])
meses=int(partes1[1])-int(partes2[1])
dias=int(partes1[0])-int(partes2[0])+31*(meses)+365*(anos)
return dias
#função que ... |
9b183bbed4812c304618fc37400c4dbf22133215 | RaviRockz/PythonDeepDive | /1_Functional/3_NumericTypes/7_floats_coercing_int.py | 869 | 3.65625 | 4 | """"""
'''Floats: Coercing To Integers'''
'''
--> math.trunc (int)
integer part only
--> math.floor
smallest integer less than x
--> math.ceil
largest integer greater than x
'''
import math
print('''Using Trunc''')
print(math.trunc(10.4))
print(math.trunc(10.5))
print(math.trunc(1... |
e6da26776fe48d52d36a0c4f41539c7678675b30 | sedstan/LinkedIn-Learning-Python-Course | /Programming_Foundations_Real_World_Examples/Exercise Files/Ch02/02_02/start_02_02_creating_jeans.py | 717 | 4 | 4 | """ The Blueprints for Jeans """
class jeans:
def __init__(self, waist, length, color):
self.waist = waist
self.length = length
self.color = color
self.wearing = False
def put_on(self):
print('Putting on {}x{} {} jeans'.format(self.waist, self.length, se... |
7fbe1893e3aadbf9cf588581db7bba89f01ba78d | bejolo018/Computer-Architecture | /ls8/cpu.py | 4,032 | 3.5 | 4 | """CPU functionality."""
import sys
HLT = 0b00000001
LDI = 0b10000010
PRN = 0b01000111
MULT = 0b10100010
class CPU:
"""Main CPU class."""
def __init__(self):
"""Construct a new CPU."""
self.ram = [0] * 256
self.register = [0] * 8
self.pc = 0
self.branchtable = {} ... |
f78cf063643d810dcaa2865d7537c1221b54714f | eazow/leetcode | /25_reverse_nodes_in_k_group.py | 1,573 | 3.5625 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:param head: ListNode
:param k: int
:return: ListNode
"""
nodes = []
current = head
while c... |
067ba869d889831bdf3907574776de10d2e2ca90 | shrukerkar/Python | /CentralLimitTheorem.py | 695 | 3.578125 | 4 | import math
import random
from collections import Counter
import matplotlib.pyplot as plt
def burnoulli_trail(n,p):
return 1 if random.random()< p else 0
def binomial(n,p):
return sum(burnoulli_trail(p) for _ in range(n))
def make_hist(p,n,num_points):
data=[binomial(n,p) for _ in range (num_points)]
... |
af24d19845c96c427f0a8dd09cfd3db5e56adb83 | Beshkov/Python_Advanced | /Multidimensional Lists/Exercises/02 - 2x2 Squares in Matrix.py | 663 | 3.640625 | 4 | def matrix_input(row):
matrix = []
for r in range(int(row)):
# matrix.append(list(map(int,input().split(', '))))
matrix.append(input().split(' '))
return matrix
def box(matrix, row, col):
aa = matrix[row][col]
ab = matrix[row][col + 1]
ba = matrix[row + 1][col]
bb = matrix[... |
0cdce96c055269953baa7922b2afd227e7e0a0d5 | AishwaryaBarai/python-Basics | /guessgame.py | 215 | 3.953125 | 4 | secret_num = 9
count = 0
while count < 3:
guess = int(input('enter your guess: '))
count = count + 1
if guess == secret_num:
print('you win !')
break
else:
print('you lost')
|
c232c3afe6189d0a3285bc1e2469acf3451ed1b2 | thisnotBryanL/RelationalDatabase | /Bootstrap_Form/qualtricsParser.py | 5,160 | 3.78125 | 4 | """
Some of the reviews are entered via Qualtrics. Qualtrics provides a form for each review to be used by multiple reviewers.
Once the reviews are collected, it can output the results as a CSV file.
You are to read in the CSV file and input the result of the review to the database.
You can assume the csv file to be ... |
76a554f8f380925ded0671c049358d1365148c66 | iamalisaleh/url-shortener | /shorturls/utils.py | 456 | 3.796875 | 4 | import string
CHARS = string.digits + string.ascii_lowercase + string.ascii_uppercase
BASE = len(CHARS)
def decimal_to_base_n(number):
if number >= BASE:
return decimal_to_base_n(number // BASE) + CHARS[number % BASE]
else:
return CHARS[number]
def base_n_to_decimal(number):
if len(numb... |
e1166712861ab5b6599573fdc49801f1cde82d47 | ver0nika4ka/PythonCrashCourse | /8.2_Favorite_book.py | 360 | 3.765625 | 4 | ''' Function that accepts one parameter, title.
The function should print a message, such as One of my favorite books is Alice in Wonderland.
Call the function, making sure to include a book title as an argument in the function call.'''
def favorite_book(title):
print(f"One of my favorite books is {title.title()}... |
be3fe203c83046b8f4c842122e50f623ca1d503c | fabeschan/practice | /n_queens.py | 1,826 | 3.59375 | 4 | class queen(object):
def __init__(self, row, n):
self.y = None
self.x = row
self.domain = range(n)
def __repr__(self):
return str((self.x, self.y))
def can_attack(q1, q2):
# qi is a 2-tuple of the queen's position (x, y)
if q1.x == q2.x or q1.y == q2.y:
return T... |
1059d78fed85a722ceb0016f456611376118a921 | jahan19011noor/Python_EssT | /Sets_Frozensets/Set_Operations/_copy.py | 576 | 4.3125 | 4 | '''
Created on Oct 24, 2016
@author: Noor Jahan Mukammel
Program: set_method: copy()
* copy() - Creates a shallow copy, which is returned.
'''
more_cities = {"Winterthur","Schaffhausen","St. Gallen"}
cities_backup = more_cities.copy()
more_cities.clear()
print(cities_backup)
more_cities = {"Winterth... |
d4e07101b5e765d3be9dabf0ba8144fbff26a7ff | kaustubh2708/Encrypter-Decrypter | /kcas(1).py | 11,270 | 3.5 | 4 | # Modules imported
from Tkinter import * # For GUI
import tkMessageBox # For GUI Popup message box
import os # Starting file
import ttk # better GUI
import datetime # to create password
# Variables
details = [] # Used to store user details during login
lblines = ... |
ff7d7fe130a8a9af77c206109747e0187668b65b | balaji-calluru/DSI-Prep | /enum.py | 474 | 3.625 | 4 | names = ["Balaji", "Vasanthi", "Surya"]
ages = [46, 39, 14]
for name, age in zip(names, ages):
print(f'{name} is {age} years old')
lst_a = [4, 3, 7, 6, 5, 9, 2, 4]
lst_b = [1, 4, 6, 7, 4, 6]
for indx, a in enumerate(lst_a):
print(indx, a)
acc = 0
for i, a, b in zip(range(len(lst_a)), lst_a, l... |
ae639bd0248aa94bf54f5871c42938905afed731 | zhouatie/python | /practise/2018051501.py | 2,667 | 3.515625 | 4 | # -- coding: utf-8 --
# from car import Car, ElectricCar
# from restaurant import Restaurant
# from collections import OrderedDict
# class Dog():
# def __init__(self, name, age):
# """初始化属性name和age"""
# self.name = name;
# self.age = age;
# def sit(self):
# """模拟小狗被命令时蹲下"""
# print(self.name.title() + " i... |
dad54815044551733476e9e4c9d89bb88f6de1fe | Ximzzz/Pawelec | /Folder3/Zadanie3/Zadanie3.pyde | 1,141 | 3.703125 | 4 | def setup():
size(480,150)
background(0,0,0) # wystarczy zadeklarować te rzeczy raz, nie ma potrzeby co klatkę
textSize(100)
def draw():
if (mouseX > 110 and mouseX < 150 and mouseY > 30 and mouseY < 100):
fill(255,0,0)
text("R", 100, 100)
else:
if ((keyPressed) an... |
00bf3c41314a67370649052f9e656ae7e40f7d4e | atomminder/Coursera_Brown_Coding_the_matrix | /labs/week1/politics_lab/politics_lab.py | 8,252 | 4.1875 | 4 | voting_data = list(open("voting_record_dump109.txt"))
## Task 1
def create_voting_dict():
"""
Input: None (use voting_data above)
Output: A dictionary that maps the last name of a senator
to a list of numbers representing the senator's voting
record.
Example:
>>> creat... |
f89bf6798d7b5a2195880b783907ba5890de1678 | Nadjamac/Mod1_BlueEdtech | /Aula10_While/Exercicio 1.py | 256 | 4.03125 | 4 | senha = "senha123"
senha_dada = " "
while senha_dada != senha:
senha_dada = input("Digite uma senha: ")
if senha_dada != senha:
input("Digite a senha novamente: ")
else:
print("Você acertou a senha!")
break
|
a005627771d8351b7f521ed1d6d3d89e968e74fe | karthik4h1/karthikpython | /90beg.py | 75 | 3.5 | 4 | k=input()
l=list(k)
b=''
for i in l:
if i.isnumeric():
b+=i
print(b)
|
e99144d3788c25b5527330b392147750718d0d6d | mpsparrow/ProjectEuler | /Problem_021.py | 1,212 | 3.90625 | 4 | ##########################################################################
# Let d(n) be defined as the sum of proper divisors of n
# (numbers less than n which divide evenly into n).
# If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable
# pair and each of a and b are called amicable numbers.
#
# For ex... |
30265a23ecc954543881f467da5563c0f1714e64 | matiaszappino/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/7-islower.py | 153 | 3.78125 | 4 | #!/usr/bin/python3
def islower(c):
if ord(c) >= 97 and ord(c) <= 121:
return True
if ord(c) >= 65 and ord(c) <= 97:
return False
|
de7425859c317dfc342baaa67599f5fb5a0d8310 | zsimo/MOOC | /6_001_x_MITx_edX/week05/Lecture10 - Memory and Search/sort-test.py | 4,233 | 3.765625 | 4 | import time
import random
### SELECTION SORT ###
# O(n**2) # di complessita' quadratica
# find the min element of the list and swap it
# with the first elemente, then find the min element
# and swap it with the second element
def selSort(L):
for i in range(len(L) - 1):
minIndx = i
minVal= L[i]
... |
b4c68fa9992b848ae99ee31aea9bafc2989fe426 | RuzimovJavlonbek/qudrat-abduraximovning-kitobidagi-masalalarni-pythonda-ishlanishi | /begin_40/begin_4.py | 520 | 3.765625 | 4 | #Bu dastur Qudrat Abduraximovning C++ ga asoslangan kitobidagi masalar asosida python dasturlash tilida yozildi
# O'rganuvchi bo'lajak dasturchi : J_Ruzimov
#Sana: 21.06.2021
# Maniz: Nukus
# Begin 4
import math
print("Begin_4 \n Aylananing diametri d berilgan. Uning uzunligi aniqlansiz L = pi*d, pi= 3.14 ... |
768df4ee739db2b292cbcbd4a110c07729cdf042 | M69k65y/json-simple-validator | /json_simple_validator/validation.py | 6,373 | 3.828125 | 4 | import re
import phonenumbers
### Checks if a variable is empty or not ###
def is_empty(variable):
if variable:
return variable
else:
return None
# # An array of fields to be validated
# validation_list = [
# # Each element is made up of the field that is being validated
# # and the alias of the field t... |
744f22b89b93c22d256f0f6d180440b6eb1a75b7 | parthpm/Data_Visualization | /matplotlib4.py | 734 | 3.953125 | 4 | #Figure size, aspect ratio and DPI
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0,5,11)
y=x**2
# #Matplotlib allows the aspect ratio, DPI and figure size to be specified
# when the Figure object is created.
# You can use the figsize and dpi keyword arguments.
#
# figsize is a tuple of the ... |
11da4c8cfc171f8bc624d1ee7acf77fb142f85e9 | mujtke/se_work | /map.py | 4,681 | 3.578125 | 4 | # 这是写格子类和地图类的头文件
class Block:
# '格子类'
def __init__(self):
self.canPlantOn = True # 清醒的人能否站在这个格子上
self.canZombieOn = True # 感染的人能否站在这个格子上
self.isPlantOn = False # 是否有清醒的人站在这个格子上
self.isZombieOn = False # 是否有感染的人站在这个格子上
self.isHome = False # 是否为家(感染者往这个地方走)
s... |
b900e68fecc632e74a72cd0984b79b7c5d2e8218 | anedelcheva/Programming101-HackBulgaria | /week1/2-The-Real-Deal/sum_matrix.py | 165 | 3.578125 | 4 | def sum_matrix(m):
N = len(m)
M = len(m[0])
result = 0
for i in range(N):
for j in range(M):
result += m[i][j]
return result
|
cde095c3a24c1f8cb97ebd7ba310c713b32be815 | fangqiangchen/newproject | /python_office/day2exam2.py | 182 | 3.6875 | 4 | for i in range(1,5):
print(' '*(4-i)+'*' * (2*i-1))
print((' '* 3 + '|'+'\n')*2)
for i in range(0,4):
print(' '* (3-i)+'*'*(i*2+1))
for a in range(2):
print(' '*3 + '|') |
c91dfbdc243504b05a33975e0c3231d51cff30b5 | mmm673/rep1 | /fizzbuzz.py | 637 | 3.53125 | 4 | def replace(A):
for i in range(len(A)):
t = A[i]
if A[i][0] == '-':
A[i] = A[i][1:]
while len(A[i]) >= 2:
sum = 0
for j in range(len(A[i])):
sum += int(A[i][j])
A[i] = str(sum)
if (A[i] == '0' or A[i] == '3' or A[i] == '6' or A[i] == '9') and (t[-1] == '0' or t[-1] == '... |
d43ac424b5c8b5aaf04d876ed53a1b84afdf67b8 | ademaas/pythonbeginner | /countingNumLetter.py | 671 | 4.125 | 4 | #Write a program that accepts a sentence and calculate the number of letters and digits.
#Suppose the following input is supplied to the program:
def inputValue(sentence):
items = [x for x in sentence]
digits=[]
letters=[]
for i in items:
s = str(i)
if(s.isdigit()==True):
d... |
71596d9fb9888e1cf1e52ac010673b6a0f84fe9f | andrewparker11/Unit3 | /warmup8.py | 240 | 3.671875 | 4 | #Andrew Parker
#10/2/17
#warmup8.py - find the sum of all positive intergers less than 100,00 that are divisible by 3, 10 and 17
total = 0
for i in range(0,100000):
if i%3==0 and i%10 == 0 and i%17 == 0:
total = total + i
print(total) |
a158aa15dd9c00ac920184022de0c9802124f639 | yc1838/Python-Mega-Course | /basics.py | 622 | 3.875 | 4 | with open("hey.txt", "a+") as file:
file.seek(0)
cont = file.read()
file.seek(0)
file.write(cont)
#have to ask teacher for this one.
# write a program that interacts below:
# Say something: Hello
# Say Something: how are you
# Hello. How are you?
'''
def sentences_modification(stringa):
caped = stringa.capitalize... |
c6bce0e13ca0f16a8db3804937e0b2a352ba1209 | SMDXXX/Practice-Materials | /message1_2.py | 274 | 3.9375 | 4 | #!/usr/bin/python3.4
from tkinter import *
from tkinter import messagebox
top = Tk()
def Hello():
messagebox.showinfo("Say Hello", "Hello World")
top.geometry("400x400")
B1= Button(top, text = "Say Hello", command = "hello")
B1.place(x = 50,y = 50)
top.mainloop() |
5af6748d37de9e8fb0ae25a0c81c941ba790e60a | rajilaxmi/python | /conditional loops/9.fibonacci.py | 85 | 3.59375 | 4 | #9. fibonacci sequence
x,y=0,1
while y<50:
print y
x,y=y,x+y
'''
1
1
...
21
34
''' |
48f573cec13c957f91b0821fa1f587b132ca542b | rporumalla/Interview_Programming_Practice | /reverseLL.py | 791 | 4.3125 | 4 | # Time Complexity: O(n)
# Space Complexity: O(1)
# add nodes at beginning
class Node:
def __init__(self,data):
self.data=data
self.next=None
class linkedList:
def __init__(self):
self.head=None
def push(self,new_data):
node=Node(new_data)
node.next=self.head
self.head=node
def reverse... |
1995e73a39488b45cb4b673d6e3f1dbc4e42a3f4 | rishi772001/Competetive-programming | /Hackerrank/sort array.py | 207 | 3.765625 | 4 | input1=[13,2,4,15,12,10,5]
even=[]
odd=[]
for i in input1:
if(input1.index(i)%2!=0):
odd.append(i)
else:
even.append(i)
seven=even.sort()
sodd1=odd.sort()
sodd=sodd1.reverse()
print(sodd)
print(seven)
|
e2d9fa081a7536aa73f4dca983880354923d323a | rochderilo/FTW-Py-Quiz | /CRUD.py | 3,523 | 4.125 | 4 | """
Question Manager for Solar System Quiz 2020
This program allows users to view, add, edit, and delete questions
used in the Solar System Quiz.
By Roch Derilo
"""
# Reading the questions from questions.csv
questions = {}
file = open("questions.csv", "r")
text = file.readlines()
for row in text:
cols = row.s... |
23fef5436cbb2a5203a5e6c8f40518d154de41ac | lshays/projectEuler | /python/p052.py | 557 | 3.5625 | 4 | i = 0
count = 0
while count != 5:
i += 1
count = 0
mySet = set()
# Turn i into a set of its digits
for digit in str(i):
mySet.add(digit)
# Loop through 2i...6i
for n in range(2, 7):
newSet = set()
# Create a set of i*n's digits
for digit in str(i*n):
... |
cb02f61d9374527a1c8ca4fdb1ce7ca85ae458d7 | cooklee/Biblioteka_ONL_PYT_W_04 | /a.py | 414 | 3.671875 | 4 | opcje = """
1 - dodaj uzytkownika
2 - wyświetl Uzytkownikow
3 - usun uzytkownikow
4 - wyjdz
"""
while True:
opcja = input(opcje)
if opcja == '4':
break
if opcja == '1':
print("tutaj bede robił dodawanie użytkownika")
elif opcja == '2':
print("tutaj bede robił wyświetlanie uzytko... |
9d92405de6ed798e6c744f7a7b80986226c09828 | davidhuangdw/leetcode | /python/341_FlattenNestedListIterator.py | 3,066 | 3.921875 | 4 | from unittest import TestCase
# https://leetcode.com/problems/flatten-nested-list-iterator/
class NestedInteger(object):
def __init__(self, val):
self.val = val
def isInteger(self):
"""
@return True if this NestedInteger holds a single integer, rather than a nested list.
:rtype... |
28bf5b7e2fc5eb982030b75d88c14c51db2c5d74 | tr1503/LeetCode | /Dynamic Programming/paintHouse.py | 962 | 3.71875 | 4 | '''Use dynamic programming to create a 2d matrix.
The row is painting this color's min costs. The col is painting different color's min costs.
The state function: dp[i][j] = dp[i][j] + min(dp[i-1][one color except j], dp[i-1][the another except j]).'''
class Solution(object):
def minCost(self, costs):
"""
... |
a025feffdd197313ece31237a2eeb92ad63f7dfe | pumatus/wlpcpy | /returnmanyvalue.py | 200 | 3.59375 | 4 | import math
def move(x, y, step, angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny, angle
print('%s, %s, %s' % (move(100, 100, 60, math.pi / 6)))
|
d45af5d974870627cd1030abd2d29dab1d66b2d0 | rusac/programmingpath | /euler12b.py | 1,758 | 3.75 | 4 | # already tested n < 16 000 000 with no result.
'''
Highly divisible triangular number
Problem 12
The sequence of triangle numbers is generated by adding
the natural numbers. So the 7th triangle number would
be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms
would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
... |
3b943ba739f9ac93102a0fc270228eba473103ef | yimanliu/CS5001-Fall2019-yimanliu | /midterm/programC.py | 742 | 3.515625 | 4 | import programB
def whoami():
return "I'm programC!"
def count_up(count):
if count < 0:
return
count_up(count - 1)
print(count)
if __name__ == "__main__":
b = programB.whoami()
c = whoami()
print("b == {}".format(b))
print("c == {}".format(c))
print(2 / 2)
fib = [0, 1, 1, 2, 3, 5, 8,... |
05b285a5d722a5c5d2650116131dcdf3199168c4 | anchuanxu/Python-Elementary-Exercise-100-Questions | /PycharmProjects/test1-10/01_1.py | 408 | 3.6875 | 4 | # 题目:有四个数字:1,2,3,4,能组成多少个互不相同且没有重复数字的三位数字?各有几个?
# 问题分析:1,2,3,4可以分别填在个位,十位,百位。组成排列组合问题,去掉不满足条件的排列组合
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if(i!=k) and (i!=j) and (j!=k):
print(i,j,k)
|
b4f84234ba94988ec1ea4faef91d2887d33bdd46 | guidozamora/Data-Structures-Algorithms-Python | /LeetCode Solutions/80_remove_duplicates_from_sorted_array_2.py.py | 967 | 3.9375 | 4 | """
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array; you must do this by modifying the input array in-place with O(1) extra memory
Solution
- Loop through the array and store each unique valu... |
3f2ec094058e4a65fbc8a07970d4ecf3466c46b7 | arsenomadridabin/projecteuler | /generate_factors.py | 275 | 3.5 | 4 | import time
def generate_factors(num):
list1=[]
i=2
while(i<=num):
if(num%i)==0:
list1.append(i)
i=i-1
num=num/(i+1)
i=i+1
return list1
a=time.time()
print(generate_factors(1301081))
b=time.time()
print(b-a) |
97b5fadfb52156668f5b011bcd3cf3ddf196a04a | johnmihalik/quant-finance | /original/time_value_money.py | 735 | 3.9375 | 4 | from math import exp
def discrete_future_value(x,r,n):
return x*(1+r)**n
def discrete_present_value(x,r,n):
return x*(1+r)**-n
def continuous_future_value(x,r,t):
return x*exp(r*t)
def continuous_present_value(x,r,t):
return x*exp(-r*t)
if __name__ == "__main__":
x=100 #value of investment in dollars... |
4efe99b7550c340dd4fbf400cfc88497d922585d | mrendo2020/modulo3 | /estructuras_datos.py | 1,262 | 3.96875 | 4 | from typing import Dict
secuencia = [1, 3, 5, 7]
print(secuencia[2])
secuencia[2] = 10
print(secuencia[2])
secuencia.append(22)
print(secuencia[-1])
valor_eliminado = secuencia.pop(3)
print(secuencia, " ", valor_eliminado)
paises = [
"España",
"Ecuador",
"Mexico",
"Peru",
"Colombia",
"Venezuela... |
29706ef4d8924fec3637d2e1a5063aa18615143b | Upsurge-11/Simple_Implementation_Projects | /2_quiz_game.py | 1,909 | 3.796875 | 4 | def new_game():
guesses = []
correct_guesses = 0
question_num = 1
for key in questions:
print("-----------------------------------------------------------")
print(key)
for i in options[question_num-1]:
print(i)
guess = input("Enter the option:-")
... |
aafdeb6b7127d42b57ef7ea2658fae3dfdfd0be5 | morisasy/AWS_ML | /lesson4/clothing/class_shirt_get_set.py | 381 | 3.546875 | 4 | from shirt import Shirt
new_shirt = Shirt('red', 's', 'short sleeve', 45)
orange_shirt = Shirt('orange', 'L', 'short sleeve', 15)
print(new_shirt.__doc__)
# print
print(new_shirt.color)
print(new_shirt.size)
print(new_shirt.style)
print(new_shirt.price)
new_price = new_shirt.change_price(10)
print(new_shirt.price)... |
36992101c841067732f9fa56124dc726aa18f868 | elocamp/Fundamentos-de-Problemas-Computacionais | /merge_sort.py | 1,160 | 3.71875 | 4 | def merge_sort(vetor):
if len(vetor) > 1:
divisao = len(vetor) // 2
esquerda = vetor[:divisao].copy()
direita =vetor[divisao:].copy()
merge_sort(esquerda)
merge_sort(direita)
i = j = k = 0
while i < len(esquerda) and j < l... |
b0735e1cd7232f15435b9ed6ae9ee828c80cc4c7 | tsui-david/tzu-chi-cs-class | /class14-array-advanced-drills/answers.py | 3,705 | 3.9375 | 4 | def ex1(a):
"""
given an array of integers, find and return the smallest integer's INDEX
ex: a = [1,2,3,4]
return 0
"""
min_num = float('inf')
min_index = -1
for i, v in enumerate(a):
if v < min_num:
min_index = i
min_num = v
return min_index
def ex2(a, target):
"""
given an a... |
7379c94dc064eb2ddccf7baf3077589978eb5f46 | kc-w/My_Tool | /python开发/特殊应用/函数式编程和高级特性/test.py | 3,343 | 3.953125 | 4 | #map函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。将运算规则抽象化。
import time
list1=[1,2,3,4,5,6,7,8,9]
list2=[]
def f(x):
return x * x
#数组遍历相乘,返回一个map对象
map1 = map(f, list1)
print(map1,list(map1),type(map1))
#将列表中的元素从整数转化为字符串
map2=map(str,list1)
print(list(map2))
#reduce把一个函数作用在一个序列[x1, x2, ... |
c6ad7a0c723c28a7167b10be3153e1f1dc0b5bcc | YangLiyli131/Leetcode2020 | /in_Python/1013 Partition Array Into Three Parts With Equal Sum.py | 547 | 3.640625 | 4 | class Solution(object):
def canThreePartsEqualSum(self, A):
"""
:type A: List[int]
:rtype: bool
"""
total = sum(A)
if total % 3 != 0:
return False
ave = total / 3
cursum = 0
i = 0
counter = 0
while i < l... |
f9d8beb6bdbbab78e422478e4fa8b8bee83098ce | ArtemisBrindlehorn/Zed | /ss_ex15.py | 875 | 4.21875 | 4 | #imports the argment variable function/module from the sys module collection
from sys import argv
#notes that there are two argument variables, one for the script, one for the filename
script, filename = argv
#this opens the file, filename, and writes the contents to a variable txt
txt = open(filename)
#prints a lin... |
f18044d28f15490c0a4e219e0563810f9ee6c376 | Biz-Computer-Programming/Python-OOP-2_62 | /GUI-Example03.py | 1,233 | 3.71875 | 4 | from tkinter import *
def addition():
number = edtNumber.get()
number = int(number)
result = msgTotal["text"]
result = int(result)
total = result + number
msgTotal["text"] = total
def reset():
total = 0
msgTotal["text"] = 0
edtNumber.delete(0,END)
edtNumber.focus
... |
9a0c4fcd7a13e6d787b6721781496c0144f4845a | Rickkwa/adventofcode | /2021/08/part1.py | 642 | 3.671875 | 4 | def read_input():
result = []
with open("input1.txt") as fp:
for line in fp:
signal_patterns = line.split("|")[0].strip().split(" ")
digits = line.split("|")[1].strip().split(" ")
result.append((signal_patterns, digits))
return result
if __name__ == "__main__":
... |
ed00125d562e341d99c58ca9b614973ff8cf1057 | VersionBeathon/Expension | /practice_treading/condition_threading.py | 1,723 | 4.0625 | 4 | # _*_ coding:utf_8 _*_
''' Python 提供了 Condition对象。它除了具有acquire和release方法之外,还提供了wait和notify方法。线程首先acquire一个条件变量锁。如果条件不足,则该线程wait,如果满足就执行线程,甚至可以notify其他线程。其他处于wait状态的线程接到通知后会重新判断条件。
条件变量可以看成不同的线程先后acquire获得锁,如果不满足条件,可以理解为被扔到一个(Lock或Rlock)的waiting池。直达其他线程notify之后再重新判断条件。该模式常用语生产消费模式'''
import time
import threading
import... |
b940fb0a3a614132d10f18f3e82ebd07e46eceb5 | terrapanda/algorithms_py | /specialization/fibonacci/fibonacci_stress.py | 961 | 3.578125 | 4 | from random import randint
from fibonacci_partial_sum import fibonacci_partial_sum
from fibonacci_partial_sum_naive import fibonacci_partial_sum_naive
n = int(input()) - 1
while True:
print('testing')
# Generate a random number between 2 and 11
random_size = str(randint(0, 400))
sample_input = ''
sa... |
d52387db69ed2ca66cba5e2dde34de91e7419ae8 | LoyaltyJi/Deep-Learning | /MLPandPerceptron/Part2 MLP_Numpy/mlp.py | 2,761 | 3.59375 | 4 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from modules import *
class MLP(object):
def __init__(self, n_inputs, n_hidden, n_classes):
"""
Initializes multi-layer perceptron object.
Args:
n_inputs: number o... |
8d30c563d08157f31c62feb6f94c0d7ac7a6da69 | marisagross/Week-Three-Assignment | /PIGGY.py | 1,008 | 4.3125 | 4 | # Marisa Gross
# Piggy.py
# Week 3: Pig Latin Assignment
#This program will translate words into Simple Pig Latin.
print("This program gives words in Pig Latin")
word=input("Enter an English word to translate: ")
vowel = "aeiou"
if word[0] in vowel:
print(word + "yay")
else:
print(word[1:] + word[0] + "a... |
d98815272306328717bff74817c009471b8199a3 | lulions/100-plus-Python-programming-exercises-extended | /day002/004.py | 159 | 3.984375 | 4 | nums = input("Insert a comma-separated list of numbers: ")
nums = nums.replace(' ', '').split(',')
nums = [int(n) for n in nums]
print(nums)
print(tuple(nums)) |
62b72cb8b7ada57b565555abd1e6ff4a031a56a8 | lucassilva-dev/codigo_Python | /ex051.py | 223 | 3.75 | 4 | pt = int(input('Qual é o primeiro termo ? '))
razao = int(input('Qual é a razão ? '))
decimo = pt + (10 - 1) * razao
for c in range(pt, decimo + razao, razao):
print('{} '.format(c), end=' → ')
print('ACABOU') |
0cb3ce6d3bbcf150923f0ad847efaa0103a64d18 | 0mUltramar/Manual-snake | /exercice07/task04.py | 2,212 | 4.03125 | 4 | # Написать функцию, принимающую длину стороны квадрата и рассчитывающую периметр квадрата, его площадь и диагональ.
# Сделать два и более варианта функции, которые должна отличаться количеством возвращаемых переменных. Не забыть про
# проверки входных данных в самой функции.
def inp_side_lenght():
"""inp_side_len... |
04c2aeacadf4c3e958427ec198adf3130ff64445 | zijuzhang/Courses | /CSC148/assignment2/mn_puzzle.py | 5,856 | 3.65625 | 4 | from puzzle import Puzzle
from copy import deepcopy
class MNPuzzle(Puzzle):
"""
An nxm puzzle, like the 15-puzzle, which may be solved, unsolved,
or even unsolvable.
"""
def __init__(self, from_grid, to_grid):
"""
MNPuzzle in state from_grid, working towards
state to_grid
... |
1611888f5443013a5b1d51e7738bc756b747f9ea | coolsync/todo | /other-space/py/py-start/11-func-advanced/04-lambda-apply.py | 652 | 4.09375 | 4 | # 带判断的lambda
print((lambda a, b: a if a > b else b)(1000,500))
# 列表data按字典key的值排序
emps = [
{'name': 'mark', 'age': 32},
{'name': 'paul', 'age': 27},
{'name': 'bob', 'age': 30},
]
emps.sort(key=(lambda x: x['name']))
print(emps)
emps.sort(key=lambda x: x['name'], reverse=True)
print(emps)
emps.sort(key=l... |
247a254ba48209150b8cfe45f25c6f4b9a6a3d4e | gxsgxs/1808 | /08day/01-平年闰年.py | 183 | 3.84375 | 4 | year = int(input("请输入年份"))
if year % 4 == 0 and year % 100 != 0:
print("%d是闰年"%year)
elif year % 400 == 0:
print("%d是闰年"%year)
else:
print("平年")
|
22b56e8cd6397ce99766d58875f84a232098bd71 | stefbos2000/TICT-V1PROG-15 | /pe7/pe7_3.py | 264 | 3.765625 | 4 | cijfers = {'Sander': 4, 'San': 5, 'Henk': 6, 'Martijn': 8, 'Adriaan': 3, 'Pieter': 9, 'Stef': 10, 'Hans': 1}
for cijfer in cijfers:
if cijfers[cijfer] > 9:
print('De mensen met een cijfer hoger dan een 10 zijn: {}: {}.'.format(cijfer, cijfers[cijfer])) |
e74adfd4f0b590966a919a628c4c667c061ef5ed | wangtao090620/LeetCode | /wangtao/leetcode-easy/0100.py | 1,027 | 3.921875 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Author : wangtao
# @Contact : wangtao090620@gmail.com
# @Time : 2020-07-16 22:37
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
from collections i... |
e6482e684154c0e5fdd39e496405dc1dcd00bf86 | repoCS/Algorithmen_UE | /ue_fibonacci_algorithm_comparison/fibonacci_speedcomparison.py | 2,036 | 3.9375 | 4 | #!/usr/bin/env python3
'''
Algorithmen Übungen - Clemens Spielvogel
Vergleich von zwei Algorithmen zur Berechnung von Fibonacci Zahlen
'''
import sys
from datetime import datetime
import subprocess
# Implementierung der Algorithmen
def RecursiveFibonacci(n):
if n == 1 or n == 2:
return 1
else:
... |
cbfdbbde0fdaade8ab68857e9e7bbd8127f5425c | KYRIEZX/TFNN | /LR.py | 1,568 | 3.5 | 4 | import numpy as np
def compute_loss(w,b,points):
total_loss=0
for i in range(len(points)):
x=points[i,0]
y=points[i,1]
total_loss+=(w*x+b-y)**2
return total_loss/float(len(points))
def step_gradient(w_current,b_current,points,learning_rate):
w_gradient=0
b_gradient=0
N ... |
08b4b94644a9a4d878eb536676a4580aa0527e1b | khanmaster/python_functions | /general_functions.py | 246 | 4.3125 | 4 | # in python def is used to define the function and give it a name
greetings = input("What is your name ")
def print_greetings():
# Python interpreter recognises intendation is key
print("Welcome on board dear " + greetings)
print_greetings() |
5633f0672a228788f9c2f44e324d02434b5f6e50 | dyyura/function | /123.py | 805 | 3.84375 | 4 | # zadainie 1
'''
list_1 = ['name','age','1','19']
def half2():
for i in range(len(list_1)):
if i % 2 == 0:
list_1[i], list_1[i + 1] = list_1[i + 1], list_1[i]
print(list_1)
half2()
def half3():
a = input().split()
print((list(reversed(a[:(int(len(a)) // 2)])))
+ (list(reversed(a[(int(len(a)) ... |
1438d051daea0e9b380bd61c326664090c471617 | kernalphage/adventOfCode | /day1.py | 303 | 3.828125 | 4 | floor = 0
instruction = 0
firstEnter = True
with open("input/input1.txt") as f:
for c in f.read():
instruction +=1
if c=="(":
floor = floor + 1
if c==")":
floor = floor - 1
if(floor == -1 and firstEnter):
firstEnter = False
print("entered basement at ", instruction)
print floor |
04023969e5b647609d50d9e57e932bcc4196c6ac | somodis/ClassRoomExamples | /SOE/ProgAlap2/20210224/race_game.py | 560 | 3.703125 | 4 | from vector_2d import Vector
class Car:
position=Vector(0,0)
velocity=Vector(0,0)
def __init__(self):
super().__init__()
def next(self,acceleration):
if acceleration.x >1 or acceleration.y>1 or acceleration.x <-1 or acceleration.y<-1:
raise Exception
self.velocit... |
2aa6c5b912d06b4f0ead5c504975ff7c4e4977ef | ugobachi/AtCoder | /PanasonicProgrammingContest/C.py | 699 | 3.671875 | 4 | # coding: utf-8
"""[solution]
√a + √b < √cかどうかを判定するプログラム
a, b, cの整数の変数
srqtを使うと小数になってしまうため、小数を使わないアプローチを採用
大小比較は両辺を二乗しても可能
a + 2√ab + b < c
まだ√が残っているので、式変形して二乗する
c - a - b > 2√ab
これを二乗して
(c - a - b)^2 > 4ab
また、a + bがcより大きければ絶対に√a + √b < √cを満たさないのでこの条件も追加
条件を満たすもののみをYesを出力
"""
a,b,c = (int(x) for x in input().split())... |
5c7547dfe535420f16418ce062b9e388246b80a8 | gilsontm/ine5416-straights | /atividades/atividade2/atividade2-1-B/011.py | 1,378 | 4.125 | 4 | class BinaryTree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def insert(self, value):
if value < self.value:
if self.left: self.left.insert(value)
else: self.left = BinaryTree(value)
el... |
0174f18002ead3a4fffda4dd5057dea216511a34 | mounirchebbi/holbertonschool-higher_level_programming | /0x03-python-data_structures/5-no_c.py | 150 | 3.703125 | 4 | #!/usr/bin/python3
def no_c(my_string):
new = [item for item in my_string if item != 'c' and item != 'C']
str = "".join(new)
return (str)
|
7472e688872952a6c352d4c92884dcd64e20578f | CoetBoet68/turtleCrossingRoad | /car.py | 1,037 | 3.765625 | 4 | from turtle import Turtle
from random import randint
class Car(Turtle):
colours = ["green","yellow", "red", "blue", "violet", "magenta","orange", "cyan", "brown"]
xPos = 250
moveSize = 0
cDis = 20
def __init__(self, xDiff, posy, mSize):
super().__init__()
self.moveSize... |
7707ee9d74c012e7723301fc6ef027e5b45c6164 | GuodongQi/LeetCode | /codes_1-50/48_Rotate_Image.py | 528 | 3.703125 | 4 | class Solution:
def rotate(self, matrix: 'List[List[int]]') -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
size = len(matrix)
m_new = [[None] * size for i in range(size)]
mid = size // 2
for i in range(size):
for j in rang... |
259da4af07afd939d8fc6556e7a81c95f64ae90e | AbouClaude/Project-1 | /Hazem_Solution.py | 7,719 | 4.0625 | 4 | import pandas as pd
import numpy as np
# Loads Bundesliga results dataset.
df = pd.read_csv('https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/vcd/Bundesliga.csv')
def Exercise1(df):
#Group the dataframe by hometeam and assert the values as "the sum of homegoals" and
#sort them accord... |
e8294c95bb5313c10ff577cfcac5612d9c3981d7 | Douphing/Python | /ex035.py | 348 | 4.03125 | 4 | print(' -='*20)
print('Analisadior de TRIANGULO')
print(' -='*20)
r1 = float(input('Primeiro segmento '))
r2 = float(input('Segundo segmento '))
r3 = float(input('Terceirop segmanto '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print(' O segmento pode formar Um triangulo ')
else:
print('O segmento não ... |
16bdc1aacb662e242855cee8ddd73104ef493632 | PZ-4CO/ScientificComputingWithPython | /TimeCalculator/time_calculator.py | 1,948 | 3.5625 | 4 | def add_time(start, duration, start_day=0):
week_days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
if start_day != 0:
start_day = start_day.lower()
start_day = start_day.capitalize()
else:
start_day = "Not provided"
time_start = start.split(... |
3016c631793f2816b013ba744bd62dfcf97b522d | LagunaElectric/Python-Playground | /Misc Playground/python-class-exploration.py | 532 | 3.859375 | 4 | # Python Class Exploration
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = f"{first}.{last}@testcompany.com"
def __str__(self):
nl = '\n'
str_out = f"First Name: {self.first}\n" \
... |
48fed09bb554f3d45772d1a9bdb94bcd40d0539c | rafaelperazzo/programacao-web | /moodledata/vpl_data/201/usersdata/267/96533/submittedfiles/mediaLista.py | 263 | 3.765625 | 4 | # -*- coding: utf-8 -*-
n=int(input('Quantidade de valores: '))
lista=[]
soma=0
for i in range(0,n,1):
elem=int(input('Digite o elemento: '))
lista.append(elem)
soma=soma+lista[i]
print('%.2f' %lista[0])
print()
print(soma/n)
print ('%.2f' %(lista))
|
28b174247d80cabf239c5946f62f5e73392c45c2 | xulleon/algorithm | /leetcode/Unsorted_Algorthm_Problems/N_Queens.py | 1,849 | 3.6875 | 4 | # https://leetcode.com/problems/n-queens/submissions/
class Solution:
"""
This problem is a dfs permutation. for each valid combination, i.e. [1,3,0,2], the index is the row number and the value is the column umber. it equivalent to
[(0,1), (1,3), (2,0), (3,2)]
The condition is the similar to qualindrom... |
e74cf6c16b61e848afdd1f77e9ddab25ce55f0b6 | franciscodominguezmateos/pyHotDraw | /pyHotDraw/src/pyHotDraw/Figures/pyHAttributes.py | 1,288 | 3.609375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Created on 27/03/2013
@author: paco
'''
class pyHAttributeColor(object):
'''
classdocs
'''
def __init__(self,r,g,b,a=255):
'''
Constructor
'''
self.r=r
self.g=g
self.b=b
self.a=a
def draw(self,g):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.