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 |
|---|---|---|---|---|---|---|
1c64989c3d865d279c0d8bc7dbbba53dc4c4c247 | loadlj/leetcode | /Range_sum_query.py | 760 | 3.734375 | 4 | # Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
class NumArray(object):
def __init__(self, nums):
self.nums = nums
self.updatedlist = []
self.updateList()
def updateList(self):
if len(self.nums) >0:
self.updat... |
4b784585fefbe4087acbc9747f481fc650a21f84 | D7DonKIM7E/Python | /BOJ_2588.py | 119 | 3.6875 | 4 | first = int(input())
second = input()
for digit in second[::-1] :
print(first*int(digit))
print(first*int(second))
|
a686a0f2ff0ea00d450015ed2f203ac144098c0d | luka3117/toy | /py/山内 テキスト text sample code/ohm/ch4/list4-2.py | 1,149 | 3.515625 | 4 | #-*- coding: utf-8 -*-
# List 4-2 skew、kurtosisの例
from scipy.stats import skew, kurtosis, norm, uniform, kurtosistest
import math
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
numsamples = 100000
v1 = norm.rvs(loc=0.0, scale=1.0, size=numsamples)
print('正規分布N(0,1)', 'skew=', round(skew(v1... |
5e260fa16cb00b8d231a1285fe00b907654183c2 | luka3117/toy | /py/山内 テキスト text sample code/ohm/ch7/list7-7.py | 2,833 | 3.53125 | 4 | # -*- coding: utf-8 -*-
# List 7-7 出生率と死亡率の関係
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
np.set_printoptions(precision=4)
x = np.loadtxt('shusseiritsu.csv', delimiter=",") # CSVファイルからデータを読込む
# 出典 http://www.mhlw.go.jp/toukei/saikin/hw/jinkou/suikei15/dl/2015suikei.pdf
birth1 = [u[... |
afdc0cfdf6ac796e06cc2e1cd574cfb765b67eed | j2sdk408/misc | /mooc/algorithms_II/lsd_sort.py | 2,265 | 3.625 | 4 | """
implementation for least-signficant-digit-first string sort
"""
from str_custom import StringCustom
class LsdSort(object):
"""class for LSD string sort"""
def __init__(self, str_list):
"""initialization"""
self.str_list = str_list
self.sort()
def __str__(self):
"""to... |
20fadd9ad05d61ed6b884287fd0cebdd0ae916e6 | j2sdk408/misc | /mooc/algorithms_II/st_tst.py | 4,503 | 3.734375 | 4 | """
implementation for string symbol table with ternary search try
"""
class Node(object):
"""class for tri node"""
MIDDLE = 0
LEFT = 1
RIGHT = 2
def __init__(self):
"""initialization"""
self.value = None
self.char = None
# 0: middle
# 1: left
# 2... |
e671953c188a7d380130aa00f48a25ccbf099ad5 | j2sdk408/misc | /mooc/algorithms_II/msd_sort.py | 2,709 | 3.546875 | 4 | """
implementation for least-signficant-digit-first string sort
"""
from str_custom import StringCustom
class MsdSort(object):
"""class for MSD string sort"""
def __init__(self, str_list):
"""initialization"""
self.str_list = str_list
self._aux_list = [None] * len(self.str_list)
... |
8829a7674ab5b9cdd3b0e5e54f28611912b206d8 | j2sdk408/misc | /mooc/algorithms_II/pathes.py | 858 | 3.734375 | 4 | """
implementation of graph algorithms
"""
class Pathes(object):
"""class for path searching"""
def __init__(self):
"""initializer"""
self.s = 0
@classmethod
def from_graph(cls, G, s):
"""find pathes in G grom source s"""
p = cls()
p.s = s
assert s <... |
02307d05d584281dd61948087f1ed8fc6853dafd | chitritha/python-project | /finalProj_cnalluru_07.py | 5,965 | 3.890625 | 4 | """
Program: Commodity Data Filtering Final
Author: Nalluru Chitritha Chowdary
Description: This program is used to filter and represent data based on user inputs
Revisions:
00 - Importing CSV, datetime and plotly modules
01 - Printing announcement
02 - Import data from CSV file and change into required format
... |
94a97edaa66c9527fc133ec3c33386a5410968ba | biradarshiv/Python | /CorePython/24_String_Formatting.py | 1,464 | 4.46875 | 4 | """
The format() method allows you to format selected parts of a string.
Sometimes there are parts of a text that you do not control, maybe they come from a database, or user input?
To control such values, add placeholders (curly brackets {}) in the text, and run the values through the format() method:
"""
print("# Fi... |
6ef55a33502d489e160f6b1109182584a17b792b | biradarshiv/Python | /CorePython/1Introduction_Comments.py | 1,466 | 4.03125 | 4 | """
Python is a programming language.
Python Syntax compared to other programming languages
Python was designed for readability, and has some similarities to the English language.
Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.
Python us... |
a36c60c380517b1e6b6d146669e9b93cf797fbcd | biradarshiv/Python | /CorePython/13_ClassObject.py | 2,393 | 4.25 | 4 | """
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
"""
print("# Create a class and access a property in it")
class MyClass:
x = 5
print(MyClass)
p1 = MyClass()
p... |
3edbceaa1a25e81edc5e284886f8a74ed0b875cc | szoto1/python101 | /day03.py | 3,946 | 3.625 | 4 | # # # # # wiek = input("Ile masz lat?")
# # # # # koty = input("Ile masz kotów?")
# # # #
# # # # # wiek = 2
# # # # # koty = 5
# # # #
# # # # # zdanie = "Ala ma 2 lata i posiada 5 kotów."
# # # # # zdanie = "Ala ma " + str(wiek) + " lata i posiada " + str(koty) + " kotów."
# # # # # zdanie = f"Ala ma {wiek} lata i po... |
50d9dd353abba8ec79d57f9603db650e5756fae9 | sathishkumar-smart/Sathish-kumar | /grap.py | 286 | 3.796875 | 4 | import turtle
colors = [ "red","purple","blue","green","orange","yellow","white","brown","violet"]
my_pen = turtle.Pen()
turtle.bgcolor("black")
for i in range(360):
my_pen.pencolor(colors[i % 9])
my_pen.width(i/50 + 1)
my_pen.forward(i)
my_pen.left(65) |
3446b3c1b5cb77bc60d2c5709e91d8656c3447ea | Nicholas-Swift/Data-Structures | /set.py | 5,193 | 3.859375 | 4 | # A Hash Table
from linkedlist import LinkedList
class Set(object):
def __init__(self, init_size=8):
"""Initialize this hash table with the given initial size"""
# Best: Omega(1)
# Worst: O(n) (init size)
self.buckets = [LinkedList() for i in range(init_size)]
self.entri... |
4ff11193a8c26d84d00ba20d3fab03525b980fa9 | Nicholas-Swift/Data-Structures | /test_deque.py | 2,267 | 3.765625 | 4 | #!python
from deque import Deque
import unittest
class QueueTest(unittest.TestCase):
def test_init(self):
q = Deque()
assert q.peekLeft() is None
assert q.peekRight() is None
assert q.length() == 0
assert q.is_empty() is True
def test_init_with_list(self):
q ... |
0abe423a5725967d6b813d2c72571fb1d5b96773 | Junrongh/15-619-CloudComputing | /Project1_1/q5.py | 1,235 | 3.8125 | 4 | #!/usr/bin/env python3
import pandas as pd
import json
from csv import QUOTE_NONE
def main():
"""
Please search and read the following docs to understand the starter code.
pandas.read_table
1) With 'squeeze=True', pandas.read_table returns a Series instead of a
DataFrame.
2) Wi... |
5b23f87d82b4596860ca67e2d6232e4207f053a9 | kanosaki/picbot | /picbot/utils/__init__.py | 824 | 3.5 | 4 |
import itertools
def uniq(*iters):
"""Make unique iterator with preserving orders. """
return UniqueIterator(itertools.chain(*iters))
class UniqueIterator(object):
def __init__(self, source):
self.source = source
self._history = set()
def __iter__(self):
return self
def ... |
8f6472d4db42afc132521b63df85977a06582164 | SociallyAwkwardTurtle/Python | /Vestluskaaslane.py | 398 | 3.96875 | 4 | print("Hello world!")
print("I am Thonny!")
print("What is your name?")
myName = input()
print("Hello, " + myName + ", it's nice to meet you!")
print("How old are you?")
input()
print("Oh, that's nice!")
from random import *
a = (randint(2, 5))
if a == 2:
a=("two")
elif a == 3:
a=("three")
elif a == 4:
a=("... |
f0d4e56573bf9b971b561a94b472facc155ebb35 | ajboxjr/CS-2-Tweet-Generator | /class7/data-structure/linkedlist.py | 7,118 | 4.21875 | 4 | class Node(object):
def __init__(self, data):
"""Initialize the node with a data and a pointer(next)"""
self.data = data
self.next = None
def __repr__(self):
"""Return a string representation of this node."""
return 'Node({!r})'.format(self.data)
"""
TO lower space time ... |
d11e5c2dd401e69ba65f98f2557fb496ff1e1a47 | trivedisorabh/Triangle-Symmetries-with-Python-Turtle | /triangle_symmetry_turtle..py | 4,097 | 4.03125 | 4 | import turtle
import tkinter as tk
screen = turtle.Screen()
class Label(turtle.Turtle):
def __init__(self, coordinates=None, screen=screen):
turtle.Turtle.__init__(self)
if coordinates is None:
self.coordinates = [0, 0]
else:
self.coordinates = coordinates
... |
b20a049364c8648b65d06340a2cdd1613ff9c5ec | chris31513/haskell-pearls | /Python/criptoaritmos.py | 3,745 | 3.546875 | 4 | #Christian Rodrigo Garcia Gomez
#Decidí usar Python por que se me facilita mucho más pensar el código en este lenguaje.
#Especificamente para este problema es más sencillo usar Python porque resulta más claro a la hora de trabajar con listas.
import random
import sys
import gc
sys.setrecursionlimit(30000000)
def cr... |
2358ce9bd1a93f9692cff142908bde4f985fd4c5 | sukiskumar/sukiskumar | /ex3.py | 202 | 4.125 | 4 | ch=input("enter a char:")
if(ch=='A'or ch=='a'or ch=='E'or ch=='e'or ch=='I'or ch=='i'or ch=='O'or ch=='o'or ch=='U'or ch=='u'):
print(ch,"its a vowel letter")
else:
print(ch,"its a consonent")
|
7bd52e231d77bfe94c4277772ef77bc4f56b7f57 | Andyyesiyu/IS590 | /Assignment/A2/hw2.py | 10,993 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
from ast import literal_eval as make_tuple
import math
# Edge definition:
# - p1, p2: endpoints of the segment
# - slope: slope of the segment
# - intersect: intersect of the line (extention of the segment most probably) on the y axis
class Edge:
def __i... |
4db5286513dde4db5afc628bb1c084b187ee898a | sfaisalaliuit/dictionary | /dict_double_prog3.py | 439 | 3.90625 | 4 | faisal = {'username': 'sfaisal', 'online': True, 'students': 145, 'section':'Computer Science', 'experience in years':21}
farhan = {'username': 'farhanahmed', 'online': False, 'students': 144, 'section':'Software Engineering', 'experience in years':15}
for key, value in faisal.items():
print(key, 'is the key f... |
f846806fe36f18555ee326609d90581c099e6ee2 | ps3296/Automated-Pun-Generator | /python files/Scripts/Scripts/homonyms_textfile_cdt/trial_generate_jokes.py | 967 | 3.765625 | 4 | def indefinite_article(w):
if w.lower().startswith("a ") or w.lower().startswith("an "): return ""
return "an " if w.lower()[0] in list('aeiou') else "a "
def camel(s):
return s[0].upper() + s[1:]
def joke_type1(d1,d2,w1):
return "What do you call " + indefinite_article(d1) + d1 + " " + d2 + "... |
7f27483d65ad0113c2b9159fa6ef4e15c59992b7 | TeamContagion/CTF-Write-Ups | /2022/SekaiCTF2022/crypto/SecureImageEncryption/enc.py | 1,646 | 3.6875 | 4 | from PIL import Image
def openImage():
#opens both images and loads them
img1 = Image.open("encryptedimg1.png")
img2 = Image.open("encryptedimg2.png")
pixels1 = img1.load()
pixels2 = img2.load()
width1, height1 = img1.size
width2, height2 = img2.size
list1 = []
#check for correct s... |
47846eb1a2b8b5db15f5f7262ae51e15973eb75b | oxfordni/python-for-everyone | /examples/lesson2/4_exercise_1.py | 372 | 4.21875 | 4 | # Determine the smallest number in an unordered list
unordered_list = [1000, 393, 304, 40594, 235, 239, 2, 4, 5, 23095, 9235, 31]
# We start by ordering the list
ordered_list = sorted(unordered_list)
# Then we retrieve the first element of the ordered list
smallest_number = ordered_list[0]
# And we print the result
... |
0c4af3021580b97e5d9d244695e5a22e5e9eb136 | oxfordni/python-for-everyone | /examples/lesson2/1_data_types_tuples.py | 152 | 3.875 | 4 | # Define an initial tuple
my_tuple = (1, 2, 3)
# Print out the list
print(my_tuple)
# Print the value at the beginning of the list
print(my_tuple[0])
|
c700081a72e7cc131897478a8f02db1507044b07 | apalaciosc/python_quantum | /practica_01/ejercicio_01.py | 180 | 3.671875 | 4 | def ensure_question(palabra):
if len(palabra) == 0:
print('Cadena no válida')
else:
print(f'{palabra}?')
palabra = input('Escriba una palabra: ')
ensure_question(palabra)
|
321b6d8b4b9ccd840eef7801dccf0cffa7a571fe | apalaciosc/python_quantum | /clase_07/scrapping.py | 893 | 3.875 | 4 | from bs4 import BeautifulSoup
html_doc = """
<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<p class="title story title2"><b>The Dormouse's story</b></p>
<p class="story">
Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="si... |
c1bbd7598c2a95628257451d744cfd3cf6bf1f98 | nawan44/Python-Basic | /iteration.py | 171 | 4.03125 | 4 | #basic iteration
Spirit = 5
for Day in range(1, Spirit+1):
print('Never Give Up')
#iteration in string
Hi = 7
for Good in range(2, Hi+7):
print(f'Morning {Good}') |
55e1d5407c28c0ea3953dedfe7bb97981a8d0455 | nawan44/Python-Basic | /arithmetic.py | 476 | 3.921875 | 4 |
#Standart Operator Arithmetic
a = 10
b = 3
#operator +
res = a + b
print(a, '+', b ,'=', res)
#operator -
res = a - b
print(a, '-', b ,'=', res)
#operator - Multiple
res = a * b
print(a, '-', b ,'=', res)
# operator / Dividen
res = a / b
print(a, '/', b ,'=', res)
# operator ^2 Eksponen
res = a ** b
print(a... |
18ca47e10a0af9166e4366ca61b3a726bbc74454 | callmefarad/Python_For_Newbies | /sesions/stringslice.py | 756 | 4.53125 | 5 | # slicing simply means returning a range of character
# this is done by using indexing pattern
# note when dealing with range the last number is exclusive.
# i.e if we are to get the last letter of digit 10, we would have a
# range of number tending to 11 where the 11th index is exclusive
# declaring my variable
my_s... |
f8ccced9d2f8bf8df346c5f5ff77a1fbc8d32954 | callmefarad/Python_For_Newbies | /sesions/rangetype.py | 367 | 4.125 | 4 | # showing range type representation
# declaring a variable name range_of_numbers
range_of_numbers = range(40)
# displaying the range of numbers
print("Below shows the range of numbers")
print(range_of_numbers)
# displaying python representation of the output value
print("Below show the python data type representation... |
85b7757dd6d1e1e5a6872596d297e5a690707f86 | callmefarad/Python_For_Newbies | /sesions/sorting_item.py | 5,457 | 4.3125 | 4 | # SORT
# the sorted() function is used to sort items in ascending order by default or by user prescriptions.
# basic sorting is used without a key and mapping function
# BASIC SORT
# sorting items in a list
print('\nsorted() function shows all the items in ascending order')
items = [1, 29, 37, 97, 2, 57, 37, 58, 46, 6... |
4a2d69fd9c1d182db95a7df2dbead89b3628f002 | callmefarad/Python_For_Newbies | /sesions/stringreplacement.py | 164 | 4.40625 | 4 | # The string replacement is used to replace a character with another
# character in that string.
my_sentence = "Ubani Friday"
print(my_sentence.replace("U", "O"))
|
b30d79e7e57f57b9b079bb566e41c6deb88425c5 | callmefarad/Python_For_Newbies | /sesions/languagetranslation.py | 708 | 4.0625 | 4 | # This progrma is called the cow translation language.
# It converts every vowel letter found in a word to "COW", thereby forming the cow language.
# defining the function
def copywrite():
print("Copywrite: Ubani U. Friday")
def translate(phrase):
word_translation = "" # an empty variable to hold each elem... |
b59e530c1b2e7d8275003cde9e1b8bce78d9b43f | callmefarad/Python_For_Newbies | /sesions/membershipin.py | 536 | 4.3125 | 4 | # a membership operator checks if sequence is present in an object
# "in" is on of the membership operator
# creating a variable named "
my_list = ['orange', 'bean', 'banana', 'corn']
print("List of items: ", my_list)
# creating a check variable
check = "banana"
# prints the result
print(check in my_list)
""""
# c... |
fd0795fd1e3b86ce259b392b644d5ade274655f0 | callmefarad/Python_For_Newbies | /sesions/func.py | 1,652 | 4.15625 | 4 | # # declaring a function
# def dummy():
# print("this is a dummy print.")
#
# # callin the function
# dummy()
#
# def add():
# user1 = float(input('Enter your firstnumber: '))
# user2 = float(input('Enter your secondnumber: '))
# sum = user1 + user2
# return sum
#
# # call the function
# add()
# x ... |
0f6be41aa20de93a0ec323b95b78b7e1b906996e | callmefarad/Python_For_Newbies | /sesions/division.py | 257 | 3.828125 | 4 | # division operator is represented with a forward slash "/"
# it is used to get a floating value after a successful divisional operation.
all_states = 30000
lagos_state = 307
total_count = all_states / lagos_state
print("The total count is: ", total_count) |
05700d145da30b014ab880e5af9be1a13d3a0a98 | callmefarad/Python_For_Newbies | /sesions/passwordChecker.py | 1,122 | 4.125 | 4 | # a program that checks if a password is too weak, weak and very strong
# defining the function
def copywrite():
print("Copywrite: Ubani U. Friday")
# main function
special_characters = ['!', '^', '@', '#', '$', '%', '&', '*', '(', ')', '_', '+']
special_numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']... |
918bcf54bf0c511c9f3b07af080991bb0ae64965 | satvks/Djikstras-Dungeon | /P1/p1-myvers.py | 6,713 | 3.84375 | 4 | from p1_support import load_level, show_level, save_level_costs
from math import inf, sqrt
from heapq import heappop, heappush
def dijkstras_shortest_path(initial_position, destination, graph, adj):
""" Searches for a minimal cost path through a graph using Dijkstra's algorithm.
Args:
initia... |
9e34742605447bc3ec4ab6da44d9b5ae5a19d32b | MetallicMonkeyu/image_encrypt | /Cube.py | 5,417 | 3.5625 | 4 | from PIL import Image
from Key import *
class Cube:
#im_path can be pefected by asking user to choose a folder
def __init__(self, img_path = [], block_size = 8):
self.image = [] #Open a new file
self.blc_size = block_size
self.img_path = img_path
def Row(self, row_index, shift... |
67c8770308f34f234d91c330da73e5aefee2a58c | Ilis/dawson | /useless_trivia.py | 585 | 4.125 | 4 | # Useless trivia
name = input("Hi! What's your name? ")
age = input("How old are you? ")
age = int(age)
weight = int(input("What is your weight? "))
print()
print("If Cammings write you a letter, he write", name.lower())
print("If mad Cammings write you a letter, he write", name.upper())
called = name * 5
print("Kid... |
d05ab90c27a5d8821c19b17cb48a2dafc78f35bc | GaboUCR/Mit-Introduction-to-python | /ps1/Ps1B.py | 848 | 4.28125 | 4 | total_cost = float(input("Enter the cost of your dream house "))
annual_salary = float(input("enter your annual salary "))
portion_saved= float(input("enter the percentage to be saved "))
semi_annual_raise = float(input("Enter the percentage of your raise"))
current_savings = 0
annual_return = 0.04
total_months = 0
por... |
9aac5e114701687f7fd97c620cdba469a6d117de | malikrafsan/Python-Language-Linter | /cyk_parser.py | 1,244 | 3.578125 | 4 | # File ini adalah CYK Parser yang digunakan
# Pada file ini, dilakukan pengecekan syntax dengan CYK
def cyk_parser(grammar, prob):
#grammar -> a dictionary of CNF
#prob -> string problem
#Set up variable
numb = len(prob)
if(numb == 0):
return True
parsetable = [[[] for i in range(num... |
b5e10ed6fec1e800562c5e7a381eceb00b53b6ab | aleph2c/miros-random | /set_hacking.py | 673 | 3.59375 | 4 | from itertools import combinations
def make_combo(_max, _pick):
comb = combinations(list(range(1,_max+1)), _pick)
return list(comb)
print(make_combo(3, 2))
def make_next(_max, _pick):
full_combo = [a for a in make_combo(_max, _pick)]
sub_combo = [b for b in full_combo if _max in b]
return sub_co... |
8111dfc4110b25b75a6d8f4e3e583aa583a54d31 | DoughyJoeyD/WorkLog2 | /task.py | 1,889 | 4.125 | 4 | from datetime import datetime
import os
import time
#handy script to clean the screen/make the program look nice
def clearscreen():
os.system('cls' if os.name == 'nt' else 'clear')
#how each task is constructed
#name
#date of task
#time taken
#extra notes
class Task():
def __init__(self):
... |
bd0e4c8d341eab303c06ea1a3ab55c1b67cce480 | uniquezhiyuan/ShipClassify | /route_revise.py | 3,550 | 3.6875 | 4 | import numpy as np
import pandas as pd
from math import sqrt
import time
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
# print(data_1.describe())
# 最小二乘回归
def least_squares(x, y):
x_ = x.mean()
y_ ... |
4aed7141e11f5cabd8d860ecdac245dffe71e6df | Gutwack/pythonProjects | /basicMetacamDose.py | 235 | 3.921875 | 4 | breed = input("Is this a dog or a cat?")
weight = float(input("What is the weight?"))
if breed == "dog":
dose = weight * 0.04
print(dose)
elif breed == "cat":
dose = weight * 0.05
print(dose)
else:
print("error")
|
01886e6780ca312c23c54061942ab487f0477727 | olamileke/web-scraping | /nytimes.py | 2,209 | 3.65625 | 4 | # Python program to fetch the contents of an nytimes article
from bs4 import BeautifulSoup, Tag
from urllib.request import Request, urlopen
import re
url = input('enter the url for the nytimes articles - ')
# formatting the text in the format we want
def parse_text(soup):
article_title = soup.h1.string
artic... |
2035a32bf51f3e3b3134e30a2943dd7d7a66220f | Terund/tools | /代码/进程、线程、协程/多线程访问共享数据的问题.py | 889 | 3.75 | 4 | """
多线程访问共享数据的问题:
1.哪些问题
数据混乱问题
2.如何解决
用锁(互斥锁)threading.Lock
获取锁(上锁)
lock.acquire()
释放锁(解锁)
locl.release()
获取锁与释放锁的次数要对应
好处:
保护数据安全,实现数据同步,不会混乱
弊端:
效率降低
容易导致死锁
"""
import time
import threading
#模拟的总票数
tickets = 1000
lock = threading.Lock()
def sale(name):
global tickets... |
2ac555d1dccc370a726e52e8283c1957de19b7a5 | andrew5205/Maching_Learning | /Python/regression/linear_regression/linear_regression.py | 1,933 | 3.828125 | 4 |
# Linear
# y = b0 + b1 * x1
# y: Dependent Variable (DV)
# x: Independent Variable (IV)
# b1: Coeddicient
# b0: Constant
# sum( y - y^) ** 2
# *********************************************************************************************************************
# Simple Linear Regression
# Importing the librarie... |
4ee82efb6887d9f33e7d71fdec4fa23bb129cd57 | StrategyCode/CourseEra | /Assignment_4.6.py | 392 | 3.6875 | 4 | def computepay():
if Hr > 40:
GrossPay=((Hr-40) * 1.5 * RatePerHour + (40 * RatePerHour))
else:
GrossPay=Hr * RatePerHour
return GrossPay
Hr=input("Enter Hours Worked")
RatePerHour=input("Enter Rate per Hours")
try:
Hr=float(Hr)
RatePerHour=float(RatePerHour)
except:
print("Pleas... |
ca3966a88fae4251deb78a587564f7bb82d348ec | StrategyCode/CourseEra | /Assignment_12.2.py | 617 | 3.578125 | 4 | #To read the Web Content using URL and get the sum of all numeric Values.
import urllib.request,urllib.error,urllib.parse
import re
from bs4 import BeautifulSoup
sum=0
#Reading the content of Web Page
#WebContent=urllib.request.urlopen('http://py4e-data.dr-chuck.net/comments_42.html').read()
WebContent=urllib.request... |
2062897e73bd9d494b843b2853bb63cfa3010477 | AzizIsa/python-challenge | /PyBank/main.py | 1,738 | 3.765625 | 4 | #Import necessary libriaries
import os
import csv
import sys
#Define average function
def average(list):
return int(sum(list) / len(list))
#Create a path for the file
csvpath = os.path.join('Resources', 'budget_data.csv')
# Open the csv file
with open(csvpath, newline='') as csvfile:
# read the file
csvre... |
48f2cb31b76fb208e71f6ffe91d372979886dd47 | harshagl2002/COVID_CLI | /Province_CovidTracker.py | 2,835 | 3.53125 | 4 | import requests
import json
import datetime
def province():
url = "https://covid-19-statistics.p.rapidapi.com/reports"
ISO = input("Enter the ISO code of the country that you would like to search for.(ISO code of India is IND. ISO code of New Zealand is NZ): ")
province = input("Enter the province you wou... |
913d183c3e9b8d62e2637c2f4bef9748c0923f83 | LostRob/Paradise | /水仙花数.py | 196 | 3.609375 | 4 | a = int(input( 'a = '))
x = int(a//100)
y = int((a//10)%10)
z = int(a%10)
if (x ** 3 + y ** 3 + z ** 3) == x * 100 + y * 10 + z:
print('是水仙花数')
else:
print('不是水仙花数')
|
b00bc36b3d68b0ecdb14f3b8906e032593a74038 | SuryaNMenon/Python | /Functions/shapeArea.py | 699 | 4.03125 | 4 | def circArea():
radius = int(input("Enter radius"))
print("Area =", (3.14 * radius**2))
def triArea():
base = int(input("Enter base"))
height = int(input("Enter height"))
print("Area =", (0.5 * base * height))
def recArea():
length = int(input("Enter length"))
breadth = int(input("Enter breadth"))
... |
2327acffc2344bdbc183846ef128e0337d5367c3 | SuryaNMenon/Python | /Classes/rectangleClass.py | 343 | 3.90625 | 4 | class Rectangle:
def __init__(self,length,width):
self.length = length
self.width = width
def Area(self):
print(f"Area = {self.length * self.width}")
def Perimeter(self):
print(f"Perimeter = {2*(self.length + self.width)}")
rec1 = Rectangle(5,10)
rec2 = Rectangle(20,10)
rec1.... |
7df9906b8a9cc0b658ed28494a8598c0948625ec | SuryaNMenon/Python | /Dictionaries/mapLists.py | 295 | 4.03125 | 4 | userlist1 = []
userlist2 = []
for iter in range(int(input("Enter the number of keys"))):
userlist1.append(input("Enter key: "))
for iter in range(int(input("Enter the number of values"))):
userlist2.append(input("Enter value: "))
userdict = dict(zip(userlist1,userlist2))
print(userdict) |
ae9a97b3fb40b8285182bb65d435f836de70ada6 | SuryaNMenon/Python | /Functions/timeAndCalendar.py | 543 | 4.21875 | 4 | import calendar,time
def localTime():
localtime = time.asctime(time.localtime(time.time()))
print(f"Current local time is {localtime}")
def displayCalendar():
c = calendar.month(int(input("Enter year: ")),int(input("Enter month: ")))
print("The calendar is:\n",c)
while(1):
choice = int(input("Menu\... |
a71788020b4f3fb954314330c388705e504a56dc | SuryaNMenon/Python | /Other Programs/whileCountdown.py | 192 | 4.21875 | 4 | #Program to print a countdown using user input range and while loop
high = int(input("Please enter the upper limit of the range"))
i=high
while i>-1:
print(i)
i-=1
print("Blast off!")
|
fb5c157023bdc1099b78647dcf39010377639d26 | SuryaNMenon/Python | /Files/writeAndRead.py | 284 | 3.625 | 4 | with open("/Ghosty's Files/Programming/Python/Files/testfile4.txt","a") as file:
file.write(input("Enter data to be inserted into the file. EOL = NewLine"))
with open("/Ghosty's Files/Programming/Python/Files/testfile4.txt", "r") as file:
for line in file:
print(line) |
8c2bbc0c0175bc8883d9fe65cbca3511dbefd81e | SuryaNMenon/Python | /Other Programs/leapYear.py | 217 | 4.3125 | 4 | #Program if user input year is leap year or not
year = int(input('Enter the year'))
if(year%4==0 or year%100==0 or year%400==0):
print('Given year is a leap year')
else:
print('Given year is not a leap year')
|
6feb3063ad9b8e229f56dd16dc7c9c7a525bf1d5 | SuryaNMenon/Python | /Other Programs/factorial.py | 187 | 4.34375 | 4 | #Program to print factorial of user input number
num = int(input('Enter the number\n'))
fact = 1
for iter in range(1,num+1):
fact = fact * iter
print('Factorial of', num, 'is', fact)
|
6722bc1f4b416b80bf6211d900e3444c27abd2b9 | bigsnarfdude/d3py | /d3py/css.py | 2,020 | 3.671875 | 4 | #!/usr/bin/python
class CSS:
"""
a CSS object is a dictionary whose keys are CSS selectors and whose values
are dictionaries of CSS declarations. This object is named according to the
definition of CSS on wikipedia:
A style sheet consists of a list of rules.
Each rule or rule-set consi... |
5493d5308b986e4efd6bfed3687712872d76bc35 | hyjae/udemy-data-wrangling | /DataCleaning/audit.py | 2,698 | 4.21875 | 4 | """
Observation of types
- NoneType if the value is a string "NULL" or an empty string ""
- list, if the value starts with "{"
- int, if the value can be cast to int
- float, if the value can be cast to float, but CANNOT be cast to int.
For example, '3.23e+07' should be considered a float because it can be cast
... |
d203e5505f5db11247c9235d678999ed345e5d61 | PrathmeshPure/fun-py-programs | /file-translator-using-googleapi.py | 4,098 | 3.734375 | 4 | '''
by: Prathmesh Pure
This program is written to translate small text or srt files from
original language to target language.
Source language is detected automatically.
This program is just passing a string and language code to google translate api
and takes response from api and displays only translated text.
Languag... |
4afad85b6bcbaf932ee7a4754308804db627d963 | kalyanrohan/ASSIGNMENTS | /FIBONACCI.py | 246 | 4.15625 | 4 |
#0,1,1,2,3,5,8
def fibonacci(n):
if n <= 1:
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
nterms = int(input("n= "))
print("Fibonacci sequence:")
for i in range(nterms):
print(fibonacci(i))
|
1df3bc87016ad046ffc4c7a27108e943ae84da27 | kalyanrohan/ASSIGNMENTS | /level2excercise.py | 1,187 | 4.6875 | 5 | #LEVEL 2
"""
1.Using range(1,101), make a list containing only prime numbers.
"""
prime=[x for x in range(2,101) if x%2!=0 and x%3!=0 and x%5!=0 and x%7!=0]
print(prime)
"""
2.Initialize a 2D list of 3*3 matrix. E.g.-
1 2 3
4 5 6
7 8 9
Check if the matrix is symmetric or not.
"""
"""
3. Sorting refers to arranging da... |
1ff75c4685f869eece4ada6af2fb00769e251097 | JudgeVector/Projects | /SOLUTIONS/Text/CountVowels.py | 636 | 4.1875 | 4 | """
Count Vowels - Enter a string and the program counts the number of vowels in the text.
For added complexity have it report a sum of each vowel found.
"""
vowels = ['a','e','i','o','u']
vowel_count = [0,0,0,0,0]
def count_vowels(s):
for i in range(0, len(s)):
if s[i] in vowels:
for j in range(0, len(vowels))... |
47d3b0a870d32315963196eef208d39be488c468 | lduran2/dev.array-problems.in-python | /p01B-missing-number-sorted | 5,602 | 4.25 | 4 | #!/usr/bin/env python3
r'''
./p01B-missing-number-sorted
This program finds the missing number in a list of integers. This
implementation is optimized for sorted lists through use of binary
search.
* by: Leomar Duran <https://github.com/lduran2>
* date: 2019-06-28T23:53ZQ
* for: https://dev.to/javinpaul/50-data-struc... |
eeb30e32b2a5b095987e5be0d0249c84328838dc | mwanchap/Oiler | /problem1.py | 561 | 3.765625 | 4 | def getSumOfMultiples(baseNum, count):
the_sum = baseNum
max_value = int(count/baseNum) + 1
for i in range(2, max_value):
the_sum += baseNum * i
return the_sum
def sumDivisibleBy(number, count):
the_max = int(count/number)
return int(number * (the_max * (the_max + 1)) /2)
count = 999... |
73bb14c9e8453d5131fba8c15782a09a23860b28 | glennsvel90/Navy_Weather_Data_Analyzer | /navywDB.py | 8,544 | 3.828125 | 4 | from datetime import date, datetime, timedelta
from tkinter import messagebox
import sqlite3
import NavyWWeb
class NavyWDB():
"""
Create and manages a database that stores local cache of all weather data that's been
downloaded from the internet.
"""
def __init__(self, **kwargs):
""" ope... |
c1235b19604218e998ba053ac1549bc238a1bfe1 | git484/leetcoding | /prime no check.py | 219 | 3.890625 | 4 | y=int(input("enter a no\n"))
flag=1
for x in range(2, y, +1):
if y%x == 0:
print("Not prime")
flag=0
break
if flag==1:
print("It is prime")
|
4241f67d8f7f09470233d34d60cc3da6ae7e80e1 | avner-csumb/python-day4 | /number_game.py | 207 | 3.921875 | 4 | low = int(raw_input('Enter low number: '))
high = int(raw_input('Enter high number: '))
# i = low
# while i <= high:
# print(i)
# i += 1
my_list = range(low, high+1)
for i in my_list:
print(i)
|
ec3e44a582edfa4a939eb1b1f314302dea22c52f | zhangruochi/Book | /FluentPython/chapter2/bisect_module.py | 628 | 3.53125 | 4 | #!/usr/bin/env python3
#info
#-name : zhangruochi
#-email : zrc720@gmail.com
import bisect
HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30]
NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31]
NEEDLES.reverse()
for num in NEEDLES:
position = bisect.bisect_right(HAYSTACK,num)
print(position... |
34f524b2719d445a465475d2ce564c810ac2badb | cy486/python | /cards_tools.py | 3,757 | 3.734375 | 4 | #记录所有的名片
card_list=[]
def show_menu():
"""显示菜单"""
print("*" * 50)
print("欢迎使用【名片管理系统】V1.0")
print()
print("1. 新增名片")
print("2. 显示全部")
print("3. 查询名片")
print()
print("0. 退出系统")
print("*" * 50)
def new_card():
"""增加名片"""
print("-" * 50)
prin... |
f313f28359bae14970c42448354d98f346640793 | neulab/tranx-study | /analysis/submissions/638965bbb0d66a5b0eae27d1324bbf89_task1-1_1596102935/task1-1/main.py | 557 | 3.625 | 4 | import random
output = {}
# generate random chars and ints and add them to a dictionary
for i in range(100):
character = (chr(random.randint(97, 122)))
integer = random.randint(1, 20)
if character in output:
output[character].append(integer)
else:
output[character] = [integer]
# sort ... |
1526c3057de6507187e3cc2f50f9d04e1c9b6df4 | neulab/tranx-study | /analysis/submissions/34b1ef17e6625ba2350f6f1c169591a1_task2-1_1595488334/task2-1/main_patch.py | 320 | 3.609375 | 4 | # Example code, write your program here
import pandas as pd
import os
os.mkdir("output")
df = pd.read_csv('data.csv')
# If you know the name of the column skip this
first_col = df.columns[0]
last_col = df.columns[-1]
# Delete first
df = df.drop([first_col, last_col], axis=1)
df.to_csv('output/output.csv', index=False) |
68473ef8a02dcf900cb061acbc7e1c852fbea181 | neulab/tranx-study | /analysis/submissions/9dd43727b9246d7f2220b94ff43380cf_task1-1_1596138232/task1-1/main.py | 684 | 3.796875 | 4 | # Example code, write your program here
import string
import random
from collections import defaultdict
dict = defaultdict(list)
def random_char():
letter = string.ascii_lowercase
result = ''.join(random.choice(letter))
return result
for i in range (1, 100):
tempkey = random_char()
tempval = rand... |
0b3d42404a595e14ccf1a8089805f1f7e28401df | neulab/tranx-study | /analysis/submissions/0ed2dff1d23b0de1cfcf9edb0ba35b1c_task7-2_1591994712/task7-2/main.py | 1,184 | 3.71875 | 4 | # Example code, write your program here
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
def main():
df = pd.read_csv("StudentsPerformance.csv")
grouped = df.groupby(['gender', 'race/ethnicity'])
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(20, 6))
bar_width = 0.35
for... |
2827ba2ce9df9c1e4174af53375b04a56f1b8981 | neulab/tranx-study | /analysis/submissions/27570bb3cfcc304aeede0cdf6c2e2762_task2-1_1600789334/task2-1/main.py | 472 | 3.640625 | 4 | # Example code, write your program here
import csv
import pandas as pd
#reader = csv.reader(open('data.csv', 'rb'))
with open("data.csv", 'r') as reader,open("output.csv", 'w') as outFile:
out = csv.writer(outFile,delimiter=',',quotechar='"')
for row in reader:
col = row.split(',')
if len(col) >... |
0e4617ecbba8d6579b53c98087b96364e5dc6e83 | neulab/tranx-study | /analysis/submissions/0ed2dff1d23b0de1cfcf9edb0ba35b1c_task1-1_1591986411/task1-1/main.py | 463 | 3.640625 | 4 | # Example code, write your program here
import random
import string
from collections import defaultdict
def main():
letters = [random.choice(string.ascii_lowercase) for _ in range(100)]
numbers = [random.randint(1, 20) for _ in range(100)]
d = defaultdict(list)
for c, x in zip(letters, numbers):
... |
44e9c95706879ed95d2dc9f2f4206dcfff1ac3d2 | neulab/tranx-study | /analysis/submissions/10fb8132405b6c443addb06bc941f9e3_task1-1_1597089229/task1-1/main.py | 633 | 3.703125 | 4 | # Example code, write your program here
import string
import random
num = []
num_paired = []
mydict = {}
letter = string.ascii_lowercase
res = ''.join(random.choice(letter) for i in range(100))
#print(res)
for i in range(100):
num.append(random.randint(1, 20))
#print(num)
for i in range(100):
for j in range(1... |
6657bda6817d3be50fabbe73148becf243bee6f3 | neulab/tranx-study | /analysis/submissions/0bd31633162f7a836160dd5b6359d29b_task2-1_1601661947/task2-1/main_patch.py | 188 | 3.640625 | 4 | import pandas as pd
columns_needed = ["first_name","last_name","email","gender"]
df = pd.read_csv('data.csv', usecols = columns_needed)
df.to_csv(r'example_output/output.csv')
print(df) |
f945785dd904c59d4723a7ed0db600d45e180b54 | kju2/euler | /problem067.py | 1,013 | 3.75 | 4 | """
By starting at the top of the triangle below and moving to adjacent numbers on
the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom in triangle.txt, a 15K text file
containing a triangle with one-hundred rows.
NOTE:... |
9b3661b407e31b15525d7caa1f956252a28a9d99 | kju2/euler | /problem047.py | 1,265 | 3.703125 | 4 | """
The first two consecutive numbers to have two distinct prime factors are:
14 = 2 * 7
15 = 3 * 5
The first three consecutive numbers to have three distinct prime factors are:
644 = 2^2 * 7 * 23
645 = 3 * 5 * 43
646 = 2 * 17 * 19.
Find the first four consecutive integers to have four distinct primes factors.
What... |
15090f3167cc207f0cf64acb0b3c84e27bbf85c4 | kju2/euler | /problem304.py | 1,494 | 3.515625 | 4 | """
http://projecteuler.net/problem=304
"""
def fib(nth):
"""fib returns the nth fibonacci number."""
fib_matrix = [[1, 1], [1, 0]]
if nth == 0:
return 0
power(fib_matrix, nth - 1)
return fib_matrix[0][0]
def power(matrix, exponent):
"""power computes the power to a given matrix."""
... |
53cf3eed32f2c405ee56e4b433e3180bc1aa1d77 | kju2/euler | /problem033.py | 1,362 | 4.15625 | 4 | """
The fraction 49/98 is a curious fraction, as an inexperienced mathematician in
attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is
correct, is obtained by cancelling the 9s.
We shall consider fractions like, 30/50 = 3/5, to be trivial examples.
There are exactly four non-trivial examples ... |
b0d32f2891d07fb5f8e5ae9e803d549f68d30e51 | kju2/euler | /problem005.py | 1,244 | 4.0625 | 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?
"""
def main():
"""
divisible by 2 if step is 2
divisible by 3 if step is 3*2
divisible by... |
62c31161a0a2b0b85a00071db97210d1d3892454 | HarshVikram/learning-python | /Python Syntax/if_else.py | 287 | 4.09375 | 4 | size = input('Enter the size of shirt: ')
value = int(size)
if value == 40:
print(' is S')
elif value == 42:
print(size + ' is M')
elif value == 44:
print(size + ' is L')
elif value > 44:
print('Size is not available')
else:
print('We would have to place a custom order')
|
79a2518aa79292f1ddffd39a3f3b78f0d7e07e0e | Kuomenghsin/my-learning-note | /HW2/heap_sort_ 06111306.py | 1,400 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
class Solution():
def heap_sort(self, nums):
self.nums = nums
self.heapSort(nums)
return nums
def toHeap(self,arr, n, i): #堆積size = n
bigest = i # 子樹根初始值 index = i
L = 2*i + 1 # (左子節點) = 2*i + 1 由左子數計算樹根位址i... |
f334ed11c9801ead3700cc0fa687ff7a81353643 | kn0709/python | /gu_nu.py | 762 | 3.796875 | 4 | import random
def number_game(in_val):
number_range = [x for x in range(1,101)]
rand_num = random.choice(number_range)
if int(in_val) == rand_num:
print("Amazing how did this happen")
else:
diff_num = int(in_val) - rand_num
if diff_num < 0:
print("You are just {} behind".format(diff_num * -1))
print("I ... |
a3940af34ce7d808facbdb0ac67cdbbd17d50a23 | xxrom/617_merge_two_binary_trees | /main.py | 2,534 | 4.125 | 4 | # Definition for a binary tree node.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __str__(self):
return str(self.__dict__)
class Solution:
# print all values
def printAll(self, root):
if root... |
f1773013a4d82b0d140d882e87e25dd3a6205bc8 | isaaczinda/route-planner | /tools/Geometry.py | 3,274 | 3.75 | 4 | import math
import numpy as np
def DifferenceBetweenDegrees(One, Two):
Difference = abs(One - Two)
if Difference <= 180:
return Difference
else:
return abs(Difference - 360)
# always returns an angle less than pi radians
def AngleBetweenLines(LineOne, LineTwo):
LengthOne = np.linalg.norm... |
2d3924eabaa80591b15c9b3530ca10b1aa0b20d7 | adityaramkumar/LeetCode | /144.py | 416 | 3.65625 | 4 | # Runtime: 44 ms, faster than 37.20% of Python3 online submissions for Binary Tree Preorder Traversal.
# Difficulty: Medium
class Solution:
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
return [ro... |
e7b383915b973dac1dd462df936a45c53e5b8c46 | adityaramkumar/LeetCode | /125.py | 452 | 3.828125 | 4 | # Runtime: 80 ms, faster than 42.27% of Python3 online submissions for Valid Palindrome.
# Difficulty: Easy
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = self.clean_string(s)
return s == s[::-1]
def clean_string(self, s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.