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 |
|---|---|---|---|---|---|---|
4318562c52a20e74f323604d6cbcc70fdb2b9a71 | kuriakosethomas/COP_4814 | /lab1.py | 579 | 3.71875 | 4 | #1
nl=[]
for x in range(2000, 3201):
if ( x % 7 == 0 ) and ( x % 5 == 0 ):
nl.append(str(x))
print (','.join(nl))
#2
def factorial(n):
if n == 0:
return 1
else:
return n * factorial( n - 1 )
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))
#3
n = int(... |
95aabab34c65ef3e09186acda3b1baae7f437822 | arghhjayy/LearningMachineLearning | /5_regression_linearregression.py | 878 | 3.65625 | 4 | from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')
xs = np.array([1, 2, 3, 4, 5, 6], dtype=np.float64)
ys = np.array([5, 4, 6, 5, 6, 7], dtype=np.float64)
# m # # b #
def best_fit_slope_and_intercept(xs, ys):
... |
ffbff41905680bde74a7d42f06d0aa90f55fca25 | yingwei1025/credit-card-checksum-validate | /credit.py | 1,333 | 4.125 | 4 | def main():
card = card_input()
check = checksum(card)
validate(card, check)
def card_input():
while True:
card_number = input("Card Number: ")
if card_number.isnumeric():
break
return card_number
def checksum(card_number):
even_sum = 0
odd_sum = 0
card_n... |
044225e9a588f859e59985b9ded5ca34b571a167 | Ruchi27280/Test-project | /Ruchi/Ex1.py | 159 | 3.640625 | 4 | x , y = input("enter x and y:").split()
x = int(x)
y = int(y)
#y = int(input("enter second number:"))
z = x * y
if z < 1000:
print(z)
else:
print(x+y)
|
cf969818539409955b0e300fca28d40d3dad6307 | jaimewitt/CodingDojoSept2017 | /change.py | 999 | 3.703125 | 4 |
def change(num):
s=0
h=0
q=0
d=0
n=0
p=0
while num > 0:
if num >= 100:
s=s+1
num=num-100
print(num)
print(s)
elif num >= 50:
h=h+1
num=num-50
print(num)
print(h)... |
66f0ccab7057084061766ca23e21d790e829922b | irmowan/LeetCode | /Python/Binary-Tree-Maximum-Path-Sum.py | 1,307 | 4.15625 | 4 | # Time: O(n)
# Space: O(n)
# Given a binary tree, find the maximum path sum.
#
# For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.
#
# For example:
# Given the below binary tree... |
6e865390ebf63d1f57f82593679630be5c922774 | irmowan/LeetCode | /Python/Sum-Root-to-Leaf-Numbers.py | 1,514 | 4.09375 | 4 | # Time: O(n)
# Space: O(n)
# Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
#
# An example is the root-to-leaf path 1->2->3 which represents the number 123.
#
# Find the total sum of all root-to-leaf numbers.
#
# For example,
#
# 1
# / \
# 2 3
# The roo... |
9fe261707283f616194ebe30757a6381d500d534 | irmowan/LeetCode | /Python/Palindrome-Number.py | 1,065 | 4.125 | 4 | # Time: O(n)
# Space: O(1)
#
# Determine whether an integer is a palindrome. Do this without extra space.
#
# click to show spoilers.
#
# Some hints:
# Could negative integers be palindromes? (ie, -1)
#
# If you are thinking of converting the integer to string, note the restriction of using extra space.
#
# You could a... |
63df9744b9920bcfee64328314ec48b600e305ad | Chatwaroon/Portfolio | /workshop/อัตราการแลกเปลี่ยนและแปลงสกลุเงิน/ExchangeRateAPI.py | 384 | 3.546875 | 4 | import requests
import json
response=requests.get('https://api.exchangeratesapi.io/latest')
data=response.text
parsed=json.loads(data)
#print(json.dumps(parsed,indent=4))
date=parsed["date"]
usd_rate=parsed["rates"]["USD"]# rate dollar
thb_rate=parsed["rates"]["THB"]
rates=parsed["rates"]
for currency,rat... |
e802d2edbe104e05a422cee180712283df00e8e6 | LinuxUser255/Python_Penetration_Testing | /Python_Review/functions03.py | 410 | 4.09375 | 4 | #!/usr/bin/env python3
#Passing an argument to a function.
def get_formatted_car(make, model):
full = f"{make} {model}"
return full.title()
#While loop
while True:
print ("\nWhat is the make and model of your car? ")
f_make = input("Make: ")
s_model = input("Model: ")
formatted_car = get_fo... |
5f8c9db073643da16d88ef03512b4ca6e97d28ca | LinuxUser255/Python_Penetration_Testing | /Python_Review/dmv.py | 308 | 4.125 | 4 | #!/usr/bin/env python3
#If-else using user defined input:
print("""Legal driving age.
""")
age = int(input("What is your age? "))
if age < 16:
print("No.")
else:
if age in range(16, 67):
print("Yes, you are eligible.")
if age > 66:
print("Yes, but with special requirements.")
|
3a69696fd862f8e6004cd71e10aaa661df0871d4 | LinuxUser255/Python_Penetration_Testing | /Python_Review/boolean.py | 458 | 3.890625 | 4 | #!/usr/bin/env python3
#Truth Value Testing
# constants defined to be false: None and False.
# zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
# empty sequences and collections: '', (), [], {}, set(), range(0)
if 0:
print("True")
else:
print("False")
OS = input("What Operating System are yo... |
be99b684be47730c902fea006c765bf27f938aa2 | LinuxUser255/Python_Penetration_Testing | /Python_Networking/client.py | 704 | 3.609375 | 4 | #!/usr/bin/env python3
#Client
import socket
HEADER = 64
PORT = 4444
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "Connection closed"
#the client's socket object:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
def ... |
babe038bf2108c6a57c79a45082f06625e7f67fd | Royzhang88/python-http-interface-test | /other/testregex.py | 156 | 3.59375 | 4 | import re
string = "今天的天气真好明天是2017年9月6日吃什么呢?"
result = re.search(r"\d+年\d+月\d+日",string)
print(result.group(0)) |
2133c5be344436c92358cc66b1eedf0207b56989 | eldanielh31/FiguritasTurtle | /Figuras/Cuadrado.py | 532 | 3.515625 | 4 | from turtle import *
class Cuadrado:
def __init__(self, lado):
self.lado = lado
def getLado(self):
return self.lado
def setLado(self, nuevoLado):
self.lado = nuevoLado
def construir(self, tortuga):
tortuga.pencolor("purple")
tortuga.forward(self.lado)
... |
f391f8be1c18a74eac487f296ce7b8436ef957f6 | baiYigao/sudoku_solver | /solve.py | 3,073 | 4.28125 | 4 | """Backtracking approach to solve Sudoku puzzle
input: a string of numbers representing the 9x9 board from top left to
bottom right (81 number of characters). 0 represents empty square.
output: a visual board that is correctly filled according to Sudoku puzzle rules.
"""
def cross_product(A, B):
"""Return a list t... |
27d9ab2b5a11c523ded85d12138ea1b58705326f | CodeNovice2017/Python-Studying | /链表,单双链表,循环链表.py | 2,512 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author:CodeMonster
@file: 链表,单双链表,循环链表.py
@time: 2017/10/13 10:26
"""
class LNode:
def __init__(self,elem,next_=None):
self.elem = elem
self.next = next_
# list1 = LNode(1)
# q = list1
# for i in range(2,11):
# q.next = LNode(i)
# q = q.next... |
203bdc3a2c1c43e190f583e8197d513fd023b3b8 | JustCallMeRob/Q-learning-tictactoe | /environment.py | 4,312 | 3.984375 | 4 | import numpy as np
import random
class Environment:
# The game of tic tac toe has a state space of size 5478 with 9 possible actions for any state
# most states will have less than 9 possible actions, however if the agent decides based on the Q table to make a
# move on a tile that already has a symbol on... |
da9d54ad2a925e1da6b8d7b380c9e72be57a4196 | hubbm-bbm101/lab5-exercise-solution-b2200765015 | /exercise2.py | 221 | 3.921875 | 4 | def email_controller(email):
if "." in email and "@" in email:
return "It is an email."
else:
return "It is not an email."
email1=input("Enter your email: ")
print(email_controller(email1)) |
f0176b38093db6c055a48c9a16a19dc94f9169b0 | AeranicusCascadia/personnel-list-app | /phone_list_sorter.py | 3,544 | 3.828125 | 4 | """
This Python application take CPM phone list as text document and strips all but first and last names of each employee, stores
then in a list, alphabetizes according to last name, then creates new text document. Requires minimal manual formatting
of text file input.
Future dev goals:
Create save file of list ... |
4e22dd8b5dc2b0824b6c1592a1d55a218d7f5138 | JunhuiJiang/MyCode | /python/深度学习/逻辑回归/deeplearning/classifiers/LogisticRegres.py | 3,227 | 3.65625 | 4 | import numpy as np
import math
import matplotlib.pyplot as plt
class LogisticRegres(object):
def __init__(self):
pass
def sigmoid(self,inX):
return 1.0 / (1+np.exp(-inX))
def gradDescent(self,x_train,y_train):
m,n = x_train.shape
alpha = 0.001
maxEpoch = 5000
... |
e4112fd625b532aed2c33ef6ce6686e21645877e | azumkehr/hack_the_stocks-jkjk | /datareader/panda_id.py | 854 | 3.5 | 4 | # Author: Andrew Zumkehr
# Purpose: Demonstrate pandas-datareader
import numpy as np
import matplotlib.pyplot as plt
from pandas_datareader import data, wb, DataReader
import backports.functools_lru_cache
from datetime import datetime
start = datetime(2018, 1, 1)
stop = datetime.now()
ibm = DataReader('IBM', 'yahoo',... |
fa430b018f2a507dbe5f8b233857621541eebb14 | Andy-Pham-72/Python-Challenge-Questions | /Python-Tips/Naming_Convention/property_method.py | 557 | 3.9375 | 4 | # @property
class Employee:
def __init__(self, name, new_salary):
self._salary = new_salary
@property
def salary(self):
return self._salary
@salary.setter
def salary(self, new_salary):
if new_salary < 0:
raise ValueError("Invalid salary")
self._salary =... |
43800bdeb2026c76700c9c5a269410abb96ccf69 | Andy-Pham-72/Python-Challenge-Questions | /Python-Tips/Inheritance-Class-Hirarchies/Inheritance.py | 502 | 3.8125 | 4 | class Number():
def __init__(self):
self.num = 0
def increase(self):
self.num += 1
def decrease(self):
self.num -= 1
class NewNumber(Number):
number_new = 11 # public variable
_new = 12 # can be accessed by different classes
__new = 11 # can be only accessed within NewNumber class
def __init__(self):
su... |
0094932e85c5989a49fde54b0e5d8e9a320f0427 | ericamendez/Learning-Python | /MIT_OCW_6.0001/pset0.py | 171 | 4.03125 | 4 | import math
x = int(input("Enter a number for x: "))
y = int(input("Enter a number for y: "))
print("x^y = " + str(x**y))
print("log (base2) of x is " + str(math.log(x))) |
ac7762e1891b6057460227c27ac0020f56d1f79b | ivila238/hangman | /hangmanv5-final.py | 1,654 | 3.984375 | 4 | import random
from sys import exit
print('H A N G M A N')
def menu():
print('Type "play" to play the game, "exit" to quit:')
menu = input(">")
valid_response = True
while valid_response:
if menu == 'play':
game()
elif menu == 'exit':
exit()
else:
... |
62824af0472d72e798711208d0d2d00676a3a8f6 | Man1exter/forex.pyv2 | /turtle_win.py | 366 | 3.9375 | 4 | import turtle
import random
# init + settings
animal = turtle.Turtle()
animal.shape("turtle")
animal.speed(20)
animal.pensize(5)
# sett with turtle
turtle.bgcolor("black")
# about drawing set
for it in range(50,500):
animal.color(random.choice(["blue","red","yellow","brown","purple","white"]))
animal.forward(it ... |
85faa83b7a3e826fea4d5872d270dc6e3bade044 | Shuhala/leet-code | /binary_search/search_in_sorted_rotated_array.py | 1,551 | 3.609375 | 4 | from typing import List
class Solution:
def search(self, nums: List[int], target: int) -> int:
if len(nums) < 1:
return -1
if len(nums) < 3:
return nums.index(target) if target in nums else -1
lo, hi, mid = 0, len(nums) - 1, 0
while lo < hi - 1:
... |
da7ad9bd4bb35add92fa50054b2696b2e1bd93a9 | Shuhala/leet-code | /arrays/majority_element.py | 562 | 3.96875 | 4 | from collections import Counter
from typing import List
class Solution:
"""
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
"""
... |
d843fd92b0bd653174429e0d85aa85623f8c0b1b | Shuhala/leet-code | /missing_number.py | 419 | 3.9375 | 4 | def search(ar):
a = 0
b = len(ar)
mid = 0
while b > a + 1:
mid = (a + b) // 2
if ar[mid] == mid + 1:
a = mid
else:
b = mid
# if (ar[a] - a) != (ar[mid] - mid):
# b = mid
# elif (ar[b] - b) != (ar[mid] - mid):
# a = m... |
fac8764c58a26db26343c114227952cb7231b09a | dian-ai/Data_preprocessing | /data_preprocessing_template_Diana.py | 3,439 | 4.09375 | 4 | # Data Preprocessing
# Importing the Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('Data.csv')
#Creat Matrix of Features (array of features)
#iloc is a function of pandas, that will take the indexes
#of columns that we want to extract from the dataset
x = dat... |
a226f14ca2c91af24d79d2d166db5d7ea2eda890 | hustlrr/leetcode | /accepted/Integer Replacement.py | 490 | 3.5625 | 4 | # coding=utf-8
class Solution(object):
def integerReplacement(self, n):
"""
:type n: int
:rtype: int
"""
def myDivide(num, res):
if num == 0:
return 0
elif num == 1:
return res
elif num % 2 == 0:
... |
b3d0bb5091e7394cf9b1dae6d403f69166f50d0e | hustlrr/leetcode | /accepted/Number of Segments in a String.py | 487 | 3.5 | 4 | # coding=utf-8
class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
# 不能直接用split,这样空间复杂度太 高
num_space = 0
s = s.strip()
s_len = len(s)
i = 0
while i < s_len:
if s[i] == ' ' and ((i + 1 < s_len... |
f64b04cd892495a1752caacb8f175c77dea57dd0 | hustlrr/leetcode | /accepted/Sum Root to Leaf Numbers.py | 929 | 3.765625 | 4 | # coding=utf-8
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def getNums(self, root, path):
if root is None:
yield 0
if root:
p... |
92b19e1d1681280e9c95162f4ad72bb2bf3833bc | hustlrr/leetcode | /accepted/Find Peak Element.py | 1,097 | 3.515625 | 4 | # coding=utf-8
class Solution(object):
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 如果大于两边返回当前index就可以 了,如果左边的节点比mid大,那 么我们可以继续在左半区间查找, 这里面一定存在一个peak,为什么 这么说呢?假设此时的区间范围为 [0, mid - 1], 因为num[mid - 1]一定大于num[mid]了,如果num[ mid - 2] <= num[mid - 1],... |
e5f8f4dec8953d5fa8ced78b37101ba9c368308b | hustlrr/leetcode | /accepted/Rotate Array.py | 318 | 3.71875 | 4 | # coding=utf-8
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.
"""
numlen=len(nums)
nums[0:k],nums[k:numlen]=nums[numlen -k:numlen],nums[0:numlen-k]
|
64dbf4bd26619d757f898a78b2a8b5cd8e620cce | hustlrr/leetcode | /accepted/Intersection of Two Linked Lists.py | 761 | 3.625 | 4 | # coding=utf-8
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
... |
e3aebae335ad597ee0646eb82b0cd575ef9d59ff | hustlrr/leetcode | /accepted/Random Pick Index.py | 571 | 3.734375 | 4 | # coding=utf-8
import random
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
:type numsSize: int
"""
self.nums = nums
def pick(self, target):
"""
:type target: int
:rtype: int
"""
candidates = []
... |
6af54a1b9e7e0d0e5c90ae8fdd18ec1b5231abeb | hustlrr/leetcode | /accepted/Length of Last Word.py | 336 | 3.578125 | 4 | # coding=utf-8
import re
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
regex='\S*\Z'
pattern=re.compile(regex)
match=pattern.search(s.strip())
if match:
return len(match.group())
else:
... |
3d42cea7cea31c00201154832f8c240fd000e254 | kengo-matsumura/mlprojects | /classification.py | 5,468 | 4.21875 | 4 | # Machine Learning - Classification
# Code examples are inspired from the DataCamp course 'Supervised Learning with Scikit-Learn'.
# Working with a variety of datasets that are available in the sklearn.datasets library.
# Load required packages
# numpy, or Numerical Python, is a very useful package for data science, ... |
35df2944b0782ad6d3a02a187b0c0de64f90e9a7 | jgeskens/python-typing-test | /main.py | 1,137 | 3.96875 | 4 | from math import sin, cos, pi
from typing import Union
# Type declarations
class Move(object):
def __init__(self, dx: float, dy: float) -> None:
self.dx = dx
self.dy = dy
class Rotate(object):
def __init__(self, degrees: float) -> None:
self.degrees = degrees
class NoOp(object):
... |
af7af7c62c76722c2dad6091dda45f43ad3c56df | RohitKochhar/advent-of-code | /2020/day1/part1_slim.py | 961 | 3.578125 | 4 | # For test purposes
import time
start_time = time.time()
i_DesiredValue = 2020
def ArrayToHash(a_Sorted):
# Find how many 100 intervals we need based on our desired number, and add 1
i_Intervals = (i_DesiredValue // 100) + 1
print(i_Intervals)
a_Matrix = []
# Create a hash table with an index... |
5fc7d0c4ffbe75bc8054d900ee79388954f3a3f9 | 7nic7/DataStructureAndAlgorithm | /Algorithm/SortAlgorithm.py | 1,873 | 3.765625 | 4 | def bubble(list_data):
"""
冒泡排序
时间复杂度 : O(n^2)
稳定性 : 稳定
"""
n = len(list_data)
for i in range(n-1, 0, -1):
count = 0
for j in range(i):
if list_data[j] > list_data[j+1]:
list_data[j], list_data[j+1] = list_data[j+1], list_data[j]
... |
e67f2943c30c05dd458f4f4f6aa12fdff032cd23 | pawkoc/KKzad2_A | /SymbolTable.py | 911 | 3.59375 | 4 | #!/usr/bin/python
class FunctionTable(object):
def __init__(self):
self.dictionary = {}
def put(self, name, retval, args):
self.dictionary[name] = [retval, args]
def get(self, name):
if name in self.dictionary.keys():
return self.dictionary[name]
else:
... |
71ce7363f8dbb9c9b68045eebf57072935a1f6ea | jw0711qt/lab2 | /books.py | 1,139 | 3.640625 | 4 |
class Author: #creatinmg Author class
def __init__(self, name):
self.name = name
self.books = []
def publish(self, title): #handle duplication of books
title=title.lower()
if title in self.books:
print ( f'sorry, this book is duplicated: {title}')
else:
... |
d56e0c2313410a3e7ac3397f88ec15a29cdbf311 | mihirbhaskar/save-the-pandas-intpython | /CleaningPittCity.py | 9,925 | 3.609375 | 4 | """
File: CleaningPittCity.py
Desc: Take the CSV of City of Pittsburgh facilities CSV/Excel file
from online. Clean this data, getting rid of sites that do not provide
community service we are interested in.
Generate a Pandas DataFrame that is exported to a final CSV, to be combined
with other CSV datas into the ma... |
6361f4914c5a1570c9113a55222c139a9844efb2 | mihirbhaskar/save-the-pandas-intpython | /filterNearby.py | 973 | 4.125 | 4 | """
File: filterNearby
Description: Function to filter the dataframe with matches within a certain distance
Next steps:
- This function can be generalised, but for now assuming data is in a DF with lat/long columns named
'latitude' and 'longitude'
"""
import pandas as pd
from geopy.distance import distance
d... |
2096aed0b726883d89aae8c3d886ae5ef3b11518 | simplex06/HackerRankSolutions | /Lists.py | 1,683 | 4.3125 | 4 | # HackerRank - "Lists" Solution
#Consider a list (list = []). You can perform the following commands:
#
#insert i e: Insert integer at position .
#print: Print the list.
#remove e: Delete the first occurrence of integer .
#append e: Insert integer at the end of the list.
#sort: Sort the list.
#pop: Pop the last elem... |
af9323dc2a6e3f5327a5c15bd6b7739a454da8d0 | Sewez/projecteulersol | /prob5.py | 819 | 3.75 | 4 | # 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
# Function to return true or false if evenly divisible
def is_evenly_div(value, div_by):
if value % div_b... |
492689343e28be7cdbb2d807514881925534a010 | SynTentional/CS-1.2 | /Coursework/Frequency-Counting/Frequency-Counter-Starter-Code/HashTable.py | 2,156 | 4.3125 | 4 | from LinkedList import LinkedList
class HashTable:
def __init__(self, size):
self.size = size
self.arr = self.create_arr(size)
# 1️⃣ TODO: Complete the create_arr method.
# Each element of the hash table (arr) is a linked list.
# This method creates an array (list) of a given size and populates eac... |
1e6f8fd5b0afd37c1e749ea5ea4b8ae1fdba3b0d | PatelProjects/ProjectEulerSolutions | /14.py | 387 | 3.6875 | 4 | cache = {1: 1}
def collatz_count(n):
if n not in cache:
if n % 2 == 0:
cache[n] = 1 + collatz_count(n / 2)
else:
cache[n] = 1 + collatz_count(3 * n + 1)
return cache[n]
highest = 0
number = 0
for i in range(1, 1000001):
x = collatz_count(i)
if x > highest:
... |
36594437c6f543976f5991a0eded56cb0501be54 | PatelProjects/ProjectEulerSolutions | /27.py | 716 | 3.515625 | 4 | def isPrime(n):
if n == 2:
return True
if n == 3:
return True
if n % 2 == 0:
return False
if n % 3 == 0:
return False
i = 5
w = 2
while i *i <= n:
if n % i == 0:
return False
i += w
... |
9310178c93c04c16483eb492e57311d24afafb6e | PatelProjects/ProjectEulerSolutions | /57.py | 505 | 3.546875 | 4 | from fractions import Fraction
import sys
count = 0
sys.setrecursionlimit(1012)
def rootTwo( iterations,count, answer = 3/2 ):
if iterations == 1:
return count
else:
answer = Fraction(str(1 + 1/(answer+1)))
if len(str(answer.numerator)) > len... |
48c28ffc2ba858970b178f9cc7ee1783a5ba7eb4 | PatelProjects/ProjectEulerSolutions | /10.py | 866 | 4.0625 | 4 |
def isPrime(n):
if n == 2:
return True
if n == 3:
return True
if n % 2 == 0:
return False
if n % 3 == 0:
return False
i = 5
w = 2
while i *i <= n:
if n%i == 0:
return False
i += w
w = 6 - w
... |
d87a99eb6b8f85277458716387d296c9174ece0e | PatelProjects/ProjectEulerSolutions | /25.py | 189 | 3.65625 | 4 | fibonacci = [1, 1]
i = 2
while True:
number = fibonacci[i-1] + fibonacci[i-2]
if len(str(number)) == 1000:
print(i+1)
break
fibonacci.append(number)
i+= 1 |
e77ffcd6831cf9111c81e7ce925e54bc63c0b957 | ChaithraBaliga/learnings | /chaithrapatterns/pattern3.py | 129 | 4.03125 | 4 | n=5
num=1
for row in range(1,n+1):
for col in range (1,row+1):
print(num,end=" ")
num=num+1
print() |
0e8ffd071d752a4b67c8dea277ca55580e55c008 | Luffyzm3D2Y/BUAA-DL2021 | /Bigscity-TrafficDL/trafficdl/utils/normalization.py | 1,852 | 3.53125 | 4 | class Scaler:
"""
归一化接口
"""
def transform(self, data):
raise NotImplementedError("Transform not implemented")
def inverse_transform(self, data):
raise NotImplementedError("Inverse_transform not implemented")
class NoneScaler(Scaler):
"""
不归一化
"""
def transform(se... |
252c9f2cd0dc2c829fb42afd58c8e1e7ee4dc3fe | UWPCE-Py210-SelfPaced-2021/lesson-02-fibonacci-series-exercise-CodyYarger | /series.py | 3,475 | 4.28125 | 4 | # 12/09/2020
# Dev: Cody Yarger
# Exercise 2.4: Fibonacci Series
#===============================================================================
def fibonacci(n):
"""The fibonacci function is passed the argument n and returns the nth value
of the Fibonacci series"""
# Base case for n = 0 and 1.
if n <... |
5d22fa670fac720aa7f5a586190a682c670e6899 | GGRice/InteractiveProgramming | /pong.py | 14,470 | 4.15625 | 4 | """
Created on Mon February 27, 2017
author: Gretchen Rice and Nina Tchirkova
Music: http://www.bensound.com
This program creates a version of pong. It is a two player game where players
control paddles and try to hit a ball past the other player's paddle to score
points.
"""
import pygame
import time
import math
i... |
88f03e0e9289421592eaad5d686b1fe0d359f14e | VRS-3999/Python-Codes | /A Puzzle Game.py | 1,275 | 3.59375 | 4 | #interchange=[(0, 1), (1, 2), (3, 4), (4, 5), (6, 7), (7, 8), (0, 3), (1, 4), (2, 5), (3, 6), (4, 7), (5, 8)]
#prime=(2,3,5,7.11,13,17,19)
interchange = [(0, 1), (1, 2), (3, 4), (4, 5), (6, 7), (7, 8), (0, 3), (1, 4),
(2, 5), (3, 6), (4, 7), (5, 8)]
prime = (2, 3, 5, 7, 11, 13, 17, 19)
def swapping(value,k):... |
98f629813d69e7a5fdcb914b61ba4c14380efbad | hujuu/py-xml | /soup2.py | 389 | 3.625 | 4 | from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError
from bs4 import BeautifulSoup
try:
html = urlopen("http://www.pythonscrapingnoexit.com")
except HTTPError as e:
print(e)
# return null, break,あるいはプランBを実行
except URLError as e:
print("The server coou... |
f739cca8ab8f4d3788c4e4461da5cb45e483d914 | sxlstevengit/My_Scripts | /python/get_tupian.py | 942 | 3.578125 | 4 | # 第一部分: 获取网页源代码
#导入模块
import requests
#定义变量
url = "http://www.lanrentuku.com/"
# 设置请求headers,让python模拟浏览去获取数据
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"}
#发起请求,获取数据
result = requests.get(url,headers=headers)
#设置数据的字符编码... |
1b3e19638259007168b1674ef453a4d81b815967 | garethgeorge/Gareth-John-MyPy | /test/euler_problems/problem10.py | 1,103 | 3.6875 | 4 | """
Project Euler #10
https://projecteuler.net/problem=10
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
"""
def sum(gen):
acum = 0
for val in gen:
acum += val
return acum
"""
Project Euler #10
https://projecteuler.net/problem=10
The sum of the p... |
1a9ba4cfe848b8529b0aa9eaddd09882f9bcd5bf | khankatan/CP3-Chetsarit-Mesathanon | /assignments/Exercise5_1_Chetsarit_M.py | 269 | 4.15625 | 4 | print("--------- CALCULATOR ---------- ")
x = int(input("num1 : "))
y = int(input("num2 : "))
print("=============================== ")
print(x,"+",y,"=",x+y)
print(x,"-",y,"=",x-y)
print(x,"x",y,"=",x*y)
print(x,"/",y,"=",x/y)
print("=============================== ") |
704943ecfcd96d0a7ee51bb70750a23fbfa61f6a | khankatan/CP3-Chetsarit-Mesathanon | /assignments/Lecture53_Chetsarit_M.py | 334 | 3.5625 | 4 | def vatCal(price,taxrate):
amount = price*(1+(taxrate/100))
return amount
print("========== VAT CALCULATION ==========")
priceInput = int(input("Product price (THB) : "))
taxrateInput = int(input("Tex rate (%) : "))
print("Price includes tax :", vatCal(priceInput,taxrateInput))
print("========== ==============... |
aa29cde7070d9c68e6572d9a362fed336488f4a1 | SeilaAM/BasicProgramPython | /ModulePractice/CustomerSystemMoveTest/Modules/Asset/BasicData.py | 1,767 | 4.21875 | 4 | # ----------------- 客戶的基本資料 ----------------- #
class BasicData:
def __init__(self, name, age, gender, phone, email):
self.__name = name
self.__age = age
self.__gender = gender
self.__phone = phone
self.__email = email
def get_name(self):
return self.__name
... |
e0f4f99d1b35788f7312e9138e54321abbc9b424 | cemalaytekin/cmpe230-File-Utility-Program | /assignment2.py | 13,971 | 3.53125 | 4 | #!/usr/bin/python
## ============================================================================
# Name : Filelist, CMPE230
# Author : Berke Esmer & Cemal Aytekin
# Description : In this project, we implement a simple application called
# filelist. It takes several parameters and searches for
# ... |
0ebd4d2700e06882760d80972b2c778306677e41 | chenshihao123456/UdacityStudy | /Task-1/cn-python-foundation/investigate texts and calls/ZH/Task0.py | 1,138 | 3.875 | 4 | """
下面的文件将会从csv文件中读取读取短信与电话记录,
你将在以后的课程中了解更多有关读取文件的知识。
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
任务0:
短信记录的第一条记录是什么?通话记录最后一条记录是什么?
输出信息:
"First record of texts, <in... |
7f7c20e3c655b59fb28d90a5b7fec803d3b65170 | MrSmilez2/z25 | /lesson3/4.py | 272 | 4.125 | 4 | items = []
max_element = None
while True:
number = input('> ')
if not number:
break
number = float(number)
items.append(number)
if not max_element or number >= max_element:
max_element = number
print(items)
print('MAX', max_element)
|
62e9a5ad75d298d91208b9ac1cc99069a48d5d06 | gring2/study_hard | /codility/lesson4/solution.py | 450 | 3.515625 | 4 |
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(N, A):
# write your code in Python 3.6
f = list(filter( lambda x: x <= N+1, A))
result = [0] * N
min_value = min(f)
if min_value > N+1:
return result
for i, x in enumerate(f):
... |
48d1ccbde1b9e68f55d68ffbe86fd830caf87dee | MandyZ0/CSC324 | /Lecture_Example/week1/tail.py | 295 | 3.640625 | 4 | def count(n):
if n == 0:
return 0
else:
return 1 + count(n-1)
def count_tail(n, acc):
if n == 0:
return acc
else:
return count_tail(n - 1, acc + 1)
def count_iterative(n, acc):
while n != 0:
n, acc = n - 1, acc + 1
return acc
|
793910b9568cdf9ace8c1d406f4a389a4f0ad855 | satyaprakash-7101/search-match- | /para_sen.py | 1,196 | 3.71875 | 4 | def biagram(l,m):
j = []
for i in range(len(l)):
if l[i] == " ":
j.append(i)
print(j)
for i in range(len(j)):
if i == 0:
m.append(l[0:j[1]])
elif i > 0 and i != (len(j)-1):
m.append( l[j[i-1]+1:j[i+1]])
elif i == (len(j)-1):
... |
dd86e4303e2e0ce7c4c423a7c29469ad3449dd7c | cbates8/ACS-Online | /Predator vs Prey/Version 3/superturtle_prey.py | 1,436 | 4.03125 | 4 | from turtle import *
from math import sqrt
from random import randint
#######################################################################
# The prey team copies and pastes their superturtle code
# below, and renames their class Superturtle_prey.
#
# Below are empty functions necessary for running the main.py progr... |
47cad7e066e581f195051e1eaeaf79d2354337e5 | cbates8/ACS-Online | /Binary Tree Maze Walking/Maze Walking/tree_maze.py | 7,851 | 4.15625 | 4 | #inspired by Jamis Buck at http://weblog.jamisbuck.org/2011/2/1/maze-generation-binary-tree-algorithm
import turtle
from maze_structure import *
from random import choice
class Tree_Maze:
""" Tree Maze class for representing a checkers-board-like maze made up of "erasable" lines. """
def __init__(self, columns, ... |
25a5fc674863d706b00d82fb6f66a3fecf61461b | cbates8/ACS-Online | /Recursive Maze Walking/Maze Definition/main.py | 9,132 | 4.34375 | 4 | # filename: Recursion - Maze Definition - Project - WIP
# inspired by Buck
import maze, walker, goal
from random import randint, choice
from math import floor
#############################
#
# Provided Utility Functions
#
#############################
def block_line(maze, start_column, start_row, length, direction,... |
a2ab21a48d07c3fe753681babeb8cfeea023038c | floryken/Ch.05_Looping | /5.2_Roshambo.py | 1,632 | 4.8125 | 5 | '''
ROSHAMBO PROGRAM
----------------
Create a program that randomly prints 1, 2, or 3.
Expand the program so it randomly prints rock, paper, or scissors using if statements. Don't select from a list.
Add to the program so it first asks the user their choice as well as if they want to quit.
(It will be easier if you h... |
2df61c73db6ecbce8b0f1e7281593ce4a8117aa6 | omarolivarez/learning-sessions | /learning-python/python_pandas_and_writing_functions.py | 6,156 | 4.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 24 21:05:13 2021
@author: OmarOlivarez
"""
"""
WHAT ARE VARIABLES?
-------------------
if x1 = 1
x2 = 2
x3 = 3
and
y1 = 2
y2 = 4
y3 = 6
Can you describe the relationship between x and y?
WHAT ARE FUNCTIONS?
----------------... |
8ddf30837ee0cc5f229b578e1a05b8e7aa355e74 | atehortua1907/Platzi | /1-MinTic_IA/2-Python/43_44-AgendaContactos/Contacts.py | 3,247 | 3.859375 | 4 | class Contact:
def __init__(self, name, phone, email):
self._name = name
self._phone = phone
self._mail = email
class ContactBook:
def __init__(self):
self._contacts = []
def add(self, name, phone, mail):
contact = Contact(name,phone, mail)
self._contacts.... |
3a7d125ffaa6d6c74e75e4389438498663259018 | StRobertCHSCS/fabroa-TLdoublelift | /Working/Practice Questions/2_8_4_loops.py | 121 | 3.859375 | 4 | start = int(input("Enter the starting number"))
end = int(input("Enter the ending number"))
for i in range(end, start ) |
ce714f825506be6bc6d8ce051bb872b7194a0f57 | StRobertCHSCS/fabroa-TLdoublelift | /Working/Practice Questions/1_3_3_userinput.py | 140 | 3.96875 | 4 | base = int(input("Enter the base: "))
height = int(input("Enter the height: "))
print("The are of the triangle is " + str(0.5*base*height)) |
74e5a4a9baf4dc3ea6f0ebc56664561d8337e60f | JHenrysson/dice_game | /dice/dicehand.py | 596 | 3.75 | 4 | """Dice Hand module."""
class Dicehand():
"""Class to keep track of each turn."""
total = None
def __init__(self):
"""Init the object."""
self.total = 0
def get_total(self):
"""Return the current total for the turn."""
return self.total
def increment(self, value... |
8f1b9e5ca6e42953eea69dee25cb7c0f8b113670 | JHenrysson/dice_game | /dice/player.py | 1,109 | 3.828125 | 4 | """Player class."""
class Player:
"""Player class."""
name = None
highscore = None # Winning the game in least amount of rolls
scores = []
def __init__(self, name):
"""Initialise the object."""
self.name = name
def get_name(self):
"""Return players name."""
... |
89f68c56931c5bf173ca03d29dde76d173319992 | goateater/SoloLearn-Notes | /SL-Python/Data Types/sets.py | 4,341 | 4.4375 | 4 | # Sets
# Sets are data structures, similar to lists or dictionaries.
# They are created using curly braces, or the set function.
# They share some functionality with lists, such as the use of in to check whether they contain a particular item.
num_set = {1, 2, 3, 4, 5}
word_set = set(["spam", "eggs", "sausage"])
pri... |
f95a79a3a2d6c1718efb817cba7c8cb7072ce57f | goateater/SoloLearn-Notes | /SL-Python/Data Types/Dictionaries.py | 2,870 | 4.71875 | 5 | # Dictionaries
# Dictionaries are data structures used to map arbitrary keys to values.
# Lists can be thought of as dictionaries with integer keys within a certain range.
# Dictionaries can be indexed in the same way as lists, using square brackets containing keys.
# Each element in a dictionary is represented by a k... |
333d2fae7916937db479ee1778ed237c59e6e57d | goateater/SoloLearn-Notes | /SL-Python/Opening Files/writing_files.py | 2,703 | 4.5625 | 5 | # Writing Files
# To write to files you use the write method, which writes a string to the file.
# For Example:
file = open("newfile.txt", "w")
file.write("This has been written to a file")
file.close()
file = open("newfile.txt", "r")
print(file.read())
file.close()
print()
# When a file is opened in write mode, th... |
b97a1a271b224eb4e9f99755e69b20898de7182d | benilak/Everything | /HardCoded/01_teach.py | 2,052 | 3.640625 | 4 | import random
import numpy as np
# Part 1
class Movie:
def __init__(self, title="", year=0, runtime=0):
self.title = title
self.year = year
if runtime < 0:
self.runtime = 0
else:
self.runtime = runtime
def __repr__(self):
return "{} ({}) - {} mi... |
e7c9ff96bfd41f28f35486d8635a44bbcdb47126 | benilak/Everything | /CS241_Miscellaneous/scratch_2.py | 2,743 | 4.28125 | 4 | '''class Time:
def __init__(self, hours = 0, minutes = 0, seconds = 0):
self._hours = hours
self._minutes = minutes
self._seconds = seconds
def get_hours(self):
return self._hours
def set_hours(self, hours):
if hours < 0:
self._hours = 0
elif hou... |
54ddf1ddf55bd87d4b72613505f31768522b6761 | benilak/Everything | /DecisionTree/DecisionTree.py | 7,649 | 3.5625 | 4 | """
CS450 - Machine Learning
Implementation of a decision tree classifier and model
(Incomplete: not yet fully functional; needs debugging)
"""
import pandas as pd
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from scipy import stats
from copy import deepcopy
cl... |
246c9d28bb9380dc89e4b40f6efcdf4c40ed9d20 | hpoleselo/robotic_vision | /opencv/apply_blur.py | 2,928 | 3.703125 | 4 | import numpy as np
import cv2 as cv
import sys
img = cv.imread('photo1.jpg')
if img is None:
print("Image could not be loaded.")
sys.exit()
def blurring_filter(img):
# We could as well show the images on matplotlib
useMatPlotLib = False
# Extract dimensions of the photo
h, w = img.shape[0:2]
... |
cb63ddf5d873dc45e0f46f0c048b06cf17864c53 | virenparmar/TechPyWeek | /core_python/Function/factorial using recursion.py | 499 | 4.28125 | 4 | # Python program to find the factorial of a number using recursion
def recur_factorial(n):
"""Function to return the factorial of a number using recursion"""
if n==1:
return n
else:
return n*recur_factorial(n-1)
#take input from the user
num=int(input("Enter a number="))
#check is the number is negative
if... |
830bf963c902c0382c08fca73c71d2fa2f7d1522 | virenparmar/TechPyWeek | /core_python/fibonacci sequence.py | 479 | 4.40625 | 4 | #Python program to display the fibonacci sequence up to n-th term where n is provided
#take in input from the user
num=int(input("How many term?"))
no1=0
no2=1
count=2
# check if the number of terms is valid
if num<=0:
print("please enter a positive integer")
elif num == 1:
print("fibonacci sequence")
print(no1... |
4ae8ad04f48d102055e470f4ca953940a8ca1f25 | virenparmar/TechPyWeek | /core_python/Function/anonymous(lambda) function.py | 299 | 4.46875 | 4 | #Python Program to display the power of 2 using anonymous function
#take number of terms from user
terms=int(input("How many terms?"))
#use anonymous function
result=list(map(lambda x:2 ** x, range(terms)))
#display the result
for i in range(terms):
print "2 raised to power",i,"is",result[i] |
01ab8ec47c8154a5d90d5ee4bd207f143a0051b3 | virenparmar/TechPyWeek | /core_python/Function/display calandar.py | 242 | 4.40625 | 4 | # Python Program to display calender of given month of the year
#import module
import calendar
#assk of month and year
yy=int(input("Enter the year="))
mm=int(input("Enter the month="))
#display the calender
print(calendar.month(yy,mm)) |
17af5750832fde25c0a10ec49865f478fae390d9 | jonathansantilli/SMSSpamFilter | /spamdetector/file_helper.py | 973 | 4.1875 | 4 | from os import path
class FileHelper:
def exist_path(self, path_to_check:str) -> bool:
"""
Verify if a path exist on the machine, returns a True in case it exist, otherwise False
:param path_to_check:
:return: boolean
"""
return path.exists(path_to_check)
def re... |
48d2a44ccda408625d6e3135e639fde3b6f29d56 | Not-Aryan/42Stuff | /ML-4/BMW-Classifier.py | 1,551 | 3.875 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
#Preparing the data
dataset = pd.read_csv('/nfs/2020/a/ajain/PycharmProjects/MachineLearning/ML... |
b691efcbbdbb0abf8591c190d67079d3a579a121 | slipmar/Python-Exercises | /eje15.py | 265 | 3.625 | 4 | def intercambio(x,y):
print 'Funcion Original'
print 'x = ',
print x
print 'y = ',
print y
temporal = x
x = y
y = temporal
print 'Intercambio'
print 'x = ',
print x
print 'y = ',
print y
x=input('Ingrese X: ')
y=input('Ingrese Y: ')
intercambio(x,y) |
3b3d64ffddd2f6be4367fda557e6e88108fa3fee | slipmar/Python-Exercises | /eje3.py | 487 | 3.96875 | 4 | def sortASC():
counter = 1
print 'Escribe diez nmeros o cadenas (slo tienes que seleccionar un tipo de datos): '
list = []
while counter != 10:
a = input('Value = ')
list.append(a)
cont += 1
list.sort()
print list
def sortDESC():
counter = 1
print 'Escribe diez nmeros o cadenas (slo tienes que selecc... |
05f0364d9561b9cd6fc0b9dd2b1cc2662497c5dc | Mindstormer619/Python-DS | /graph.py | 3,369 | 3.78125 | 4 | from collections import deque
class Graph:
def __init__(self,directed = False,weighted = False):
self._graph = {}
self.directed = bool(directed)
self.weighted = bool(weighted)
self.edgeCount = 0
self.vertexCount = 0
def addVertex(self,node):
if node not in self._graph:
self._graph[node] = []
se... |
d2b0d45cabf1c9ad1c5c47b8da4178ed7b451ae5 | GiovanaArreola/TrazoDePoligono_GiovanaArreola | /AlgoritmoNLados-Rentrega-GiovanaArreola-3061.py | 2,682 | 3.921875 | 4 | import turtle as t
# Pide el numero de lados
lados = int(input("Ingresa el numero de lados: "))
def DDA():
angulo = 0
x1 = 2
y1 = 2
x2 = 2
y2 = 6
n = lados
dx = abs(x2 - x1)
dy = abs(y2 - y1)
steps = 0
if (dx) > (dy):
steps = (dx)
else:
... |
23f1a1b8dbb2e627abdce1a45351bc2b538bdd2d | Tomdssdasd/try | /p7.py | 274 | 3.71875 | 4 | # 输入一个数求1!+2!+3!+4!+n!=?
num=int(input("请输入一个数字:"))
l=1
sum=0
if num<0:
print("负数没有阶乘")
elif num==0:
print("0的阶乘为1")
else:
for i in range(1,num+1):
l=l*i
sum+=l
print("得数是:",sum) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.