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 |
|---|---|---|---|---|---|---|
5c17e156ac00c2476a2797124987341a5832ce18 | yashrajput0508/telegram-app | /Responses.py | 3,284 | 3.5625 | 4 | data=[
"""Hey! I’m Nerd - your budgeting assistant. I’ll help setup budget, weekly targets and keep you on track. Select a goal to begin
Type option number
1. New Gadget, vacation etc
2. Investing money
3. Building emergency fund
4. Paying off debt
5. Just saving"""
,
"""
Your Income & Pay date?
Type (eg):... |
4c658fbcaac27160d8364f20eae90b67936372a2 | madisonmay/MotorControl | /plot.py | 701 | 3.671875 | 4 | import matplotlib.pyplot as plt
from matplotlib.axes import Axes
import mpl_toolkits.mplot3d.axes3d as p3
from math import radians, cos, sin, tan
#2D data points
real = []
#Division by axis for 2D plot
x, y = [], []
#load in csv
def load(filename):
f = open(filename, 'r')
for line in f:
time, pos =... |
24d6aed69f8b3fd58b086e41c5e830a2fe0ddb66 | KotaCanchela/PythonCrashCourse | /9 Classes/modules.py | 4,591 | 4.5625 | 5 | class Car:
"""A simple statement to represent a car."""
def __init__(self, make, model, year):
"""Initialise attributes to describe a car"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Ret... |
0eed4503d62e20fce3db85f562ca367224fc6d63 | KotaCanchela/PythonCrashCourse | /16 Downloading Data/death_valley_rainfall.py | 1,307 | 3.59375 | 4 | import csv
import matplotlib.pyplot as plt
from datetime import datetime
from matplotlib.pyplot import figure
filename = "/Users/Kota/Desktop/pcc_2e-master/chapter_16/the_csv_file_format/data/death_valley_2018_simple.csv"
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
# Get inde... |
b20c213ddbfc74344369b60b7b7ae977a82089d1 | KotaCanchela/PythonCrashCourse | /7 User input and While statements/cities.py | 624 | 4.0625 | 4 | # Using break to exit a loop
# Also adding input to dictionary for funsies
prompt = "\nPlease enter the name of a city you have visited: "
prompt += "\n(Enter 'quit' when you have finished)\n"
cities_visited = []
# A loop that starts with 'while True' will go forever until it reaches a break statement (no way to add... |
85e1e5c1adbc4daf79aaebaa31a2514e523dcef9 | KotaCanchela/PythonCrashCourse | /6 Dictionaries/pizza.py | 774 | 4.34375 | 4 | # Store information about a pizza being ordered.
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese']
}
# Summarise the order
print(f"You ordered a {pizza['crust']}-crust pizza with the following toppings: ")
for topping in pizza['toppings']:
print("\t" + topping)
# favourite languages... |
d42cbd34de99f30e6fb99a1a2aeb4f1f44e86683 | KotaCanchela/PythonCrashCourse | /9 Classes/electric_car.py | 3,526 | 4.84375 | 5 | # You don’t always have to start from scratch when writing a class.
# If the class you’re writing is a specialized version of another class you,
# wrote, you can use inheritance.
# When one class inherits from another, it takes on the attributes and methods,
# of the first class.
# The original class is called the pa... |
b3f906c56f714ca8d5e724b607dbe2e8d071b662 | KotaCanchela/PythonCrashCourse | /6 Dictionaries/favourite_languages.py | 1,860 | 4.5 | 4 | # Break a large dictionary into several lines for readability
# Add a comma after last key-value pair to be ready to add any future pairs
favourite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
sarah_language = favourite_languages['sarah'].title()
print(f"Sarah's f... |
9656f8e78d643569f078cf363ca57b4af32cb8ad | KotaCanchela/PythonCrashCourse | /9 Classes/9-8_Privileges.py | 1,844 | 4.28125 | 4 | # Write a separate Privileges class. The class should have one attribute, privileges,
# that stores a list of strings as described in Exercise 9-7. Move the show_privileges()
# method to this class. Make a Privileges instance as an attribute in the Admin class.
# Create a new instance of Admin and use your method to ... |
4d440d271bd189b22db644b888408fd001330c81 | KotaCanchela/PythonCrashCourse | /4 working with lists/4-6 Odd Numbers.py | 932 | 4.78125 | 5 | # “4-6. Odd Numbers: Use the third argument of the range() function
# to make a list of the odd numbers from 1 to 20.
# Use a for loop to print each number.
odd_number = [value for value in range(1, 21, 2)]
print(odd_number)
# 4-7. Threes: Make a list of the multiples of 3 from 3 to 30.
# Use a for loop to print the n... |
4262c4943e75c83ce8b337b8ec7a7802400760e5 | KotaCanchela/PythonCrashCourse | /10 Files and Exceptions/favourite_number.py | 784 | 4.46875 | 4 | # Write a program that prompts for the user’s favorite number. Use json.dump()
# to store this number in a file. Write a separate program that reads in this
# value and prints the message, “I know your favorite number! It’s _____.”
import json
def ask_number():
"""Asks the user for their favourite number and store... |
332454e2039df29fa6c379252da70dcbd5c8a532 | KotaCanchela/PythonCrashCourse | /7 User input and While statements/Counting.py | 609 | 4.375 | 4 | # Using continue in a loop
# continue allows the user to return to the beginning of the loop rather than breaking out entirely
# The continue statement tells Python to ignore the rest of the loop
# Therefore, when current_number is divisible by 2 it loops back
# otherwise when it is odd it goes to the next line (print... |
0fe235c13cec1fa605f7703cff4ac5f833c84243 | SamuelEsd/Algorithmic_Toolbox | /week3_greedy_algorithms/7_maximum_salary/largest_number.py | 727 | 3.9375 | 4 | #Uses python3
import sys
def greater_than(a,b):
max_len = max(len(a),len(b))
min_len = min(len(a),len(b))
count = 0
while(count < max_len):
if(count < min_len):
if(a[count] == b[count]):
count += 1
continue
elif(a[count] < b[count]):
... |
211e3b39a03b1ccbe68f5f18b6da1cf88f02898f | acarso02/QTA | /quantTradingAlgorithm/main.py | 5,584 | 3.75 | 4 | # -*- coding: utf-8 -*-
from pandas_datareader import data
import pandas as pd
import datetime as dt
class ClassifyBar:
__near = 0.005 #Definition of "close enough" used in is_doji method
def __init__(self, open, close, high, low, volume, date = dt.datetime(2018, 5, 3)):
self.op... |
d1f91590be9cb6bda3fa5e84f55852cd98eb356e | xanthoc/sql | /07_sql.py | 340 | 3.9375 | 4 | import sqlite3
with sqlite3.connect("new.db") as conn:
c = conn.cursor()
c.execute("UPDATE population SET population=9000000 WHERE city='New York City'")
c.execute("DELETE FROM population WHERE city='Boston'")
for row in c.execute("SELECT city, state, population FROM population"):
for item in row:
print(item,... |
38cd736639a4de8ed99364a77ca05ed7644424a5 | woodfi/Re-choose | /index.py | 1,268 | 3.890625 | 4 | # Import the modules
import sys
import random
again = "y"
while again == "y":
question = raw_input("Ask Re-choose a question: ")
answers = random.randint(1,12)
if question == "":
sys.exit()
elif answers == 1:
print "For sure"
elif answers == 2:
print "Ex... |
0996ebc4e6c6f5cd40444d1ddd1a5d3a82232b95 | ERJLSC/Python | /4_12_Auto_Invoice.py | 1,218 | 3.703125 | 4 | total=0
# dictionary of services and prices
svc_dict={
'Oil change':35,
'Tire rotation':19,
'Car wash':7,
'Car wax':12
}
# print header
print('Davy\'s auto shop services')
# rather than "if" every item in the dictionary, we will use the "for" loop
for item in svc_dict:
print(item + ... |
24769369f92024515a49dcc7f40bd6e6e19e2a02 | ERJLSC/Python | /Ch_8_Extra.py | 13,435 | 3.78125 | 4 | import random
def get_Menu_Input(my_rainfall):
usrInput='w'
while usrInput !='q':
print()
print(' Main Menu')
print('1 Rainfall Stats')
print('2 List Functions')
print('3 Encryption')
print('4 Dictionary Methods')
print('q Qu... |
81209a237f8de4fd37b69fcfd2a83e0780b9c072 | stali1234/open-cv2--image-convertor- | /image-convertor.py | 241 | 3.53125 | 4 | import cv2
from matplotlib import pyplot as plt
img = cv2.imread('hell.png')
#change the color using the channels provided by the inbuilt python convertor
new_img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
plt.imshow(new_img)
plt.show() |
51efa628d367c3baf627f9eb226811aeef768994 | NuGelaLies/python-practise | /Day1/string.py | 570 | 3.921875 | 4 |
string = 'hello world'
print('字符串长度: %s' % (len(string)))
print('单词首字母大写 %s:' % (string.title()))
print('字符串大写: %s' % string.upper())
print('字符串小写: %s' % string.lower())
print('字符串判断大小写: %s' % string.isupper())
print('字符串开头是不是hello: %s' % string.startswith('hello'))
print('字符串是否是以hello结尾: %s' % string.endswith('hello... |
39c1def98f14bbf795559e796cea11627ba84a36 | davidetacchini/projecteuler | /030/sol.py | 231 | 3.671875 | 4 | def is_sum(n):
return sum(int(d)**5 for d in str(n)) == n
def solve():
res = 0
for i in range(10, 10**6 // 2):
if (is_sum(i)):
res += i
return res
if __name__ == "__main__":
print(solve())
|
2c0f70a8ace63bd7d5319cf58d5c6082cbf4b281 | ds18b20/Keras_Tutorial | /01_mnist_fc.py | 1,755 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Train a Fully-Connected Neural Network(MLP) classification on MNIST dataset
MLP: Multi-Layer Perceptron
Use categorical_crossentropy loss
"""
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from... |
cba0ddedf988f37db0ae23ab08c00435922e70f5 | MAT49/universidad | /C Python Assembly Bash/hw3_English.py | 553 | 3.84375 | 4 | #!/usr/bin/python
import re
file = open('English_example', 'r')
#reads file
text = file.read()
file.close()
#replaces word with number
text = re.sub('one', '1', text)
text = re.sub('two', '2', text)
text = re.sub('three', '3', text)
text = re.sub('four', '4', text)
text = re.sub('five', '5', text)
text = re.sub('six',... |
4f23092abc8d6eda5c8ce520ea70d4e864eb8a75 | Zewzki/GaussianNetwork | /Gaussian.py | 4,621 | 3.5625 | 4 | import matplotlib.pyplot as plt
import numpy as np
from math import sqrt
from math import pi
from math import exp
def printGaussianList(arr, name):
print('{0}:'.format(name))
for xs in arr:
for cell in xs:
print(cell, end = '\t')
print()
print()
class Gaussian:
... |
cefb4142ffda596bf0e822678abdabac4209538b | OldLace/Python_the_Hard_Way | /may_19.py | 1,844 | 4.1875 | 4 | #May 19 - Paul Gelot
#Python the Hard Way - Exercise 12
num1 = int(input("Please enter a number: "))
num2 = int(input("Please enter another number: "))
total_sum = num1 + num2
subtract = num1 - num2
product = num1 * num2
division1 = num1 / num2
print("The sum of the two numbers is:", total_sum)
print("The difference... |
180c892336d6a048da555972c923c8968874cafc | OldLace/Python_the_Hard_Way | /hw4.py | 1,723 | 4.4375 | 4 |
# 1. Write a Python program to iterate over dictionaries using for loops
character = {"name": "Walter", "surname": "White", "nickname": "Isenberg", "height": "6 foot 7", "hobby": "trafficking"}
for i in character:
print(i,":", character[i])
# 2. Write a function that takes a string as a parameter and returns a ... |
d42f5290aa67eb2dad48b10d5b7f386f803a0b4f | allisgao/MyTools | /tax_calcute.py | 2,281 | 3.84375 | 4 | #! python3
# Author: George Gao, gaojz017@163.com
# 根据工资计算所得税以及到手的金额。本脚本以北京为例,
# Beijing
msg = "Your salary is %s.\nYou should pay %s.\nYou have %s."
condition = 1
while True:
salary = input("Please Input Your Salary(¥)\nPress any alphabet to quit :")
if salary.isdigit():
condition == 1
salary ... |
b56678091b66597c151cef1f46bc0847ef9c5fa1 | justinbthompson/myEE551projectPowerDemand | /ProgressCodes/Progress_01_20190420_AccessingURL.py | 1,615 | 3.9375 | 4 | ##VOID CODE
##This code was written to access URL of US Energy Information Administration
##Project now takes date from New York ISO
##Trial Code 1, Work done 4-20-2019
##This code is early trials of forming the URL wanted to reach from the requested date
#import requests #to be used to scrape data from URL
import t... |
c851ebf664c3ed4575b8141d48eb650fc1dc18aa | justinbthompson/myEE551projectPowerDemand | /ProgressCodes/Progress_03_20190420_GettingCorrectDataSet.py | 1,603 | 3.921875 | 4 | #TestCode_03
#TestCode to look for the correct data files given a certain date
#External libraries needed, must be installed
import pandas as pd #Python Data Analysis Library
#Python built-in libraries needed
from urllib.request import urlopen #To request data from URL
from io import BytesIO #To obtain zip file from U... |
54df2b1d58ec8e54e58b5c3796d133026683d493 | SahaanaIyer/dsci-greyatom | /spy_game.py | 2,933 | 3.515625 | 4 | # Path for file sample.txt is stored in file_path
# sample.txt contains message "This is a sample message."
# Path for file M1.txt is stored in file_path_1
# M1.txt contains message "2222"
# Path for file M2.txt is stored in file_path_2
# M2.txt contains message "2477"
# Path for file M3.txt is stored in file_path_3... |
d49cf149fb486f3fd72a986645f76ca9c5b040ca | Rashmi1664/Joy-of-Computing-using-Python-NPTEL | /Week 3/week3 - assignement ii.py | 149 | 3.5625 | 4 | #link for question
#https://onlinecourses.nptel.ac.in/noc19_cs09/progassignment?name=264
[print(i,end=' ') for i in input().split() if int(i)%3!=0]
|
5d12e017c0828c550c9b41cfe8819cfecc31069d | Rashmi1664/Joy-of-Computing-using-Python-NPTEL | /Week 3/week3 - jumbled_words.py | 1,636 | 3.90625 | 4 | import random
def read_words_from_file():
s = [];
with open('words.txt') as file:
for line in file:
s.append(line.strip());
return s;
def choose(words):
return random.choice(words);
def jumble(s):
return ''.join(random.sample(s,len(s)));
def check_answer(player,score,word):
... |
568b7ff05102d545afba14a2fac985b0b0f232d1 | gargarpan/assignement-9 | /ass9 q2.py | 541 | 3.6875 | 4 | class Student:
college = 'DIT'
def __init__(self, name, rno, marks):
self.name = name
self.rno = rno
self.marks = marks
def display(self):
print('Name: {}, RollNo: {}, Marks: {},'.format(self.name, self.rno, self.marks), end=' ')
print('College:', self.c... |
7b13a8fd8ed6d766ad5c6190da93e998c1323202 | di-wendy/Leetcode-Python | /19 Remove Nth Node From End of List.py | 979 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
globa... |
33222aa286b880cad00f71801d8aded8760c1c30 | di-wendy/Leetcode-Python | /167 Two Sum II.py | 527 | 3.671875 | 4 | class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
#Use double pointers head and tail
p1 = 0
p2 = len(numbers)-1
while(p1<p2):
... |
0a1c0a259543e4704dbc11a3a699227b6ee5abf4 | di-wendy/Leetcode-Python | /189 Rotate Array.py | 535 | 3.625 | 4 | class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
#Seperate in two piece and stitch them together
k = k%len(nums)
array1 =... |
3ca4edb198280d10b77492cd501170c380a6aec1 | sixfwa/computational-intelligence-cw | /lab-sign-off/python_code/utils.py | 1,018 | 3.671875 | 4 | import operator
def from_csv(file, skip):
data = []
with open("{}.csv".format(file), "r") as f:
content = f.readlines()
for i in range(skip):
content.pop(0)
for item in content:
new_item = item.rstrip()
new_item = new_item.split(',')
float_item = [float... |
0e53725479f0b1debe16892910e1f73c107bdf6c | Hermonhth/hthworkfolderv2 | /Python Practice/adventure v2.py | 2,778 | 4.0625 | 4 | # Vi Vu, Hermon Gebrehiwet
# monster room- you will need to rename this function.
from random import *
def heat_room():
# some prompts
# '\n' is to print the line in a new line
print("This is the heat room, you see a furance, you can: ")
print("1) Turn the heat up")
print("2) Leave the heat alone") # Activa... |
51f72b65f476209ce78a087d0c401548be8dbb34 | nivedipagar12/PracticePython | /E7_ListComprehensions.py | 882 | 4.28125 | 4 | '''
************* DISCLAIMER: THESE TASKS WERE POSTED ON https://www.practicepython.org ***********************************
************************* I AM ONLY PROVIDING SOLUTIONS ***************************************************************
Project/Exercise 7 : List Comprehensions (https://www.practicepython.... |
76100afdfbeaabc631e5375da7ce9d06553957d3 | nivedipagar12/PracticePython | /E24_DrawAGameBoard.py | 2,666 | 4.4375 | 4 | '''
************* DISCLAIMER: THESE TASKS WERE POSTED ON https://www.practicepython.org ***********************************
************************* I AM ONLY PROVIDING SOLUTIONS ***************************************************************
Project/Exercise 24 : Draw a Game Board (https://www.practicepython.o... |
17e09b72eba9b69ffed63b90d1ab3ceaec8b225a | nivedipagar12/PracticePython | /E1_CharacterInput.py | 1,894 | 4.28125 | 4 | '''
************* DISCLAIMER: THESE TASKS WERE POSTED ON https://www.practicepython.org************************************
************************* I AM ONLY PROVIDING SOLUTIONS ***************************************************************
Project/Exercise 1 : Character Input (https://www.practicepython.org/... |
c1827dc4cc1e6bacfd1c12cf126dc671283a542e | agutib/myFirstPy | /pythonTuts Files/receivingInput.py | 104 | 3.796875 | 4 | name = input("What is your Name?: ")
color = input("Favorate Color?: ")
print (namne + "Likes" + color) |
b7f755755d5ce91b39611c94889c3cd77f90ffb6 | dynes900alog/algorithms | /lintcode/ladder/design/groking/example-codes/cricinfo/account_type.py | 1,022 | 3.59375 | 4 | # For simplicity, we are not defining getter and setter functions. The reader can
# assume that all class attributes are private and accessed through their respective
# public getter methods and modified only through their public methods function.
class Player:
def __init__(self, person):
self.__person = p... |
cac833c4fe03ccd572f164a3aa91a2be83ce4c6d | dynes900alog/algorithms | /lintcode/ladder/design/groking/example-codes/atm/bank.py | 1,476 | 3.546875 | 4 | from abc import ABC
class Bank:
def __init__(self, name, bank_code):
self.__name = name
self.__bank_code = bank_code
def get_bank_code(self):
return self.__bank_code
def add_atm(self, atm):
None
class ATM:
def __init__(self, id, location):
self.__atm_id = id
self.__location = locat... |
2acdba60909073de27f9824ef211f311d869cc9d | Podolov/Python_labs | /PolynomialTests.py | 6,697 | 3.671875 | 4 | import unittest
from Polynomial import Polynomial
class PolynomTests(unittest.TestCase):
def test_init_empty_list_values(self):
p = Polynomial([])
self.assertEqual(p.coeffs, [0])
def test_init_zero_degree(self):
p = Polynomial([1])
self.assertEqual(p.coeffs, [1])
def t... |
a81f36182dee04cd838b6ce101acd217d309ab66 | poojajunnarkar11/CTCI | /CallBoxDevTest-3.py | 567 | 4.53125 | 5 | def is_power_two (my_num):
if my_num == 0:
return False
while (my_num != 1):
if my_num%2 != 0:
return False
my_num = my_num/2
return True
print is_power_two(18)
# Why this will work for any integer input it receives?
# -Because the while loop works until the number is... |
3600722a737572b901b604b1e4897beb0f974f1a | waoba/Python_basic_training | /formula_test.py | 427 | 3.984375 | 4 | def f(x):
return int(x)*3
ipt=input("input x value here")
result=f(ipt)
print(result)
ipt=input("write any sentence as you like")
result_l=len(ipt)
print(result_l)
def eo(x):
if x%2==0:
print("you entered even")
elif x%2==1:
print("you entered odd")
else:
print("you should etner... |
8cca35a1847a11729dbaf7efad93f141c16f75d0 | waoba/Python_basic_training | /chap14.py | 740 | 3.921875 | 4 | class Shape:
def __init__(self,number,name):
self.number=int(number)
self.name=name
def __repr__(self):
return self.name
triangle=Shape(4,"Pyramid")
print(Shape)
print(triangle)
print(triangle.number)
#Q1
class Square:
square_list=[]
def __init__(self,length):
self.leng... |
00404a17c4abb680cc7424d8e968d4b5bce4de82 | bsakers/Introduction_to_Python | /classes_three.py | 1,976 | 4.3125 | 4 | class Computer(object):
condition = "new"
def __init__(self, model, color, ram, storage):
self.model = model
self.color = color
self.ram = ram
self.storage = storage
def display_computer(self):
return "This is a %s %s with %s gb of RAM and %s gb SSD." %(self.color, se... |
c4f1a54798667c53eb6952afc1d0fe923c052803 | bsakers/Introduction_to_Python | /classes.py | 1,977 | 4.34375 | 4 | #general sytax for a class:
class NewClassName(object):
# code
pass
#in the above, we simply state the keyword 'class' and whatever we want to name it
#then we state what the class will inherit from (here we inherit from python's object)
#the 'pass' keyword doesnt do anything, but can act as a placeholder to n... |
027342a1e6c8fa72fc03ea820f4770209fa04f77 | bsakers/Introduction_to_Python | /enumerate.py | 463 | 4.6875 | 5 | #enumerate supplies a corresponding index as we loop
options = ["pizza", "sushi", "gyro"]
#normal for loop:
for option in options:
print option
#enumerator (note that "index" could be replaced by anything; it's just a placeholder)
for index, option in enumerate(options):
print index, option
#we can ev... |
325ab3f4d26130fd386bbdb3473ae5c7dbe9ca63 | bsakers/Introduction_to_Python | /pig_latin_translator.py | 376 | 4.125 | 4 | print 'Welcome to the Pig Latin Translator!'
original_word = raw_input("Enter a word you would like translated: ").lower()
ending = "ay"
if len(original_word) > 0 and original_word.isalpha():
translated_word = original_word[1:len(original_word)] + original_word[0] + ending
print translated_word
else:
prin... |
b0186723371fa9d3a524af5ca97616659405b99e | Hizudao/AbaqusPython | /rwExcel/xlsxWrite.py | 681 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
@author: ldn
"""
aDict = {'key1':'value1', 'key2':'value2', 'key3':'value3'}
print('-----------dict-------------')
for d in aDict:
print("%s:%s" %(d, aDict[d]))
print('-----------item-------------')
for (k,v) in aDict.items():
print('%s:%s' %(k, v))
#效率最高
print... |
d0aa978f163486bd0d37df334ba4671a0a05c69b | claudiu-orosanu/InformationRetrieval | /BooleanRetrievalSystem/listUtils.py | 801 | 3.609375 | 4 | def intersect_lists(l1, l2):
result = []
i, j, k = 0, 0, 0
while i < len(l1) and j < len(l2):
if l1[i] == l2[j]:
result.append(l1[i])
i += 1
j += 1
elif l1[i] < l2[j]:
i += 1
else:
j += 1
return result
def union_list... |
333495078ea131ebb460ae58012e9b8c82e50ef2 | ajocelynpatrick/routemaster | /routemaster/exit_conditions/operations.py | 1,424 | 3.625 | 4 | """Operation definitions for the condition stack machine."""
import enum
@enum.unique
class Operation(enum.Enum):
"""Classes of instructions for the exit condition machine."""
# Pop `value` from the stack, interpret it as a boolean, and push
# that to the stack.
TO_BOOL = 'to_bool'
# Pop boolea... |
68dd43fa41ac2b2313a476959b971405c26a48fd | DaniG2k/ProjectEuler | /48.py | 239 | 3.625 | 4 | #! /usr/bin/python
#The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.
#Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
series = [i**i for i in xrange(1,1001)]
result = str(sum(series))
print result[-10:] |
2552d45a81e2d6c4354359c6c7ce55504fed6d1b | DaniG2k/ProjectEuler | /3.py | 493 | 3.765625 | 4 | #! /usr/bin/env python
def isPrime(n):
if n < 1:
return False
elif n == 1:
return True
else:
l = [i for i in range(1, n+1) if n % i == 0]
if l[0] == 1 and l[1] == n:
return True
return False
def primeFactors(num):
l = []
i = 2
while i <= num:
if isPrime(i) and num % i == 0:
l.append(i)
num ... |
afaee1d1358dbafcbfe239a1924739d72f6628c7 | DaniG2k/ProjectEuler | /17.py | 1,828 | 3.890625 | 4 | #! /usr/bin/env python
#If all the numbers from 1 to 1000 (one thousand) inclusive
#were written out in words, how many letters would be used?
counters = {1: 'one', 2: 'two',
3: 'three', 4: 'four',
5: 'five', 6: 'six',
7: 'seven', 8: 'eight',
9: 'nine', 10: 'ten',
11: 'eleven', 12: 'twelve',
13: 'th... |
2c9c8b27ba5b5e8ce2e18370b6ca9a0a4554422a | DaniG2k/ProjectEuler | /34.py | 227 | 3.65625 | 4 | #! /usr/bin/python
def factorial(n):
f = 1
for i in xrange(1,n+1):
f *= i
return f
result = 0
for i in xrange(3,99999):
s = [factorial(int(char)) for char in str(i)]
if sum(s) == i:
result += i
print 'Result:',result |
73e14a5cf2d6fe18a8e9b7d7b2f3e89118fbd14d | borith23/test2 | /review.py | 1,128 | 3.859375 | 4 | #Creat class person
class Person():
def __init__(self, fname, lname):
self.firstName = fname
self.lastName = lname
def displayName(self):
print(self.firstName, self.lastName)
#Create class teacher and inheritance from super class Person
class Teacher(Person):
pass
x = Teacher("Pyth... |
4e7ac2f2df6e505ee50d4e6ae8d70fe76a7a7b2d | sepandhaghighi/Integer-Squaring | /main.py | 5,167 | 4.21875 | 4 | # -*- coding: utf-8 -*-
import math
import doctest
#By : Sepand Haghighi & Mohammad Abassi
def IntegerSquaring(Input_integer,Base=10):
'''
Integer Squaring Algorithm
Book : Cryptographic Engineering (Serdar S¨ uer Erdem, Tuˇ grul Yanık, and C ¸ etin Kaya Koc)
Chapter : 5
Page : 80
:param ... |
f8321c3e5b4ac3fe47366a647e71d9ef3c7b8781 | PanTomRastr/103_Pankratov1 | /ДЗ2(1).py | 375 | 4.03125 | 4 | def factorial1(n):
f=1
if (n < 0) or (type(n) != int):
return ValueError
for i in range(1,n+1):
f=i*f
return(f)
m=int(input())
print(factorial1(m))
def factorial2(n):
if n < 0 or type(n) != int:
return ValueError
if n==0:
return 1
else:
... |
d894050c4155d5f350d0f691a1754175311a868d | maverick-zhang/Algorithms-Leetcode | /leetcode_day13/Q129_path_sum2.py | 775 | 3.671875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def path(self, root):
if root is None:
return []
res = []
if root.left is None and root.right is None:
... |
428e66c9d836cf5fc74e764b8e353eaff3780fd6 | maverick-zhang/Algorithms-Leetcode | /leetcode_day14/Q78_subsets.py | 704 | 3.515625 | 4 | class Solution:
def __init__(self):
self.res = []
#寻找k个数字的组合,下标从index开始
def combination(self, nums, k, index, res):
if k == 0:
self.res.append(list(res))
return
if k > len(nums):
return
for i in range(index, len(nums)-k + 1):
... |
5569e2d684b2ad85ce4a0b01f81859adb2584066 | maverick-zhang/Algorithms-Leetcode | /leetcode_day11/Q234_is_palindrome.py | 941 | 3.640625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 时间复杂度O(n),空间复杂度O(1)
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
i, p = 0, head
while p:
i += 1
p = p.next
if i < 2:
... |
5084e8619415e18553febfc1115bcec11e0b09ba | maverick-zhang/Algorithms-Leetcode | /leetcode_day10/Q451_frenquency_sort.py | 496 | 3.640625 | 4 | from operator import itemgetter
class Solution:
def frequencySort(self, s: str) -> str:
record = {}
for ch in s:
if ch not in record:
record[ch] = 1
else:
record[ch] += 1
list2 = sorted(record.items(), key=itemgetter(1), reverse=True)
... |
80425e4281e232c1e7c0ac87cdb8ac07cb88d97d | maverick-zhang/Algorithms-Leetcode | /leetcode_day14/Q39_combination_sum.py | 1,222 | 3.71875 | 4 | # 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
#
# candidates 中的数字可以无限制重复被选取。
#
# 说明:
#
# 所有数字(包括 target)都是正整数。
# 解集不能包含重复的组合。
class Solution:
def __init__(self):
self.res = []
def __combination(self, candidates, index, target, res):
if target == 0:
... |
3aae270f26e6a22bf805081abfee3ed682002282 | ayecoo-103/Python_Code_Drills | /03_Inst_ATM_Application_Logic/Unsolved/atm.py | 656 | 4.15625 | 4 | """This is a basic ATM Application.
This is a command line application that mimics the actions of an ATM.
Example:
$ python app.py
"""
accounts = [
{
"pin": 123456,
"balance" : 1436.19},
{
"pin" : 246802,
"balance": 3571.87},
{
"pin": 135791,
"balance" : 543.79},
{
"pi... |
c1a5399d7019e8250c726ff2cebbb3e475d96d1d | 8451-CS-Club/connect-four | /ethan.py | 3,311 | 3.953125 | 4 | from gameboard import GameBoard
from time import sleep
import copy
# Make a move
def make_move(board, color):
best_move_x = 0
# This value being lower than -1 means the player will prefer an
# empty space over nothing, even if it means losing
best_val = -2
return(find_best_move(board, color))
# ... |
863d93b8294e16a752e202436d7569151fb70e5f | akshaykatre/PL_Stats | /stats.py | 3,234 | 3.625 | 4 | import pandas
from Shots import shots, percent_vs_shot_plot
from Fouls import fouls
from Plotting import totals_plot, detailbars
from Results import results
import matplotlib.pyplot as plt
x = pandas.read_csv("2013-2014.csv")
teams = x.HomeTeam.unique()
m_teams = {}
for index, t in enumerate(sorted(teams)):
m_... |
1e5af5b4c888f1dd7822e5dcb3fef0aa0bfd4a9a | milomacphail/pythonPractice | /rockPaperScissors.py | 905 | 3.984375 | 4 | from random import randint
options = ["rock", "paper", "scissors"]
computer = options[randint(0,2)]
player = False
while player == False:
player = input("Rock? Paper? Scissors?")
if player == computer:
print("Player and computer tie!")
elif player == "rock":
if computer == "paper":
... |
e776d9161f7b7143513e7d9e15d03e0d4f8b7f0a | tombjarne/blackjack-logic | /card.py | 428 | 3.5625 | 4 | class Card:
name = ""
symbol = ""
value = 0
ace = False
def __init__(self, name, symbol, value, ace):
self.name = name
self.symbol = symbol
self.value = value
self.ace = ace
def getsymbol(self):
return self.symbol
def getvalue(self):
return... |
4ae7881af202545a9948bd13e68a245101f6658e | ignis05/informatyka-python | /zadania/1.3.py | 571 | 3.828125 | 4 | import math
class Circle:
def __init__(self, radius):
self.radius = radius
def Pole(self):
return self.radius * self.radius * math.pi
def Obw(self):
return 2 * self.radius * math.pi
class Walec:
def __init__(self, radius, h):
self.circle = Circle(radius)
self... |
ba4c6bb212ce1374b4bf1779ae7b2fc415d6017b | ignis05/informatyka-python | /!KLASA_4/2.3.py | 949 | 4.3125 | 4 | # Napisz program, który sprawdzi położenie punktu względem odcinka.
# Użytkownik podaje współrzędne początkowe i końcowe odcinka oraz współrzędne punktu.
# Program należy zabezpieczyć przed podaniem współrzędnych określających długość odcinka równą 0.
import math
def distance(a,b):
return math.sqrt((a.x - b.x)**2 ... |
f7f402f502418d52fbdac796ce2d431ff6749a21 | ignis05/informatyka-python | /1.4/koloModule.txt | 219 | 3.53125 | 4 | import math
class Circle:
def __init__(self, radius):
self.radius = radius
def Pole(self):
return self.radius * self.radius * math.pi
def Obw(self):
return 2 * self.radius * math.pi |
35914a58c76913ed5cf6b8ecb597ad0e210a2b0a | AdamBHolt/CU-CSCI3104 | /Homework 2/src/RSAEncrypt.py | 1,724 | 3.546875 | 4 | import random
import time
import math
def RSAEncrypt():
start = time.time()
#Original message to encrypt
x = 3104
#Number of bits for random numbers
n = 16
#Set p and q as large random numbers
p = GetPrime(n)
q = GetPrime(n)
#N = p * q
N = p * q
#Set e to a r... |
22113c0fbcc71571cded352157ed61aeef8fcf40 | conradstorz/oldworldradio | /stats.py | 721 | 3.59375 | 4 | """
Take the input file and count the number of each entry type.
"""
from time import sleep
from datetime import datetime as time
import requests
from lxml import html
import json
from pprint import pprint as pprint
def Recover_file(filename):
with open(filename) as fp:
json_dict = json.load(fp)
return jso... |
ac51a04b6213e9a8b96e8b1b5d8e4310b56a945a | sarahdepalo/python-classes | /pokemon.py | 2,834 | 4.125 | 4 | #Below is the beginnings of a very basic pokemon game. Still needs a main menu built in. Someday I'd like to add the ability to maybe find new pokemon and battle random ones!
class Pokemon:
def __init__(self, name, health, attack, defense):
self.name = name
self.health = health
self.attack ... |
28c862aa8f344385f67ab5b74b1cf5becb8dda3e | wikizero/MyScripts | /leetCode/最长回文子串.py | 754 | 3.5625 | 4 | # coding:utf-8
s = "adam"
def longestCommonSubstr(str1, str2):
matrix = [[0] * (len(str1) + 1)] * (len(str2) + 1) # 构造零矩阵
ret = []
for i, val1 in enumerate(str2):
for j, val2 in enumerate(str1):
if val1 == val2:
matrix[i + 1][j + 1] = matrix[i][j] + 1 # 向前移一位防止 i-1 ... |
cef6f2c7add8e1f2d46376dedf45c6ec7218ee67 | wikizero/MyScripts | /Books/Python Cookbook/chapter3(数字日期和时间).py | 737 | 3.65625 | 4 | # coding:utf-8
import random
# (1)四舍五入函数作用在个位、十位、百位、、、
print round(14558, -1)
# (2)随机数生成
print random.randint(1, 11) # 随机整数
print random.random() # 随机浮点数 0-1
# (3) 随机选择
print random.choice(xrange(10)) # 给定序列随机取出一个元素
print random.sample(range(10), 3) # 给定序列随机取出n个
lst = list(xrange(10))
random.shuffle(lst) # 随机打乱... |
9e39d11e2c3cc9f81350ff02ad8c50c49786f020 | satyaki-mitra/Evalution_Exercise | /addgame.py | 913 | 3.53125 | 4 | import itertools
class AddGame(object):
def minimum(self, S):
if (len(S) <= 20):
n = len(S)
combinations = [list(comb) for i in range(1, n+1) for comb in itertools.combinations(S, i)]
list1 = []
for i in combinations:
comb_sum = 0
... |
9e6f77c1736e6f70f35a5ee1b7abaa797df9787b | michaelvargasloza/Python-Principios-basicos-python-desde-cero- | /ej4.py | 302 | 3.84375 | 4 | #Condicionales anidadas
nota1 = int(input("Ingrese primera nota: "))
nota2 = int(input("Ingrese segunda nota: "))
nota3 = int(input("Ingrese tercera nota: "))
prom = (nota1 + nota2 + nota3) / 3
if prom >= 7:
print("Promocionado.")
else:
if prom >= 4:
print("Regular.")
else:
print("Reprobado.") |
6ee76c871d3c7436160b06b41fb44cfc52fef312 | Tetrastorm/ISN-Labyrinthe | /Source/Matrix.py | 3,231 | 3.546875 | 4 | import pickle
class Matrix(object):
# Constructor
def __init__(self, lSizeMatrix, bIsAdditive = False):
self.lSize = lSizeMatrix
if bIsAdditive:
fValue = 1
else:
fValue = 0
self.iaMatrix = [[fValue], [fValue]]
self.mChange = [[0,0],[0.0]]
... |
01b202204801a52b6dd164997960f1da08ab4b35 | sriniavireddy/Text | /palindrome.py | 591 | 4.03125 | 4 | """
written by Srinivas Avireddy
Date : 11/26/2013
This program
Checks if the string entered by the user is a palindrome.
"""
def isPalindrome(input):
""" Checks if the string entered by the user is a palindrome """
reverse = input[::-1]
if input == reverse:
return True
else:
... |
620b0ea275f03ebb977b9d01187a8e2c7b75251e | csliuchang/LeetCodeAlgorithms | /datastructure/binary_search/binary_search_non-recursive.py | 456 | 3.953125 | 4 | # coding utf-8
def binary_search(alist, item):
"""
binary search using non-recursive
Optimal time complexity o(1)
the worst time comlexity o(log n)
"""
n = len(alist)
first = 0
last = n - 1
while first <= last:
mid = (first + last) // 2
if alist[mid] == item:
... |
0cbb64ffe1e7c5e826b0535386933cabde2c18df | JulesvanDongen/AI4.1 | /week1/UCS.py | 2,405 | 4 | 4 | import math
from collections import deque
from week1.Algorithm import Algorithm
class UCS(Algorithm):
NAME = "UCS"
unvisited = deque()
visited = {}
def nextIteration(self):
# 1. Take an unvisited node, find the fastest route on one of the surrounding positions and add this as a route
... |
fc3cbb645609e6b555f121e01f4c82bf17f2a627 | seung-lab/torchfields | /torchfields/utils.py | 5,868 | 3.84375 | 4 | from functools import wraps
#############################################
# Decorators for enforcing return value types
#############################################
def return_subclass_type(cls):
"""Class decorator for a subclass to encourage it to return its own
subclass type whenever its inherited functio... |
3d2f7fa54173fdf96a0b66e9c3fb36ed37451227 | schammer22/CMDA | /Inclass4_SarahHammer.py | 6,014 | 4.21875 | 4 | #Sarah Hammer
#CMDA 3654
#Inclass4 Part 2
"""What does the code below do? Run the code in iPython.
For each line of code, add an explanation
through a comment."""
#PART I
#prints "I will now count my chickens"
print "I will now count my chickens:"
#prints "Hens" then the integer value 25+30/6 (=30)
print "Hens", 2... |
13a3cd99ce41f0af3925b0471e11ffc1da4f98c1 | cpe202spring2019/lab1-Hsingh42 | /lab1_test_cases.py | 7,258 | 3.78125 | 4 | import unittest
from lab1 import *
# A few test cases. Add more!!!
class TestLab1(unittest.TestCase):
def test_max_list_iter(self):
"""when list is None"""
tlist = None
with self.assertRaises(ValueError): # used to check for exception
max_list_iter(tlist)
def test_max_... |
7c744188e7d75ac5ecf083c29b5449c43928e11d | pasanchamikara/ec-pythontraining-s03 | /numpy-tutorial/basics.py | 1,205 | 4.46875 | 4 | import numpy as np
# Basics
# a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) # Create a rank 1 array
# print(type(a)) # Prints "<class 'numpy.ndarray'>"
# print(a.shape) # Prints "(3,)"
# print(a)
# | 1 2 3 4 |
# | 5 6 7 8 |
# print(a[0], a[1], a[2]) # Prints "1 2 3"
# a[0] = 5 ... |
b2478988fed601e0c3b2bbcba70605d0940622b4 | seshu141/20-Projects | /19th Program.py | 715 | 4.125 | 4 | # 19th program Find second biggest number of a list
print(" enter the range of no. and stop")
def Range(list1):
largest = list1[0]
largest2 = None
for item in list1[1:]:
if item > largest:
largest2 = largest
largest = item
elif largest2 == None or largest2 < ... |
40f42faa9ff184914e9725e845f69113d73634a2 | stevenckwong/learnpython | /ex06.py | 590 | 4.3125 | 4 | #String formatting
hilarious = False
joke_evaluation = "Isn't that joke so funny?! {}"
print (joke_evaluation.format(hilarious))
a = "Adam"
b = "Bob"
c = "Cathryn"
friends = "There were once 3 friends named {}, {} and {}"
print (friends.format(a,b,c))
# positioning of the variables corresponds to the location of th... |
9b67263e7c33c532840bd950c7fc055053e70cd7 | stevenckwong/learnpython | /ex32.py | 676 | 4.53125 | 5 | #Loops and Lists
the_count = [1,2,3,4,5]
fruits = ['apples','oranges','pears','apricots']
change = [1,'pennies',2,'dimes',3,'quarters']
#the first kind of for loop that goes through a list
for number in the_count:
print(f"This is count {number}")
for fruit in fruits:
print(f"A fruit of type: {fruit}")
# not... |
50d248e79e004c46fa5b05bef425247ba7e46d69 | pranjalbhawsar11/pranjal | /stack.py | 764 | 4.0625 | 4 | class Stack:
def __init__(self):
self.head = []
def push(self, data):
self.head.append(data)
print(self.head)
def pop(self):
return self.head.pop()
a = Stack()
while 1:
print('1] push')
print('2] pop')
print('3] quit')
... |
66fa6d629d9ddfe80b4255e1ba72f95bff31ad4a | kwikl3arn/python-tutorial | /Python-Palindrome-Number.py | 290 | 4.25 | 4 | # Python Program for Palindrome Number
num = int(input("Enter a number: "))
temp = num
rev = 0
while num>0:
remain = num % 10
rev = (rev * 10) + remain
num = num // 10
if temp == rev:
print("Number is palindrome")
else:
print("Number is not palindrome")
|
4bcac0b0f4b04e6a728d1aa73f7d51a005d11c15 | tegsheeb/AdvancedPython_CS231 | /hw11.py | 714 | 3.890625 | 4 | '''
Write a universal wrapper program that expects its command line arguments to contain
the absolute path to any program, followed by its arguments. The wrapper should run
that program and report its exit value
'''
from sys import argv
from os.path import exists
from subprocess import call
# Checking whether there... |
4a369bff7a8797951f2ab3c7af2fef2b4ae75ba3 | CraGL/Hyperspectral-Inverse-Skinning | /PerVertex/util.py | 2,478 | 4.21875 | 4 | import re
import numpy as np
def veclen(vectors):
""" return L2 norm (vector length) along the last axis, for example to compute the length of an array of vectors """
return np.sqrt(np.sum(vectors**2, axis=-1))
def normalized(vectors):
""" normalize array of vectors along the last axis """
return vec... |
4ebaebb325d4e88a98be2373352e72c0cf6c2274 | rayturner677/polishing_skills | /17_April/stringPrac.py | 729 | 3.921875 | 4 | string1 = input("Enter:")
string2 = input("Enter:")
nw_string1 = []
def sortFunction():
if string1 > string2:
newString(string1, string2)
else:
newString2(string1, string2)
def newString(string1, string2):
for i in string1 or i == ".":
if i in string2:
nw_string1.app... |
2c735ce62f1c46c109ca2d2d6d3b485af0d04df3 | rayturner677/polishing_skills | /29_April/split_bill.py | 363 | 3.515625 | 4 | the_bill = [9.50, 11.00, 8.25, 8, 9]
allegy = 1
money_gave = 40
def split_bill(bill, index, partners_money_given):
first_total = 0
for i in bill:
first_total += i
total = first_total - bill[index]
value = total / 2
print(partners_money_given - value)
split_bill(the_bill, allegy, money_g... |
68413c901b9145d79bc12bf1c92e18f10111820b | mahdi-asadzadeh/learning-python-design-patterns | /behavioral/command_example_2.py | 773 | 3.953125 | 4 | from abc import ABC, abstractmethod
# Command
class Command(ABC):
def __init__(self, receiver):
self.receiver = receiver
@abstractmethod
def execute(self):
pass
# Concrete Command
class ConcreteCommand(Command):
def __init__(self, receiver):
self.receiver = receive... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.