blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
0db86a5747fe5323cc6b9713636f7e110267e2c4 | annamnatsakanyan/HTI-1-Practical-Group-1-Anna-Mnatsakanyan | /Homework_3/missing_number.py | 227 | 4.09375 | 4 | def missing_number(num):
n = len(num) + 1
_missing_number = n * (n + 1) // 2 - sum(num)
return _missing_number
numbers = [int(elem) for elem in input("enter the numbers: ").split()]
print(missing_number(numbers))
|
c5a2503ff4fa49e6afce2478e8875c0ea16f9816 | annamnatsakanyan/HTI-1-Practical-Group-1-Anna-Mnatsakanyan | /Homework_3/rectangle_perimeter.py | 476 | 3.796875 | 4 | import math
def segment_length(x1, y1, x2, y2):
side = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
return side
def rectangle_premier(coordinate):
premier = 2*(segment_length(coordinate[0], coordinate[1], coordinate[2], coordinate[3]) + segment_length(
coordinate[2], coordinate[3], coordinate[4], ... |
905b60811eff634ba1f6873ab0bc0566783058b5 | majiayu000/pycheckio-solutions | /Electronic Station/unix_match_part_1.py | 3,294 | 3.71875 | 4 | #!/usr/bin/env checkio --domain=py run unix-match-part-1
# Sometimes you find yourself in a situation where among a huge number of files on your computer or in a separate folder you need to find files of a certain type - for example, images with the extension '.jpg' or documents with the extension '.txt', or even file... |
b04288084089c2665160d38afda76ceb32866da3 | japarker02446/BUProjects | /CS521 Data Structures with Python/Homework2/japarker_hw_2_5.py | 748 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
japarker_hw_2_5.py
Jefferson Parker
Class: CS 521 - Spring 1
Date: January 27, 2022
Execute the fizz-buzz challenge for a loop of 30 iterations.
"""
MAXVAL = 30
# For loop implementation
for i in range(1, MAXVAL+1):
next_string = ''
if(i % 2 == 0):
next_str... |
4e95c987b1a5b1a131715a1a53aeb21e0ee3e251 | japarker02446/BUProjects | /CS677 Data Analysis with Python/Homework2/japarker_hw2_1.py | 5,729 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Jefferson Parker
Class: CS 677
Date: March 29, 2022
Homework Problem 2.1
Read historical stock data (PFE, SPY) and assign a label for gain or loss days.
"""
import numpy as np
import pandas as pd
import os
import operator
# Set the input directory path.
try:
os.chdir(os... |
ca06fa9e3d87538837e9ef1bc0c753cc0c96b09f | japarker02446/BUProjects | /CS521 Data Structures with Python/Homework4/japarker_hw_4_3.py | 1,566 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
japarker_hw_4_3.py
Jefferson Parker
Class: CS 521 - Spring 1
Date: February 10, 2022
Create two constant lists, one of first names and one of last names.
Validate that the last name list is at least as long as the first name list.
If not, exit with an error message.
Use the zi... |
eb50ffc9ea9abc10458acfb992f5eea870147e1b | japarker02446/BUProjects | /CS521 Data Structures with Python/Homework4/japarker_hw_4_5.py | 984 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
japarker_hw_4_5.py
Jefferson Parker
Class: CS 521 - Spring 1
Date: February 10, 2022
Convert a (negative and / or floating point) number to words.
"""
# Initialize variables.
NUM_MAP = {"1":"One",
"2": "Two",
"3": "Three",
"4": "Four",
... |
271c767917e48a6b5e4fb490a51b36ab8f4aafe2 | japarker02446/BUProjects | /CS677 Data Analysis with Python/Homework3/japarker_hw3_6.py | 2,481 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Jefferson Parker
Class: CS 677
Date: April 1, 2022
Homework Problem 3.6
Read and plot real vs fake bank note data from UCI Data Set repository.
Implement logistic regression to predict bill authenticity with dropped features
F1, F2, F3 or F4.
"""
import numpy as np
import os
im... |
454519eaad46c2e7d710b886b3ec1474d2197470 | japarker02446/BUProjects | /CS677 Data Analysis with Python/Homework2/japarker_hw2_2.py | 10,954 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Jefferson Parker
Class: CS 677
Date: March 29, 2022
Homework Problem 2.2
Read historical stock data (PFE, SPY) and PREDICT label for gain or loss days.
"""
import numpy as np
import pandas as pd
import os
import operator
# Set the input directory path.
try:
os.chdir(os.... |
ac38587f5f16fd8f330294422eed009678adaaf7 | cfpb/hmda-viz-processing | /testing/test_index_old.py | 670 | 3.625 | 4 | #test a module takes an input and returns an index
class testing(object):
def __init__(self):
pass
def key_return(self, class_name, function_name, input_dict, key):
if getattr(class_name, function_name)(input_dict[key]) == input_dict['output']:
print 'passed for output {output}'.format(output=input_dict)
el... |
0b27cfe4524f099a3f33db5981da7172f07c001b | BruddaFett/python_loan_calc | /main_code.py | 2,293 | 3.71875 | 4 | import math
WIDTH = 20
def getLoanInfo():
loanAmt = float(input('Enter Loan Amount: '))
interestRate = float(input('Enter Interest Rate: '))
return loanAmt, interestRate
def loanTermMenu():
print('-' * WIDTH)
print('Loan Report Menu: ')
print('-' * WIDTH)
print('1. One Year')
... |
46ca0cc0de67bcc58430952e78505260f4b383f4 | colinvsyolanda/python | /study/list_tuple_dictionary/python010.py | 359 | 4.125 | 4 | """
题目:暂停一秒输出,并格式化当前时间。
程序分析:无。
"""
import time
print(time.localtime())
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
time.sleep(2)
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
time.sleep(2)
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
|
0285230b73401bcaf3a7a5a8b15c01d9832c09c8 | colinvsyolanda/python | /study/list_tuple_dictionary/python011.py | 847 | 3.828125 | 4 | """
题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
程序分析:兔子的规律为数列1,1,2,3,5,8,13,21....
"""
def calNumber(month):
tuzi_month_number = []
if month == 1 or month == 2:
tuzi_month_number.append(1)
else:
tuzi_month_number = [1, 1]
for i in range(... |
26eb512c18e30d70e0a383ca748302bfef9a3681 | samarthgowda96/pycharprojects | /pal.py | 493 | 4.15625 | 4 | string= input("enter the input"+" ")
def isPalindrome(str):
length = len(str)
first = 0
last = length - 1
palindrome = 1
while first < last:
if(str[first] == str[last]):
first = first + 1
last = last - 1
continue
else:
palindrome= 0
... |
7367490845696a41f8ee3ff508711d5dc48f5f91 | chang-1/BrownUniversity | /ENGN2020/HW5/hw5_3b.py | 490 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 20 10:40:31 2019
@author: xumin
"""
from submission.client import submit, check_score
def filter(links):
length = len(links)
result=[]
#loop all links to see if it contains the "/academics/engineering/" key word
for i in range(length):
if(links... |
c62ce629f1dcb98ea43bdbb6947e48bf0e9bfeb9 | chang-1/BrownUniversity | /ENGN2020/Mid1/mid_2bc.py | 3,879 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 20 11:37:52 2019
@author: xumin
"""
#include libraries
import numpy as np
import json
import matplotlib.pyplot as plt
#read in results
results = json.load(open('results.json'))
team_names = json.load(open('teams.json'))
'''
* @name: getTopTenScores
* @description: get th... |
181d59c7c3acec073c7c9b188400ca45f32b3b57 | chang-1/BrownUniversity | /CSCI1420/hw10/models.py | 13,208 | 3.6875 | 4 | import numpy as np
import random
def l2_loss(predictions,Y):
'''
Computes L2 loss (sum squared loss) between true values, Y, and predictions.
:param Y: A 1D Numpy array with real values (float64)
:param predictions: A 1D Numpy array of the same size of Y
:return: L2 loss using pre... |
37f7995cd0bdebf46e1a3a4776885ea94c301713 | poojarkpatel/Testing_Triangle_Classification | /HW01_Pooja_Patel.py | 1,702 | 4.25 | 4 | """
HW01
Triangle classification
"""
import math
class Triangle:
"""
The class takes length of three sides of triangle and return the
type of triangle.
"""
def __init__(self, side1, side2, side3) -> None:
"""
init function of class
"""
self.side1 = float(side1)
... |
8b89a4b42869fb143357174fcf98e5c0d50170e8 | srujanprophet/PythonPractice | /11 - Unit 4/4.1.12.py | 407 | 4.1875 | 4 | str = "Global Warming"
print str[-4:]
print str[4:9]
if str.isalpha() == True:
print "It has alphanumeric characters"
else:
print "It does not have alphanumeric characters"
print str.strip("ming")
print str.strip("Glob")
print str.index('Wa')
print str.swapcase()
if str.istitle() == True:
print "It i... |
e59ca9809c55ec392cafd5705da55e915201bce3 | srujanprophet/PythonPractice | /11 - Unit 3/3.2.3.py | 89 | 3.9375 | 4 | x = int(raw_input("Enter a number : "))
ans = x + 3
ans *= 2
ans = ans - 2*x
print ans
|
808bab1440d793ccbaca0effd29d517bc7043782 | srujanprophet/PythonPractice | /Class XII CBSE/1.1.17.py | 377 | 4 | 4 | z1r = int(raw_input("Enter real part of 1st complex no. :"))
z1i = int(raw_input("Enter imaginary part of 1st complex no. :"))
z2r = int(raw_input("Enter real part of 2nd complex no. :"))
z2i = int(raw_input("Enter imaginary part of 2nd complex no. :"))
Zr = z1r*z2r - z1i*z2i
Zi = z1r*z2i + z1i*z2r
print "Multiplicat... |
4966b5c497abaf1b52375a14aebb438cdbf22bdf | srujanprophet/PythonPractice | /Class XII CBSE/2.1.12.py | 435 | 3.90625 | 4 | def selectionsort( aList ):
for i in range( len( aList ) ):
least = i
for k in range( i + 1 , len( aList ) ):
if aList[k] < aList[least]:
least = k
swap( aList, least, i )
print aList
print aList
def swap( A, x, y ):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
l = []
n = int(raw_input(... |
45ddb69ddf9618b5dda3a1e2a87ae8f740be84fc | srujanprophet/PythonPractice | /Class XII CBSE/1.4.22.py | 1,395 | 3.71875 | 4 | class employee(object):
Eno = "NULL"
Ename = "NULL"
Designation = "NULL"
Address = "NULL"
PhoneNo = "NULL"
def getdata(self):
self.Eno = raw_input("Enter Employee No. : ")
self.Ename = raw_input("Enter Employee Name : ")
self.Designation = raw_input("Enter Designation : "... |
b7856076678d3ee518d06ed63acdd113f195715b | srujanprophet/PythonPractice | /11 - Unit 3/3.3.6.py | 203 | 4.15625 | 4 | def fibonacci():
n = int(input("Enter no. of terms : "))
pre = 0
cur = 1
for i in range(1,n+1):
print cur
nxt = pre + cur
pre = cur
cur = nxt
fibonacci()
|
27e667911c448a90a1c047900699ad4742e79bcc | srujanprophet/PythonPractice | /LPHTW/projects/Book_Cricket.py | 7,748 | 3.734375 | 4 | from random import randint
from sys import exit
import os
OUT = [ "Bowled Him", "Edged and Gone", "High up in the air, Fielder coming underneath and takes the catch",
"Finger goes up, LBW!", "Run Out :(", "Caught and bowled"
]
##def Toss():
## print "Choose heads or tails: (Press enter after deciding).... |
da4781a4edd5ce302c4cb46bb9d33e9a54801248 | srujanprophet/PythonPractice | /11 - Unit 4/4.3.4.py | 286 | 3.78125 | 4 | customers = dict()
n = int(raw_input("Enter no. of customers : "))
for i in range(n):
a = raw_input("Enter Customer Name : ")
b = raw_input("Enter Customer's Phone No. : ")
customers[b] = a
name = raw_input("Enter Number of entry : ")
del customers[name]
print customers
|
a380acea3c3718c1079998db7aad2355d33f8ee0 | srujanprophet/PythonPractice | /11 - Unit 4/4.1.11.py | 75 | 3.65625 | 4 | str = raw_input("Enter a string : ")
str = str.replace('y','')
print str
|
322b2a9af248d9621511927525378521e1da3e84 | srujanprophet/PythonPractice | /LPHTW/projects/Vacation.py | 960 | 3.96875 | 4 | def hotel_cost(nights):
return 140 * nights
def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
elif city == "Mumbai":
return 600
... |
d61b1a78537906cc17a4987f7735a02958e78d7f | srujanprophet/PythonPractice | /Class XII CBSE/1.1.18.py | 315 | 3.703125 | 4 | f1 = raw_input("Enter First Distance (x'y\") : ")
f2 = raw_input("Enter Second Distance (x'y\") : ")
F1 = (float(f1[0])*12 + float(f1[1]))*2.54
F2 = (float(f2[0])*12 + float(f2[1]))*2.54
F = F1 + F2
i = F*0.3937008
j = i/12.0
k = (j%1)*12
print
x = int(j)
y = int(k)
print "Sum of distances is",x,'\'',y,'\"'
|
0108f3c6f3aa9701f38b4a4ac7e2acafb5619d1a | srujanprophet/PythonPractice | /11 - Unit 4/4.2.10.py | 333 | 3.703125 | 4 | n = int(raw_input("Enter no. of rows of matrix : "))
m = int(raw_input("Enter no. of columns of matrix : "))
a=[[0 for row in range(n)]for col in range(m)]
sum = 0
for i in range(0,m):
for j in range(0,n):
a[i][j] = int(raw_input("Enter Element : "))
if a[i][j] % 2 == 0:
sum += a[i][j]... |
c37c51cc1cea86761b207203799fd387dc45f866 | vlad9913/DJ-SETLIST-GENERATOR | /GA/chromosome.py | 9,642 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 13 16:37:06 2021
@author: Vlad
"""
'''
input: n - chromosome length (number of songs)
tracks - array of dictionaries representing songs, from where we choose
our atoms
'''
def generate_a_random_chromosome(n,tracks):
import rand... |
fc374af7587643a9e9edc4d5ac4b12287c3bb535 | jiahenglu/VeblenWedderburn | /NumberSystem.py | 1,535 | 3.734375 | 4 | listoflists = []
list = []
for i in range(0,10):
list.append(i)
if len(list)>3:
list.remove(list[0])
listoflists.append((list, list[0]))
def numeric_compare(alist1, alist2):
list1 = alist1[0]
list2 = alist2[0]
for i in range(0,len(list1)):
if list1[i] != list2[i]:
... |
366a2e7916c31e2603b7db73a63ca71e574a8b87 | TNTian/Python-ASCII-art-generator | /ASCII art generator.py | 2,131 | 3.703125 | 4 | from PIL import Image, ImageFont, ImageDraw
def image_to_text(image, resize_width, resize_height, textFile):
codeLib = '''@B%8&WM#*o@BdpqwmZO0QLCJUYXzcvunxrlINt\|()1{}[]?-_+~<>i!lI;:,"^`'. '''
length = len(codeLib) # length of codeLib 69
print(image.size)
image = image.resize((int(image.size[0... |
f02ac49567bc1f4089fcc75e4307c397ffc9cdf0 | saurabhpati/python.beginner | /OperatorsAndConditionals/elif.py | 535 | 4.40625 | 4 | # elif keyword is used to make the else if statement in python
# Requirement for this example: User gives the amount.
# 1. If amount is less than 1000, discount is 5%
# 2. If amount is less than (or equal to) 5000, discount is 10%
# 3. If amount is more than 5000, discount is 15%
amount = input('Enter the amount: ');
... |
e0904227f93e82295153e04d9ffdaeb41d5ebc56 | saurabhpati/python.beginner | /Functions/lambda.py | 256 | 3.75 | 4 | # Lambda functions have a single statement and cannot contain multiple expressions.
multiply = lambda number1, number2 : number1 * number2;
number1 = int(input('Enter number1:'));
number2 = int(input('Enter number2:'));
print(multiply(number1, number2)); |
fe5b725a5760c7c55a3aeff33b85cce2aaa6aa5a | saurabhpati/python.beginner | /Lists/list-operations.py | 1,426 | 4.5 | 4 | # iterating over a list.
testList = [1, 2, 3] ;
for x in testList:
print(x, end='\n');
# extend will the given list to the list on which extend is called.
languagesKnownList = ['c#', 'javascript','python'];
languagesKnownList.extend(testList)
print('Languages known and extended:', languagesKnownList);
# appe... |
62972556afefe4a6c26da77fd13bde13ab18da94 | saurabhpati/python.beginner | /OOP/manager.py | 491 | 3.6875 | 4 | from base_employee import BaseEmployee;
class Manager(BaseEmployee):
def __init__(self, name):
self.designation = 'Manager';
self.name = name;
# This printEmployee method is overriden from BaseEmployee.
def printEmployee(self):
if hasattr(self, 'id'):
print('Id:', s... |
c62411f0248c2c1a680a7d385be98cdfd672f2eb | saurabhpati/python.beginner | /Math/roundOff.py | 269 | 3.78125 | 4 | # round function rounds the value upto the given input decimals.
# example round(100.12) will give 100, round(100.29,1) will give 100.3
# round(100.264, 2) will give 100.26
print(round(100.8)); # 101
print(round(100.264, 3)); # 100.264
print(round(100.29, 1)); # 100.3 |
3ec9c0250c484d50af12a557650e415956c1303f | saurabhpati/python.beginner | /OperatorsAndConditionals/arithmetic.py | 287 | 4.3125 | 4 | # This programs intends to highlight between the differences of '/' and '//' operators.
x = input('Enter the dividend: ');
y = input('Enter the divisor: ');
x = int(x);
y = int(y);
print('x/y = ', x/y);
print('x//y = ', x//y);
print('divident raised to the power of divisor = ', x**y); |
aa777b032c029a381336ebf7ba0b2b0e491ba57d | zhzixuan/Deep-Learning | /Assignment1/Part1/q1.py | 7,532 | 4.03125 | 4 | import numpy as np
from datasets.toy_data import xor_3_input
# from datasets import toy_data as xor_3_input
def sigmoid(x):
"""
Compute the sigmoid function.
"""
### YOUR CODE HERE
s = 1 / (1 + np.exp(-x))
### END YOUR CODE
return s
def sigmoid_grad(x):
"""
Compute... |
7ccb89204ac0544c84e474c8ab8fec69a04d28a1 | Rujabhatta22/program1 | /program3.py | 109 | 4.28125 | 4 | radius=float(input('enter radius of cricle'))
pi=3.14
area=pi*radius^2
print(f'the area of circle is{area}')
|
a9ffc17d0d69c5e6d130a2cc2ed64357572f2986 | Shen-po-heng/LeetCode_Practice | /84_Largest Rectangle in Histogram.py | 974 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 27 00:15:49 2021
@author: shenpaul
"""
#still not correct
class Solution(object):
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
left=0
right=len(heights)
MostWater=0
... |
1fa6d9a7dcd6862983b5f6460204a8fa786958f8 | Shen-po-heng/LeetCode_Practice | /15_3Sum.py | 1,209 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 27 00:18:35 2021
@author: shenpaul
"""
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
#sort the list at first
nums.sort()
arr=[]
#print(... |
2e5261371e3c74ea12b51a3c3dbf39ff6551402a | Shen-po-heng/LeetCode_Practice | /334_Increasing Triplet Subsequence.py | 821 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 27 00:17:44 2021
@author: shenpaul
"""
class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
Num01 = Num02 = float("inf")
for i in nums:
print(i,Num01,Num02)... |
3780b2fa4c7883dbd760ac52830406c9971957ec | Already-Ready/CtCI_Python | /Ch_4/Q4_9_bst_sequence.py | 1,508 | 3.703125 | 4 | import unittest
class Node():
def __init__(self, data, left = None, right = None):
self.data = data
self.left = left
self.right = right
def bst_sequence(partial, subtrees):
if not subtrees:
return [partial]
sequence = []
for index, node in enumerate(subtrees):
... |
9723753d463b5333c26685a204a0f10c4ae75930 | Already-Ready/CtCI_Python | /Ch_5/Q5_2_Binary_to_String.py | 729 | 3.796875 | 4 | import unittest
def toBinary(num):
if num <= 0 or num >= 1:
return "ERROR"
binaryString = "0."
while num > 0:
if len(binaryString) >= 32:
return "ERROR : This num is too Long Binary"
double = num * 2
if double >= 1:
binaryString += "1"
... |
531c8e7310c497b92202accb2b9477e5605e5957 | burakonal89/edu-projects | /pycharm_projects/HackerRank/10 Days of Statistics/1_2.py | 351 | 3.984375 | 4 | import math
def findMean(numbers):
return float(sum(numbers)/len(numbers))
def findVariance(numbers):
mean = findMean(numbers)
sum = 0.0
for number in numbers:
sum += (number-mean)**2
return math.sqrt(sum/len(numbers))
n = raw_input()
numbers = [int(i) for i in raw_input().split(" ")]
pri... |
037f5d7ef8e0bdc4b95998f1993e77be2c8a907c | zaiahkoh/bubble-tea | /visual_distr.py | 3,606 | 3.890625 | 4 | """
The purpose of this file is to illustrate the concepts of distributions.
You are not required to understand the code.
"""
import matplotlib.pyplot as plt
import numpy as np
import ipywidgets as widgets
from scipy.stats import norm
import pandas as pd
def update_x(x):
"""Function for updating the chart with ... |
a0050a3c5375653743e52283756fbe648cb01e62 | kazmanbanj/Practice_on_Python | /file io/script.py | 953 | 4.1875 | 4 | # my_file = open('test.txt')
# print(my_file.read())
# my_file.seek(0)
# print(my_file.read())
# my_file.seek(0)
# print(my_file.read())
# print(my_file.readlines())
# my_file.close()
# Standard way to Read, write, append in python
# with open('test.txt', mode='r+') as my_file:
# print(my_file.readlines()... |
858b0398f6fc27df6131f912954599628fcb3e6d | kazmanbanj/Practice_on_Python | /python basics1/main.py | 6,818 | 4.15625 | 4 | #Fundamental data types
int, float, bool, str, list, tuple, set, dict
#Classes - custom types
#specialized data types
# None
# int and float
print(type(2 + 4))
print(type(2 - 4))
print(type(2 / 4))
print(type(2 * 4))
print(type(2 ** 4))
print(type(2 // 4))
print(type(2 % 4))
# math fun
print(round(3.0))
print(ab... |
2a72917723970899328c9c335f888ec542d7976f | rachelbates/coding-challenges | /leet/palindrome.py | 561 | 3.9375 | 4 | x = 1234321
def palindrome(x):
return False if x < 0 else x == int(str(x)[::-1])
# x = str(x)
# length = len(x)
# if length == 1:
# return True
# if int(x) < 0:
# return False
# if length % 2 != 0:
# odd = 1
# middle = int(length/2) + odd ... |
a82449106366c7ec31d8dad27d8dfcb7e6f8e969 | rachelbates/coding-challenges | /adventcode/Day1/p2.py | 883 | 4.09375 | 4 |
#Extract list of numbers from file
def extract_list_file(the_file):
opened_file = open(the_file)
numbers = []
for line in opened_file:
numbers.append(int(line.rstrip()))
opened_file.close()
return numbers
# #Find 2 entries that total to the sum
# def find_three_entries(numbers, tar... |
656b258f65243b4547e029a49b6266504a81a9ad | ffsedd/qq | /qq/qq_inspect.py | 1,293 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
def f_args_log(func):
'''Decorator to print function call details - parameters names and effective values'''
from functools import wraps
import logging
@wraps(func)
def wrapper(*func_args, **func_kwargs):
arg_names = func.__code... |
47d6af487624d5495dfa3d07f91c6d4f0b81eb05 | kb9zzw/arcpy_scripts | /parseHTMLimages.py | 593 | 3.578125 | 4 | #Name: parseHTMLimages.py
#Purpose: Parses and reports image tags out of a given URL
#Usage: parseHTMLimages.py <URL>
#Example: parseHTMLimages.py "http://www4.ncsu.edu/~lgtateos"
#Author: Jon Burroughs (jdburrou)
#Date: 4/12/2012
import sys, urllib2
sys.path.append("C:/Temp")
import BeautifulSoup as bs... |
c666e839c06a7dcb299706f8fb77bbccf29d1e70 | kb9zzw/arcpy_scripts | /distanceTry.py | 1,012 | 4.1875 | 4 | #Name: distanceTry.py
#Purpose: converts miles to kilometers or vice-versa
#Usage: distanceTry.py <numerical_distance> <distance_unit>
#Example: distanceTry.py 5 miles
#Author: Jon Burroughs (jdburrou)
#Date: 2/16/2012
import sys
# get distance value from user (assume they'll provide it correctly)
dist... |
97279647291a461d4413c840cd8d5b2e6aa7dd17 | harry-sparta/eng_48_txt_editing | /user_name_db.py | 668 | 3.9375 | 4 | from functions import *
## Variable = text document to be read
file_user = 'user_name.txt'
## Creating an empty dictionary
user_dict = {}
## Calling read function to return content in file_user
file_user_list = file_read(file_user)
print(file_user_list)
## Setting a counter to count and name user object in for loop be... |
b72976c22d23658a0fae17a700cc4fc53b4822b5 | sugaofeng/cracking-the-coding-interview-python-solution | /Chapter 4/Q4_5.py | 1,500 | 3.8125 | 4 | from classes.BinaryTreeNode import *
import sys
# In-order traversal, and compare an element to the previous one
def isBST1(btree):
return checkBST1(btree)[0]
def checkBST1(btree, previous = -sys.maxint-1):
if btree is None or btree.value is None:
return True, previous
[isleftbst, previo... |
c89ce1be0de4860d62271f788469fd73ac50f7a3 | sugaofeng/cracking-the-coding-interview-python-solution | /Chapter 1/Q1_3.py | 634 | 3.96875 | 4 | def isPermutation(string1, string2):
if len(string1) != len(string2):
return False
dic = {}
for char in string1:
dic[char] = dic.get(char, 0) + 1
for char in string2:
if dic.get(char,0) <= 0:
return False
else:
dic[char] -= 1
return True
#--... |
85184d7002085c64b69844eded5ab385810b16df | StanHaakman/HU_AI_Blok_C | /Structured Programming/Mastermind.py | 12,176 | 3.953125 | 4 | from random import randint, choice
from itertools import *
gamestarted = False
first = True
feedbackgiven = False
soclose = False
allnums = [1, 2, 3, 4, 5, 6]
choicelist = []
colorcode = []
notnum = []
allcombos = []
newcombos = []
usedcombos = []
print("welcome")
def welcome():
#Just some giberish to lead the... |
4e97126402920dfe74274cca75890fe7a8851961 | myton/head_first_python | /ch06/Athlete.py | 650 | 3.671875 | 4 | class Athlete:
def __init__(self, a_name, a_dob=None, a_times=[]):
self.name = a_name
self.dob = a_dob
self.times = a_times
sarah = Athlete('Sarah Sweeney', '2002-6-17', ['2:28', '2.58', '1.56'])
james = Athlete('James Jones')
print ('type(sarah)')
print (type(sarah))
print (">>> sarah ")
print (sarah)
p... |
3a651cddce3a68306e2d94084808a6df085aa16d | Glayfang/quanbaobao | /test.py | 96 | 3.53125 | 4 | # -*- coding: utf-8 -*-
a=1
b=2
if a<b:
break
elif a>b:
print(111)
else :
print(222) |
f4b7f5bda5fa1a541ed33cba2ed098cb79eb6f97 | hayeon9792/Python_IoT | /0430_CH1_3.py | 2,643 | 3.96875 | 4 | # 한 줄 주석
"""
20180430 Day-1
여러 줄 주석
"""
"""
print("Hello world!")
a = 100
b = 100
result = a+b
print(a + b)
print(a, "+", b , "=" , result)
"""
"""
restart shell => ctrl + f6
변수의 자료형 확인 => type(a)
"""
"""
a = 100
b = 50
result=a+b
print(a,"+",b,"=",result)
result=a-b
print(a,"-",b,"=",result)
result=a*b
print(a,"*",... |
695ff7e838702058a89199decdcc3e9b6110c675 | hayeon9792/Python_IoT | /0510_CH9_10.py | 8,385 | 3.671875 | 4 | '''
## 변수 선언 부분
ticket, sel, person = 0, 0, 0
## 메인(main) 코드 부분
ticket = int(input("1.이용권 2.입장권 : "))
if ticket == 1:
sel = int(input("1.주간권 2.야간권 3.2일권 : "))
elif ticket == 2:
sel = int(input("1.주간권 2.야간권 : "))
person = int(input("1.대인 2.청소년 3.소인/경로 : "))
if ticket == 1:
if sel == 1:
if person =... |
a1a38bcdbc0a6a4f99fb819022496f4a421cfd80 | xiangwhy/untitled | /ex04.py | 643 | 3.8125 | 4 | __author__ = 'xiang_000'
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers # 100-30=70
cars_driven = drivers # 30
carpool_capacity = cars_driven * space_in_a_car # 30*4.0=120.0
average_passengers_per_car = passengers / cars_driven # 90 / 30=3.0
print("There are", cars, "... |
6f3d2881cdd2ab5cf54ab085d11b69be44cf38f9 | DvidGs/Python-A-Z | /9 - Funciones en Python/ejercicio 6.py | 1,515 | 4.5 | 4 | # Ejercicio 6
# Crea una función que devuelva el MCM (mínimo común múltiplo) de 2 números proporcionados por
# parámetro.
# PISTA: Aprovecha la función que calcula el MCD de dos números del ejercicio anterior y la función que
# calcula el valor absoluto de un número.
def bigger(a, b):
"""
Devuelve el mayor num... |
e4c25314eaab9261336eeff4f0160a3ba72ecea6 | DvidGs/Python-A-Z | /3 - Operadores de decisión/ejercicio 5.py | 1,016 | 4.3125 | 4 | # Ejercicio 5
# Haz que un usuario introduzca dos números enteros positivos. Suponiendo que el primer número introducido
# por el usuario es mayor o igual al segundo número introducido por el usuario, comprueba que la división del
# primer número entre el segundo número es entera.
# En caso de la división ser entera, d... |
69e6e1a8cc493929a6b5f64950608d2adcd1674d | DvidGs/Python-A-Z | /7 - Estructuras de datos: Conjuntos/ejercicio 4.py | 325 | 3.8125 | 4 | # Ejercicio 4
# Dado un conjunto, crea un programa que nos devuelva el caracter con mayor valor ASCII. Debes hacerlo sin
# recurrir a la función max().
valor = {1, 2, "A", "E", "@"}
max = -9999
for i in valor:
if ord(str(i)) > max:
max = ord(str(i))
print("El caracter con mayor valor ASCII es: ", chr(max... |
dac2ff0605cec22524cc4a34b283818a599f2e21 | DvidGs/Python-A-Z | /6 - Estructuras de datos: Diccionarios/ejercicio 5.py | 381 | 3.8125 | 4 | # Ejercicio 5
# Crea un programa que lea números enteros hasta que introduzca el 0 y devuelva un diccionario con la
# cantidad números pares e impares introducidos.
n = int(input("Número entero: "))
par = 0
total = 0
while n != 0:
if n % 2 == 0:
par +=1
total += 1
n = int(input("Número entero: "))... |
5cb01fe5970e14264deed6610df0362372d5bcd3 | DvidGs/Python-A-Z | /6 - Estructuras de datos: Diccionarios/ejercicio 9.py | 486 | 3.953125 | 4 | # Ejercicio 9
# Crea un programa que pida el número de palabras a introducir. Crear un diccionario de clave la palabra y
# de valor el número de vocales de la palabra.
numero = int(input("¿cuántas palabras va a introducir? "))
palabras= {}
contador = 0
for i in range(numero):
palabra = input("palabra: ")
for ... |
f2ed6a48d9cac7a7c869294bbfcf9de98d0067f2 | DvidGs/Python-A-Z | /9 - Funciones en Python/ejercicio 8.py | 1,277 | 4.03125 | 4 | # Ejercicio 8
# Crea una función que dado un color en hexadecimal devuelva una lista de 3 posiciones, cada una de ellas
# correspondiente al valor R, G o B en este orden. Los valores de RGB varían entre 0 y 255.
def hex_to_decimal(hex_num):
"""
Dado un número dexadecimal en formato string lo transforma a númer... |
d46575b716c6c25c4105f75a905fb449dda92c25 | DvidGs/Python-A-Z | /10 - Funciones Lambda/ejercicio 6.py | 491 | 3.921875 | 4 | # Ejercicio 6
# Dada una lista de palabras, calcula el número de vocales de cada una con map().
def total_vowels(w):
"""
Devuelve el total de vocales de una palabra
:arg
:param w: palabra en formato strinng
:return:
:cosonants: Número entero
"""
vowels = 0
for c in w:
if... |
04303264a5f312c096fd49ec57e00bac891092f4 | DvidGs/Python-A-Z | /9 - Funciones en Python/ejercicio 4.py | 485 | 3.90625 | 4 | # Ejercicio 4
# Crea una función que devuelva True si el caracter introducido por parámetro se trata de una vocal y False
# en caso contrario.
def is_vowel(c):
"""
Devuelve si el caracter dado es una vocal.
Args:
c: Caracter
Returns:
Booleano
"""
if len(c) == 1:
if c.low... |
b26ab0b7012e79d594453095aaeb954c860b90bd | DvidGs/Python-A-Z | /2 - Strings en Python/ejercicio 7.py | 233 | 4.0625 | 4 | # Ejercicio 7
# Con la función input(), indícale al usuario que introduzca su apellido y guárdalo en la variable llamada
# apellido
print("introduzca su apellido: ")
apellido = input()
print("su apellido es {}".format(apellido)) |
8c45ff286a26c9104e3c4fa2bbb36de1062d17be | nabeel-m/python_hardway | /ch01/ex25.py | 429 | 4 | 4 | the_count =[1,2,3,4,5]
fruits =['apple','orange','pears','apricot']
change =[1,'pennies',2,'dimes',3,'quarters']
for number in the_count:
print(f"This is count {number}")
for fruit in fruits:
print(f"A fruit is type{fruit}")
for i in change:
print(f"I got {i}")
elements=[]
for i in range(0,6):
... |
431f7e20d56b5a183041a26b50eb2dcd62b1ed8b | nabeel-m/python_hardway | /ch01/ex26.py | 225 | 3.984375 | 4 | i = 0
numbers =[]
while i < 6:
print(f"At the top of i is{i}")
numbers.append(i)
i=i+1
print("number is",numbers)
print(f"At the bottom of i is {i}")
print("numbers")
for num in numbers:
print(num)
|
6755586a6609542d108ed95c4c93201ab7ad0440 | suyeon-yang/Saturday-Class | /main.py | 1,241 | 3.828125 | 4 | def box ():
for row in range (1,11):
digit = row
for col in range (1,11):
print(digit % 10, end = "")
digit += 1
print()
def withwhile():
for i in range(9):
fact = i + 2
print("{}!=".format(fact),end = "")
digits = 1
while digits < fact:
print("{}*".format(digits)... |
cbeb4d467ea1b62bc6b1290fdecc70e01e70022a | openml-labs/gama | /gama/utilities/generic/stopwatch.py | 1,015 | 3.734375 | 4 | import time
class Stopwatch:
"""A context manager that keeps track of wall clock time spent."""
def __init__(self, timing_function=time.time):
"""
Parameters
----------
timing_function: Callable (default=time.time)
The function used to measure time, e.g. time.time... |
9dfafbdd65869dc60caf8e377838be1237441662 | arujbb/myrzaiim | /lisson7/hw.py | 791 | 3.546875 | 4 | plane = [
["*", "*", "*"],
["*", "*", "*"],
["*", "*", "*"],
]
def check_winner(p):
win = True
for i in range(3):
row = plane[i]
start = ""
for k in row:
if k == "*":
win = False
break
if not start:
sta... |
33ee9d993b9acf8c31adf29dfe9cea37a4005241 | AndruOn/Python-LEPL1401_UCL | /partie8 dictionaires/mission 7/M7-dico.py | 3,550 | 3.71875 | 4 |
def readfile(filename):
'''pre : filename est un fichier
post : retourne une liste comprenant tous les lignes du fichier'''
with open(filename,"r") as f:
text= f.read()
l=text.split("\n")
return l
def get_words(line):
'''pre : line est une chaîne de caractères
... |
0e5436b00f1ed7c0e0099eb3a7707d3f5ea73eb7 | AndruOn/Python-LEPL1401_UCL | /partie8 dictionaires/fin de sem.py | 748 | 3.71875 | 4 | def create_dic(words):
d={}
for word in words:
d[word]=d.get(word,0)+1
return d
def top_k(words,k):
d=create_dic(words)
l=[]
for key in d:
l.append((d[key],key))
print("l créé")
l= sorted(l,reverse=True)
ll=[]
k2=0
print("liste inversée")
while k2 <= k:
... |
04d2921af691fd973cd7935aa9ad5e546f5ce76e | AndruOn/Python-LEPL1401_UCL | /Partie10 classes objets/ex APE.py | 1,274 | 4.09375 | 4 |
class Student :
def __init__(self,n) :
"""
Initialise un nouvel objet de type Student avec un nom n donné.
@pre: -
@post: Un objet de type Student a été créé avec comme 'name' n,
et un score None pour chacun des trois tests 'test1', 'test2' et 'test3'
"""
... |
d025deb31af17aa526f0cfd6584899ef4d7bd704 | AndruOn/Python-LEPL1401_UCL | /Partie10 classes objets/Mission musique/Spotify de pauvre.py | 3,624 | 3.734375 | 4 |
class Duree:
def __init__(self,h,m,s):
h= int(h)
m= int(m)
s= int(s)
if m >= 60 and m < 60 or s >= 0 and s < 0:
print("Minutes ou secondes non valides")
return
self.h=h
self.m=m
self.s=s
def toSeconds(s... |
d5bdea1bdf0ae8fa9a8d912a295d1a2c74f16201 | aedwardg/AdventOfCode-2020 | /Python/02regex.py | 914 | 3.765625 | 4 | import re
pattern = re.compile(r'^(\d+)-(\d+) (\w): (.+)$', re.MULTILINE)
with open('02.txt', 'r') as f:
passwords = pattern.findall(f.read())
def valid_password_by_letters(low: int, high: int, letter: str, password: str) -> bool:
return low <= password.count(letter) <= high
def valid_password_by_pos(low: i... |
4f15f30cf4a6bc5a8247db23aa664317899a4c34 | sravich2/bullshit | /bullshit/client.py | 11,116 | 3.578125 | 4 | # https://www.raywenderlich.com/38732/multiplayer-game-programming-for-teens-with-python
import getopt
import sys
from time import sleep
from PodSixNet.Connection import ConnectionListener, connection
import pygame
import pygbutton
from bet import Bet
from card import Card, CardValue
class Game(ConnectionListener):... |
749a4cbdfed7794be4d275ab6db22341f81c3eca | swcjack6931677/ERINN | /erinn/python/utils/np_utils.py | 1,600 | 3.5625 | 4 | """Numpy-related utilities."""
from __future__ import division, absolute_import, print_function
import numpy as np
def rand_replace_elem(x, ratio, fill=0, inplace=True):
"""Random replace array with specific value at certain ratio.
Parameters
----------
x : numpy.ndarray
2D array.
ratio ... |
bb7cd640891e3e371ab66bac12b43aca22f0a20f | laboon/PythonScripts | /aliquot.py | 1,389 | 3.890625 | 4 | def get_proper_divisors(n):
return [x for x in range(1,n-2) if not divmod(n,x)[1]]
def get_aliquot_sum(x):
return sum(get_proper_divisors(x))
n = int(raw_input("Enter starting value n (positive int): "))
init = n
max = int(raw_input("Enter maximum iterations: "))
print "Aliquot sequence for " + str(n)
cnt = 0
tmp_... |
48fce9095357591db90140cd25bfdb08e0cdcfc6 | laboon/PythonScripts | /euler12.py | 650 | 3.84375 | 4 | import math
def generate_tri(x):
return (x * (x +1)) / 2
def factors(n):
for x in xrange(1,n):
if n%x == 0:
return (x,) + factors(n/x)
print n
return (n,1)
def get_divisors(x):
max = x
numDivs = 0
j = 1
numDivs = len(factors(x))
return numDivs
cont = True
cand... |
cc6cc66695996be72427cbf515cec98af948d524 | BuildGK/hack-help | /python_scripts/http_check_resource.py | 808 | 3.671875 | 4 | import http.client
print("** This program checks if a specific resource is available on the webserver **\n")
host = input("Insert the host/IP: ")
port = input("Insert the port(default:80): ")
url = input("Insert the url: ")
if port == "":
port = 80
try:
connection = http.client.HTTPConnection(host, port)
... |
d35f70ffe70b684c210129fd0ddceed3c30cc282 | qpwoeirut/python_book_work | /book_work/22_Divisible.py | 192 | 3.6875 | 4 | for num in range(1,100001):
def divisible(inta = []):
if num % inta == 0:
print(num, 'is divisible by', inta)
for value in range(2,100001):
divisible(value) |
2fbb31d6ea051260551205126fac7c5532ce22e7 | qpwoeirut/python_book_work | /book_work/21_Dictionary.py | 468 | 4.34375 | 4 | stanley = {'age': '11', 'birthday': 'August 24, 2005','school': 'Bowman School', 'grade': '6th', 'activities': 'soccer, coding, and video games', 'family': 'Nan Zhong(Father), Yun Luo(Mother), Randy Zhong(Brother)'}
print(stanley['school'])
today = {'year': '2017', 'month': 'June', 'day': '13'}
today['weekday']= 'Tues... |
b853c57ce6ae24cd0001cf225395cf98a7a6b614 | h-shreesha/File-Structure-lab-programs | /fs_lab4.py | 2,057 | 3.90625 | 4 | class student:
def __init__(self):
self.usn = input('Enter usn: ')
self.name = input('Enter name: ')
self.branch = input('Enter branch: ')
self.sem = input('Enter sem: ')
def insert(storefile, s):
record = s.usn+'|'+s.name+'|'+s.branch+'|'+s.sem+'#'
storefile.writ... |
201f80110bccfa0f88a135be78b09bce7269af85 | ciscowh/Python-test | /D1/Python_first.py | 166 | 4.03125 | 4 | str_1='计算1+2的结果'
str_2='计算结果为:'
str_3=1+2
print(str_1)
print(str_2,str_3)
# result = 1 + 2
# print('计算 1 + 2 的结果为:' + str(result))
|
68f5dc37f23b5c29ac2eb42e991fb6fc1be22e9b | jayendra-patil33/python_lab_programming | /Prime_till_num.py | 231 | 3.546875 | 4 | # Jayendra Patil
# roll no: 19, gr no: 11810706
# To check prime till a given number
n=int(input())
for i in range(1,int(n)):
for j in range(2,(i+1)):
if i%j==0:
if i==j:
print(i)
break |
8713d7b1db28ea750666376aecce9231393655bf | PromytheasN/Project_Euler_Solutions_1-10 | /Task 5 Solution.py | 1,201 | 4.1875 | 4 | import numpy
def small_divident():
"""
This is a function that calculates the smallest divident number,
evenly divisable by all numbers between 1 to 20.
"""
#If our number is evenly divisable with the list bellow, it should be evenly divisable with
#1 to 10 as well as all the numbers bell... |
13d0411298bcba34dd26eafec9029efcc8da626d | wansang93/Python | /How to use Python in Silicon Valley/18. Libraries Tools and Tips/236. format 표기.py | 1,474 | 3.578125 | 4 | # formating 과 f-string을 비슷하게 사용할 수 있어서 f-string으로 표현하였습니다.
t = (1, 2, 3)
# 1. 기본적인 사용법
print(f'{t[0]}, {t[2]}')
# 1, 3
print('{0} {2}'.format(*t))
# 1 3
# 2. 빈공간 만들기
center='center'; fill='*'; align='^'; width=30
left = 'left'; right = 'right'
print(f'{left:<30}')
print(f'{right:>30}')
print(f'{center:^30}')
print(f'... |
f09c2d9ecbb087d152ec56da431385430eb744aa | wansang93/Python | /How to use Python in Silicon Valley/18. Libraries Tools and Tips/243. functools.partial.py | 477 | 3.578125 | 4 | import functools
# 방법1
def f(x, y):
return x + y
def task(f):
print('start')
print(f(10, 20))
task(lambda x, y: x+y)
# start
# 30
# 방법2
def outer(x, y):
def inner():
return x + y
return inner
def task2(f):
print('start')
print(f())
f = outer(30, 20)
task2(f)
# start
# 50
# ... |
bc941cb4678acf624296de33a4837e8bcdd8ca4c | wansang93/Python | /How to use Python in Silicon Valley/09. Coding the Simple Application/robot_project/robot_app/models/robot.py | 969 | 3.765625 | 4 | """Defined a robot model """
from robot_app.views import console
DEFAULT_ROBOT_NAME = 'Ronaldo'
class Robot(object):
"""Base model for Robot."""
def __init__(self, name=DEFAULT_ROBOT_NAME, user_name='',
speak_color='green'):
self.name = name
self.user_name = user_name
... |
0b074161887e99edef01fddf54c18e978390b133 | wansang93/Python | /Basic & ComputerVison/Code/Code03-05 if 문 응용.py | 222 | 3.859375 | 4 | import random
numbers = []
for _ in range(0, 10) : # for (i=0; i<10; i++)
numbers.append(random.randint(0,9))
print(numbers)
for num in range(0, 10) :
if num not in numbers :
print(num, '이 없어요') |
fedcaaaf97ebd8a825de45e99dad718494ab902f | TaoChiuRui/phamnhatthanh-fundamental-c4e35 | /Session 3/Homework/turtle1.py | 195 | 3.9375 | 4 | from turtle import *
colors = ['red','blue','brown','yellow','grey']
for i in range (3,8):
color(colors)
for l in range(i):
forward(100)
left(360/i)
mainloop()
|
6429502147fdc3a840c8cf0043c099a5899d6efe | AlessandroCaula/Programming_Alessandro_Caula | /Script/sort.py | 732 | 3.578125 | 4 | #ORDINARY SORT
A=[7,6,5,4,3,2,1]
for j in range(1,len(A)):
key=A[j]
i=j-1
#j=j+1
while i>-1 and A[i]>key:
A[i+1]=A[i]
#print(A[i+1], A[i])
i=i-1
#print(i)
#print(i)
A[i+1]=key
print(A)
#MERGE SORT
A=[3,2,4,5,6,1]
# p=0
# r=len(A)
# def split(A,p,r):
# # if p>... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.