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 |
|---|---|---|---|---|---|---|
e35cc82f1e4e633fa23184aa0d8edf7f54a1fae5 | sandeepbaldawa/Programming-Concepts-Python | /strings/reverse_words.py | 123 | 4.15625 | 4 | def reverse(input):
return (" ").join([each[::-1] for each in input.split()])
print reverse("Mary had a little lamb")
|
a968a3bca2d0ec1f55f9be6382f26ae2ef1ae6d9 | sandeepbaldawa/Programming-Concepts-Python | /recursion/regex_matching.py | 813 | 4.0625 | 4 | # http://articles.leetcode.com/2011/09/regular-expression-matching.html
# If there is a "+" compare first character(d0es not match return Fale) and then replace with * and continue same logic"
def match(string, pattern):
if len(pattern) == 0 and len(string) == 0:
return True
if (len(pattern) == 0 and l... |
d39cf9c6a416f7678bf3b98e36ab52b6ac17997a | sandeepbaldawa/Programming-Concepts-Python | /recursion/crypto_game.py | 2,243 | 4.34375 | 4 | '''
Given a formula like 'ODD + ODD == EVEN', fill in digits to solve it.
Input formula is a string; output is a digit-filled-in string or None.
Where are we spending more time?
if we run CProfile on CProfile.run('test()')
we see maximum time is spent inside valid function,
so how do we optimize the same?
In valid ... |
8a4090962cf60143b82ae2c02934f8b8c0e16486 | sandeepbaldawa/Programming-Concepts-Python | /arrays/pairs_with_same_diff.py | 1,217 | 3.703125 | 4 | '''
Pairs with Specific Difference
Given an array arr of distinct integers and a nonnegative integer k, write a function findPairsWithGivenDifference that returns an array of all pairs [x,y] in arr, such that x - y = k. If no such pairs exist, return an empty array.
In your solution, try to reduce the memory usage wh... |
16494f0438fe6af0cfc369187fa8c8708bda7925 | sandeepbaldawa/Programming-Concepts-Python | /lcode/amazon/medium_sort_chars_by_freq.py | 504 | 4.25 | 4 | '''
Given a string, sort it in decreasing order based on the frequency of characters.
Example 1:
Input:
"tree"
Output:
"eert"
'''
from collections import defaultdict
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
res = defaultdict(int... |
d63de3639cd7870165658eb974ac857a82dbfca7 | sandeepbaldawa/Programming-Concepts-Python | /python_basics/word_count.py | 1,181 | 3.90625 | 4 | Users-MacBook-Pro:~ user$ vi wc.py
import sys
def print_words(filename):
res = {}
with open(filename, "r") as file:
for line in file:
words=line.strip("\n").split(" ")
for each_word in words:
if each_word in res:
res[each_word] += 1
else:
res[... |
0b96df3ae8e6d60c413590b551b32613b7e2736a | Caosrdz/Python101 | /ifstatement.py | 93 | 3.640625 | 4 | veg = input("dime un vegetal :")
if veg == "corn":
print(True)
else:
print(False)
|
4b6c99511a315b4e438ac7d6a1d61ab07da452c9 | Caosrdz/Python101 | /boolop.py | 122 | 3.625 | 4 | #boolean operators
print(4 > 1 and "hola" == "hola")
print(3 == 2 and "blue" != "red")
print(3 == 2 or "blue" != "red")
|
a7fd15d7416683f46f4e4dc60e096b816768c6ca | DamienCvl/GoogleHash2017 | /main.py | 849 | 3.625 | 4 | def lectureFichier(path):
lineNumber = 0
rowCount = 0
tableauPoint = []
with open(path) as f:
for line in f:
if(lineNumber == 0):
line1 = line.split()
elif(lineNumber == 1):
line2 = line.split()
elif(lineNumber == 2):
... |
c30a97aaad6a9188c71a64457b3ec1c4cb33eb31 | strangemonad/cplr | /ignoreForPackage/ac/adatoken.py | 3,579 | 3.5625 | 4 | class Token(object):
def __init__(self, begin, end, lexeme):
self.begin = begin
self.end = end
self.lexeme = lexeme
def __str__(self):
return '<' + self.__class__.__name__ + ':' \
+ str(self.begin) + ',' \
+ str(self.end) + ',' \
+ self.lexeme + '>'
def __repr__(self):
return str(self)
class Integer... |
d448c781210bfdebb291136bab81c5b0af5e8179 | SailorLee11/anomaly_detection_unws_nb15 | /python_practice/company.py | 1,192 | 4 | 4 | """
@Time : 2021/5/18 21:54
-------------------------------------------------
@Author : sailorlee(lizeyi)
@email : chrislistudy@163.com
-------------------------------------------------
@FileName: company.py
@Software: PyCharm
"""
class Company(object):
"""
魔法函数是__xxx__
优先使用迭代器、然后使用getitem这个方法;
迭代... |
a5bb9daafa50593ba2e94ee0cfa5c721fcecdd5e | MaryamNajafian/Tea_oop_review | /encapsulation_1.py | 714 | 3.6875 | 4 | class MyClass:
var = 10
def print_val(self):
print("Hi")
#ENCAPSULATION: to insure integrity of the data going in and reject any data that isn't working
def set_val(self,val):
#To ensure the value in the val is always an integer
try:
val = int(val)
except Val... |
7551903b79e96a66d315945f71dfec15bf8a6604 | MaryamNajafian/Tea_oop_review | /object_serialization_yaml.py | 1,555 | 3.859375 | 4 | """
Serialization means persist storage to disk
storing data between ex
Relational storage writes data to tables
Object-based storage stores objects as they are used in code (Object databases)
Object-relational mappings can mediate between the two
YAML serializes python objects like Pickle and JSON: sudo pip install py... |
9903925e4fd3178eca31c5486883a24a82817db1 | MaryamNajafian/Tea_oop_review | /polymorphism_1.py | 686 | 3.96875 | 4 | class Animal:
def __init__(self, name):
self.name = name
def eat(self, food):
print (f"{self.name} is eating {food}")
class Dog(Animal):
def fetch(self, item):
print(f"{self.name} goes after the {item}")
def show_affection(self):
print(f"{self.name} wags tail")
class Ca... |
b16d5613be5a483877d451567c5a77bfe1ca3498 | NikilNair/Homework-7 | /leapyear.py | 363 | 3.90625 | 4 | def program(val):
if val % 4 != 0:
return "This is not a leap year"
elif val % 4 == 0 and val % 100 != 0:
return "This is a leap year"
elif val % 4 == 0 and val % 100 == 0 and val % 400 == 0:
return "This is a leap year"
elif val % 4 == 0 and val % 100 == 0 and val % 400 != 0:
... |
4a003fa8363bfa53293861f5383bd1b7f47ac2f6 | ahtif/Big-Data-Module | /Lab7/exploreIncome.py | 2,595 | 3.8125 | 4 | def read_income(fileName = "Adult_Census_Income.csv"):
## Load the data
import pandas as pd
return pd.read_csv(fileName)
def clean_income(df):
## Remove rows with missing values
df.dropna(axis = 0, inplace = True)
## Drop specific rows
## Drop rows with ? in column 'workclass'
for i ... |
73fac159605df8b23361bbdf0d6b36dd9e6d31e1 | Karamba278/DZP1 | /DZP6/65Stationery.py | 1,095 | 3.84375 | 4 | class Stationery:
title = 1
def draw(self):
print(f'Запуск отрисовки №{Stationery.title} с неизвестным инструментом')
class Pen(Stationery):
def draw(self, ins):
print(f'Запуск отрисовки №{Stationery.title} при помощи {ins}')
class Pencil(Stationery):
def draw(self, ins):
prin... |
9e637d7773cba966549c19ff88bda8eb1c89fcc0 | dsocaciu/Projects | /Finance/Term Structure/Swaption.py | 1,852 | 3.5625 | 4 | #swap
from copy import deepcopy
level = 5
shortrate = [[0 for i in range(j+1)] for j in range(level+1)]
rate_root = 0.06
shortrate[0][0] = rate_root
u = 1.25
d = .9
q = .5
one_minus_q = .5
for i in range(0,level):
for j in range(0,i+1):
#print(round(shortrate[i-1][j]*down,5))
#print(str(i) + " " + str(j)... |
456941fe1cf15880221648e4909a2f0811d770b4 | gonced8/EDEN | /Class_Being.py | 3,825 | 4.09375 | 4 | #Project EDEN 13/12/2016 João Bernardino
from random import randint
from Class_World import *
from Class_Population import *
from prob import *
from color import *
from shape_generator import *
from Class_Food import *
class Being(object):
"""This class contains all the information that a being require... |
718d4def46be45b880b51fee17239dfe5d0316bd | islandhuynh/Blackjack | /main.py | 2,370 | 3.921875 | 4 | import random
from os import system
logo = """
.------. _ _ _ _ _
|A_ _ |. | | | | | | (_) | |
|( \/ ).-----. | |__ | | __ _ ___| | ___ __ _ ___| | __
| \ /|K /\ | | '_ \| |/ _` |/ __| |/ / |/ _` |/ __| |/ /
| \/ | / \ | |... |
4fcf4d2382a0222c93bcd328383399ea292ea031 | isrishtisingh/python-codes | /URI-manipulation/uri_manipulation.py | 1,173 | 4.125 | 4 | # code using the uriModule
# the module contains 2 functions: uriManipulation & uriManipulation2
import uriModule
# choice variable is for choosing which function to use for manipulating the URL/URI
choice = -1
try:
choice = int(input(" \n Enter 1 to parse given URL/URIs \n Enter 2 to enter your own URI/U... |
ba0f0e2c027b38c36e3a2c2f2ea4c2247617df66 | jonwang1026/WebScraping-Tool | /Web Scrape/BST.py | 3,433 | 3.765625 | 4 | class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.left_child = None
self.right_child = None
class BinarySearchTree:
class NotFoundError(Exception):
pass
class EmptyTreeError(Exception):
pass
def __init__(self):
self._root = None
... |
88510ab5208dbfda2c46fe0f767076d6128ab28f | swiffo/Tic-Tac-Toe | /players.py | 8,009 | 4.25 | 4 | """
Classes for Tic-Tac-Toe players.
See comments at tictactoe.py for what a player class must implement and satisfy.
Classes available:
- RandomPlayer: Makes random and possibly illegal moves. This player is blind
to the board.
- HumanPlayer: Does not make moves on its own but requests input from the
user f... |
98732e1ae03db951b7a43527dfd2b2f8bdb316d0 | huynle/python-skeleton-1 | /checkout/transaction.py | 1,477 | 4.03125 | 4 | from .purchase import Purchase
class Transaction(object):
'''
Represents a single trip to the checkout, encapsulating some
current pricing rules.
'''
def __init__(self, rules):
self.rules = rules
'''Pricing rules for this transaction.'''
self.purchases = {}
'''dic... |
71fb14524cda7c95c69c039a904b66d57b21f512 | Kevin-McGonigle/spoileralert | /code/front-end/utils/file_cleaners/episodes_cleaner.py | 693 | 3.796875 | 4 | # This program takes a text file and removes duplicates, used to clean characters text file so that
# Used to clean characters text file so that it can be used to classify text to "related to GoT" or "not related to GoT"
# In this case I am using files that have already been converted from JSON to text format
to_writ... |
52115f6238a8074e59d12f9b284519f610451a78 | Kevin-McGonigle/spoileralert | /code/back-end/classification.py | 3,254 | 3.65625 | 4 | # Code taken from datacamp under "natural language processing fundamentals in python"
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import metrics
from sklearn.naive_bayes import... |
9775f3d0e2e1175d073d958105d290b25b55218b | Choiseokjoon/HelloPython | /CH03/EX01.py | 445 | 3.75 | 4 | first = int(input('정수를 입력'))
second = int(input('정수를 입력'))
sum = first+second
sub = first-second
mult = first*second
div = first/second
div_num = first//second
remainder = first%second
print(first,"+", second, "=" , sum)
print(first,'-', second, '=', sub)
print(first,'*', second, '=', mult)
print(first,'... |
c65930180a66d8ee69672c507e23b64d2e3efa5d | Choiseokjoon/HelloPython | /CH05/PCH05EX07.py | 619 | 3.546875 | 4 | user_input = int(input("숫자를 입력하세요(10~99)"))
user_s = str(user_input)
import random
lotto_num = random.randint(10,99)
lotto_s = str(lotto_num)
print(lotto_num)
if lotto_num == user_input:
print("100만원 !!오 이런 어서 돈을 챙겨 이 나라를 떠나세요")
elif (user_s[0] == lotto_s[0]) or (user_s[0] == lotto_s[1])... |
b1c8edc10465e09f5824f4b439f23c3c3ccf40f0 | Choiseokjoon/HelloPython | /CH07/FuncEX02 - 원 삼각형 사각형.py | 593 | 4.0625 | 4 | def circle_area():
area = radius**2 * 3.14
return area
def rect_area(side, height=50):
area = side*height
return area
def tri_area(side,height):
area = side * height / 2
return area
#radius = int(input("반지름:"))
#area0 = circle_area()
#print("원의 면적:",area0)
area0 = circle_ar... |
51ec9fdd3250ba93459039fc6ff9cc6deee821ca | Choiseokjoon/HelloPython | /CH06/팩토리얼.py | 160 | 3.625 | 4 | fact = int(input("원하는 팩토리얼을 입력하세요"))
result = 1
for i in range(1,fact+1):
result = result * i
print("결과" ,"=", result)
|
cbe66bf27b0f90dfcc1072c5e416467af767dc0c | ThreeSR/Algorithm-Toolbox | /BinarySearch_Algorithm.py | 751 | 3.953125 | 4 | # Reference: Grokking Algorithms: An illustrated guide for programmers and other curious people
# Aditya Bhargava
def bin_search(data,element):
l = 0
r = len(data) - 1
while(l<=r):
mid = (l+r) // 2
if (element == data[mid]):
return mid
if (element > data[mid]):
... |
0c432ce4e65a94f847ceda8fda5a1b45edc29666 | sabin-c/PracticeProj | /pyFiles/heapsOfFun.py | 1,476 | 3.671875 | 4 | import heapq
class myHeapThingy:
def __init__(self):
self.h = []
heapq.heapify(self.h)
def addItem(h, intVal):
heapq.heappush(h, int(intVal))
def customPopulate(h):
heapq.heappush(h, 1)
heapq.heappush(h, 3)
heapq.heappush(h, 2)
heapq.heappush(h, 0)
heapq.heappush(h, 5)
... |
9c531f122153f4a8474aea8e956babe37b7adf7c | mayank-17/Practice-Programs | /Python/pAssignment1.py | 274 | 4.03125 | 4 | def reverse(num):
remainder, reverseOfNumber = 0,0
while(num > 0):
remainder = num % 10
num = num // 10
reverseOfNumber = reverseOfNumber * 10 + remainder
return reverseOfNumber
num = int(input())
print(reverse(num))
|
f8b5ef1fdbdc80a545af43cc5b40e8e7cec0ddb9 | mayank-17/Practice-Programs | /Python/summer-lesson.py | 430 | 3.515625 | 4 | #!/bin/python3
import sys
def howManyStudents(m, c):
l=[]
n=[]
for i in range(m):
l.append(i)
for i in l:
n.append(c.count(i))
return n
if __name__ == "__main__":
n, m = input().strip().split(' ')
n, m = [int(n), int(m)]
c = list(map(int, ... |
c496f34e165b76aebe913a15569f4accab625a8e | mayank-17/Practice-Programs | /Python/1.py | 2,515 | 3.859375 | 4 | # """import math
# # Complete the connectedCell function below.
# #def connectedCell(matrix):
# def connectedCell(matrix):
# # Complete this function
# result_list = []
# n,m = len(matrix),len(matrix[0])
# for i in range(0,n):
# for j in range(0,m):
# if matrix[i][j] == 1:
... |
00f05bdaf2bac550cb4453ff773b7fd663fdc4af | knliao-southernco/substation_readings_manager | /substation_readings_manager/utils/date_functions.py | 2,149 | 3.796875 | 4 | from datetime import datetime, timedelta, date
from dateutil.relativedelta import relativedelta
import calendar
import pyodbc
from typing import Dict, List, Tuple
def get_last_month_date() -> date:
""" This function returns the date one month ago. This is for get_date_range_one_month
which then takes the firs... |
ddb5e99ccdf1c29b5bcab81628b7895b635a6e3d | MetaGeoKid/techdegree-project-3 | /phrasehunter/phrase.py | 1,683 | 3.734375 | 4 | class Phrase:
def __init__(self, phrase):
self.phrase = phrase
self.phrase = self.phrase.lower()
self.blank_list = []
#Need to return the phrase with the _ and the letters guessed correctly
def display(self, guess):
if guess == None:
for i in self.ph... |
89ea463ab59b1aa03b14db54ec8d86a8a4168fcf | iriabc/python_exercises | /exercise3.py | 2,082 | 4.46875 | 4 | from collections import deque
def minimum_route_to_treasure(start, the_map):
"""
Calculates the minimum route to one of the treasures for a given map.
The route starts from one of the S points and can move one block up,
down, left or right at a time.
Parameters
----------
the_map: list of... |
a4ea2d631b5d560fb9a1c07095636b5ec6706a73 | ChenyangSong315/Project | /Gradient descent/Gradient descent .py | 16,900 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
print("Function Number:")
print("Sphere: 1")
print("Rosenbrock: 2")
print("Camel: 3")
Function = input("Please type the Function Number:")
Function = float(Function)
# binary search used to find the initial st... |
14eb69206f4d8c741abf655d65a7ed6d1123278c | Lodosss/Umvelt | /argv.py | 845 | 3.796875 | 4 | import sys
# Class
class user():
def __init__(self):
self.name = input("Your name?")
self.password = input("Enter your password")
def print(self):
print("Name: " + self.name)
print("password: " + self.password)
class admin(user):
def __init__(self):
u... |
32b585f6955954c75ac4c0108ec1adc8f65d81c8 | srijib/rideshare-2 | /app/geotest.py | 860 | 3.75 | 4 | import urllib
def geocode(address):
# This function queries the Google Maps API geocoder with an
# address. It gets back a csv file, which it then parses and
# returns a string with the longitude and latitude of the address.
# This isn't an actual maps key, you'll have to get one yourself.
# Sign up for one here... |
aa31f4a1a4a4b68bd708b77a58939f0012e99d31 | jesusvita/PythonPractice | /fantasyInventory.py | 1,125 | 3.84375 | 4 | stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
#displays a dictionay
def displayInventory(inventory):
print("Inventory: ")
itemTotal = 0
for k, v in inventory.items():
print(k + ' : ' + str(v))
... |
eee57e8cc250f859a42b8a103b71d369953a79d1 | rproque/reference_guide | /programming/python/file_input_output.py | 519 | 3.703125 | 4 | #!/usr/local/bin/python3
#MACOSX
# Description: Read a file and write to another file line by line
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--source_file')
parser.add_argument('-d', '--destination_file')
args = parser.parse_args()
source_file = args.source_file
destination_file = ... |
0acfa44ec4fe8ec52a70e6f5a0e2695ab56e5cd0 | sunschong/wallbreakers | /week2/sort-characters-by-frequency.py | 387 | 3.59375 | 4 | import collections
class Solution:
def frequencySort(self, s: str) -> str:
c = collections.Counter(s)
result = ''
for s in c.most_common():
if s[1] > 1:
result += s[0] * s[1]
else:
break
for s in sorted([x for x... |
566c6174353280de333c951ef0c971a99f16eb15 | amitagrawal08/Enabling-HR-with-Machine-Learning | /test1.py | 5,424 | 3.640625 | 4 | import tkinter as tk # also import the themed tkinter for good looking widgets (not obligatory)
from tkinter import *
class Widget:
def __init__(self):
window = tk.Tk()
window.title("Employee Attrition")
window.resizable(0, 0) # prohibit resizing the window
#window.resizable... |
e89069835ee85ea3bd36186cbcbbc0e24158189f | sunilrana4252/python1 | /test3.py | 157 | 3.546875 | 4 | s=input("enter a sentence")
a=s.split()
d={}
for i in a:
d[i]=d.get(i,0)+1
# print(d)
for k,v in d.items():
print("{} occurs {} times ".format(k,v))
|
5edcdacba6c3394f4f6fc975ed6e1dddc9ea43ff | LDSSA/batch4-students | /S01 - Bootcamp and Binary Classification/SLU02 - Subsetting Data in Pandas/utils.py | 791 | 3.921875 | 4 | import re
import numpy as np
def duration_to_int(duration):
"""
Computes integer duration of string if format corresponds to Xmin
Args:
str: the input duration string
Returns:
int: number of corresponding minutes
"""
match = re.match(r'(\d+ ?)(?=min)', duration)
if matc... |
2d9e8f90b9bb67762e8a1d94c5974419fa798dcf | JPchico/APyInSky | /src/SK_topology.py | 5,768 | 3.53125 | 4 | def solid_angle(A,B,C):
""" Calculation of the solid angle between 3 spins that form a triangle.
Args
----------
- A,B,C : (float [3] array) three 3D vectors
Returns
----------
- angle: solid angle between the 3 vectors in the vertices of a triangle
Authors
----------
Jon... |
6a2ba153a1effa85d897a799c26be81518782edd | asamadgithub/Machine_Deep_Learning | /part_2__Regression/section_4__Simple_Linear_Regression/A_Samad/simple_linear_template.py | 1,546 | 4 | 4 | # Data Preprocessing Template
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Data.csv')
# change the Categorical variables,
# =====================================================================================
# st... |
284bfb229acd5c1e11099d2f2a22a695f87cfc17 | vvklr/PYTHON | /tut3.py | 212 | 4.03125 | 4 | a = 1
b = 0
print("Enter numbers to be added")
print("Enter 0 to quit")
while a!=0:
print('currentsum is :', b)
a= float(input('number ?'))
a= float(a)
b+=a
print ("total sum is :",b) |
a3c232a6c220ad1a72284e764c9e70f19fc672b8 | NoName3755/basic-calculator | /calculator.py | 1,108 | 4.21875 | 4 | calculate = True
while calculate:
try:
x = int(input("Enter your first number: "))
y = int(input("Enter your second number: "))
except(ValueError):
print("not an integer")
else:
o = input("enter your operator in words :")
if o == "addition" or o == "+":
... |
35b81820ee7621f682f3c553cf210ac726c14611 | RHEA211/Python | /operators.py | 253 | 3.96875 | 4 | a=input("Enter the value of a- ")
b=input("Enter the value of b- ")
c=input("Enter the value of c- ")
if (a>b and a>c):
print("A is the greatest")
elif(b>c and b>a):
print("B is the greatest")
else:
print("C is the greatest")
|
16b006c12a0477c9a8270e1cc01d7a92de15fe94 | marieyalap/Coursera-Stanford-ML-Python | /ex3/lrCostFunction.py | 1,912 | 3.65625 | 4 | #from ex2.costFunctionReg import costFunctionReg
from numpy import log, dot
from sigmoid import sigmoid
from numpy import e #
import numpy as np
"""def sigmoid(z):
g= 1./(1.+e**(-z))
# ====================== YOUR CODE HERE ======================
# Instructions: Compute the sigmoid of each value of z (z can be a... |
9b46618d76e01320e58a38e63209390d6c87d1aa | canjieChen/LeetCode_for_fun | /he-wei-sde-liang-ge-shu-zi-lcof.py | 1,154 | 3.609375 | 4 | # coding=utf-8
"""面试题57. 和为s的两个数字
输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[2,7] 或者 [7,2]
示例 2:
输入:nums = [10,26,30,31,47,60], target = 40
输出:[10,30] 或者 [30,10]
限制:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^6
"""
class Solution(object):
d... |
8a2f7a77b5a93ae6cca88c17287eae8ceb6103b0 | canjieChen/LeetCode_for_fun | /happy-number.py | 1,318 | 3.640625 | 4 | # coding=utf-8
"""
编写一个算法来判断一个数是不是“快乐数”。
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
示例:
输入: 19
输出: true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
"""
from math import pow
class Solution(object):
def isHappy(self, n):
"""
... |
2c83f6a29dddee865c7bee0a12b52933a577a62a | canjieChen/LeetCode_for_fun | /rectangle-overlap.py | 1,469 | 3.84375 | 4 | # coding=utf-8
"""
矩形以列表 [x1, y1, x2, y2] 的形式表示,其中 (x1, y1) 为左下角的坐标,(x2, y2) 是右上角的坐标。
如果相交的面积为正,则称两矩形重叠。需要明确的是,只在角或边接触的两个矩形不构成重叠。
给出两个矩形,判断它们是否重叠并返回结果。
示例 1:
输入:rec1 = [0,0,2,2], rec2 = [1,1,3,3]
输出:true
示例 2:
输入:rec1 = [0,0,1,1], rec2 = [1,0,2,1]
输出:false
说明:
两个矩形 rec1 和 rec2 都以含有四个整数的列表的形式给出。
矩形中的所有坐标都处于 -10^... |
c19aa554a05f2926cfd9c449f794f13650f6d1c6 | sangural16/Data-Science | /Program 2: More Pandas.py | 12,979 | 3.703125 | 4 | Question 1 (20%)
Load the energy data from the file Energy Indicators.xls, which is a list of indicators of energy supply and renewable electricity production from the United Nations for the year 2013, and should be put into a DataFrame with the variable name of energy.
Keep in mind that this is an Excel file, and not... |
c79c3ef64eb8080ff3563b854f5740a51c4100bd | christianreotutar/Programming-Challenges | /ProjectEuler/8/largestproduct.py | 473 | 3.703125 | 4 | import fileinput
numbers = []
for line in fileinput.input():
line = line[:-1]
linesplit = list(line)
for num in linesplit:
x = int(num)
numbers.append(x)
greatestProduct = 0
numAdjacentDigits = 13
for i in range(len(numbers) - numAdjacentDigits):
currentProduct = 1
for j in range... |
6603519e0959ed2e96ed28b96b674a77f790f8df | Doderok/pyton_3 | /pyton_3.1.py | 119 | 3.828125 | 4 | a=int(input("введите число \n"))
if a%2==0:
print("чётное")
else:
print("нечётное")
|
19d10ffc36a71b8e662857b9f83cbdecdb47114e | TnCodemaniac/Pycharmed | /hjjj.py | 567 | 4.125 | 4 |
import turtle
num_str = input("Enter the side number of the shape you want to draw: ")
if num_str.isdigit():
s= int(num_str)
angle = 180 - 180*(10-2)/10
turtle.up
x = 0
y = 0
turtle.setpos(x,y)
numshapes = 8
for x in range(numshapes):
turtle.color("red")
x += 5
y += 5
turtle.forward(x)
tur... |
e4623f1f3399b37ab3d6b3b070d37540746c07c8 | nocturnaltortoise/advent_of_code2017 | /day3/problem1.py | 1,140 | 3.515625 | 4 | import math
input_position = 368078
# i = input_position
# lower_odd_square = None
# while not lower_odd_square and i > 1:
# if math.sqrt(i) % 2 == 1:
# lower_odd_square = i
# i -= 1
#
# i = input_position
# upper_even_square = None
# while not upper_even_square:
# if math.sqrt(i) % 2 == 0:
# ... |
179ac78bc7d4d378da4214e705cdcc3fbe477e89 | amlsf/HB_Exercise09_recursion | /recursion.py | 7,718 | 4.15625 | 4 |
"""
Exercise 9: Recursion
---------------------
The Evil Wizard Malloc has attacked you and taken away your ability
to use loops! The only way you can defeat him is by fighting back
using the power of recursion!
Below are function stubs for a variety of functions that are able
to be solved recursively. For this ex... |
febb13d196080a604a1a99a22dc0e97df7730a17 | TiZxGaming/isn | /projet.py | 959 | 3.5625 | 4 | from tkinter import*
def cercle(can):
item=can.create_oval(0,0,120,120,fill="light blue",outline="dark blue")
liste_cercle.append(item)
def carre(can):
item=can.create_rectangle(0,0,120,120,fill="red",outline="pink")
def polygone(can):
can.create_polygon(0,0,250,250,500,500,fill="gold",outline="black")
def ... |
3c906c1ec7c01bdeefab11960dab5ec8dc44725c | NicolasHubs/MML-regression | /runtimeXText/oldmml/results/linear_training/result.py | 1,055 | 3.796875 | 4 | #!/usr/bin/env python2
#Importing python modules
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import linear_model
from sklearn.metrics import mean_squared_error
df = pd.read_csv("../BostonHousing.csv", index_col=0)
# Spliting dataset between features (X) and label (y)
col_inde... |
653c0e75c90f2f607eb46df5a885b47cbbd8d107 | Prolgu/PyExamples | /Diccionario-For_menu.py | 1,605 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Diccionario-For_menu.py
#
#
#
import os
salir = False
dic={'1': '0', '2': '0', '3': '0', '4': '0'}#defino mi diccionario
def menu(): #mi memu principal
os.system('clear')
print("Esto parece un menu:")
print("\t1 - Ingresar val... |
f4c1b3a78ed2b6335e30f3d7770462f1a06e19a4 | Prolgu/PyExamples | /EstadisTxt.py | 1,091 | 3.59375 | 4 | #!/usr/bin/env python
#-*-coding: utf-8 -*-
import os
# from tabulate import tabulate
def count_char(txt,char):
count=0
for c in txt:
if c == char:
count += 1
return count
os.system('clear')
f=input(" --> ")
lineas= 0
with open(f, 'r') as file:
for line in file:
if line ... |
9054628d46bc9d1ad59fb41eead6b15b17682c72 | JiangHanChao/NetworkMotifDiscoveryAlgo | /comofinder/Algorithm.py | 1,249 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# if array doesn't contain the node, it will insert the node into the array and return false, else return true
def Binarysort(array, node):
low = 0
high = len(array) - 1
while low <= high:
mid = int((low + high)/2)
if node < array[mid... |
4add9584953d81aba05437f1d56d036884f0481c | Make-School-CS-2-1/CS-2.1-Advanced-Trees-and-Sorting-Algorithms | /Code/sorting_recursive.py | 4,566 | 4.28125 | 4 | #!python
from sorting_iterative import is_sorted, bubble_sort, selection_sort, insertion_sort
def merge(items1, items2):
"""Merge given lists of items, each assumed to already be in sorted order,
and return a new list containing all items in sorted order.
TODO: Running time: ??? Why and under what conditi... |
f6467fba03fd1bc0c8d67966f354112bd9cf5e66 | mmjiang91/leetcode | /5.最长回文子串.py | 937 | 3.578125 | 4 | #
# @lc app=leetcode.cn id=5 lang=python3
#
# [5] 最长回文子串
#
# @lc code=start
class Solution:
def longestPalindrome(self, s):
ori_s = s
s = s.lower()
count = len(s)
curLongStr = ''
for i in range(count):
j = i - 1
k = i + 1
l = 1
... |
38735a35d57dcb8099bc3fb97cd48f9129da82c0 | DanielSMS98/calculadora_grafica | /calculetion.py | 3,538 | 3.734375 | 4 | from tkinter import *
#Constantes
ventana = Tk()
ventana.title("Calculadora")
i = 0
#Entry windowns
e_text = Entry(ventana, font=("Calibri 20"))
e_text.grid(row = 0, column = 0, columnspan = 4, padx = 5, pady = 5)
#funciones
def click_boton(valor):
global i
e_text.insert(i, valor)
i += 1
return
def ... |
978e190bc3222885e0edba82f90a9d06c1f7e55a | Caldass/rental_properties | /heroku_app/example/example.py | 877 | 3.5 | 4 | import pandas as pd
import requests
import json
#prediction request url
url = 'https://rental-properties.herokuapp.com/predict'
#headers
headers = {'Content-type': 'application/json'}
#input example
input_df = pd.DataFrame({'property_type': ['apartamento'], 'address' : ['Avenida Boa Viagem, 5822 - Boa Viagem, Recife... |
568742690b82913b1f68ad4171824b94f181fe2c | nembangallen/Python-Assignments | /Functions/qn2.py | 148 | 3.875 | 4 | """
2. Write a Python function to sum all the numbers in a list.
"""
def sum_all(my_list):
return sum(my_list)
print(sum_all([1, 2, 3, 4]))
|
2d5a337a4cef68a85705c164d5dcdfbd4edb5e17 | nembangallen/Python-Assignments | /Functions/qn10.py | 384 | 4.15625 | 4 | """
10. Write a Python program to print the even numbers from a given list.
Sample List : [1, 2, 3, 4, 5, 6, 7, 8, 9]
Expected Result : [2, 4, 6, 8]
"""
def get_even(my_list):
even_list = []
for item in my_list:
if (item % 2 == 0):
even_list.append(item)
else:
pass
... |
8a872760535ef1b17100bdd9faee4ff6609c1b8d | nembangallen/Python-Assignments | /Functions/qn13.py | 395 | 4.21875 | 4 | """
13. Write a Python program to sort a list of tuples using Lambda.
"""
def sort_tuple(total_student):
print('Original List of tuples: ')
print(total_student)
total_student.sort(key=lambda x: x[1])
print('\nSorted:')
print(total_student)
total_student = [('Class I', 60), ('Class II', 53),
... |
040902675356f5d842d290c5b0570546bc83c9cb | nembangallen/Python-Assignments | /Functions/qn8.py | 387 | 4.28125 | 4 | """
8. Write a Python function that takes a list and returns a new list with unique
elements of the first list.
Sample List : [1,2,3,3,3,3,4,5]
Unique List : [1, 2, 3, 4, 5]
"""
def unique_list(my_list):
unique_list = []
for x in my_list:
if x not in unique_list:
unique_list.append(x)
... |
50d434b7a29209b480bd3cee1cb8553a73cd9c72 | colinbazzano/grokking-algorithms | /test.py | 278 | 3.84375 | 4 | a = 43
b = "23"
print(type(a*b))
l1 = [1, 2, 3]
l2 = [3, 4, 5]
l1.extend(l2)
combined = list(set(l1))
print(combined)
def reverse(s):
if len(s) == 0:
return s
else:
return reverse(s[1:]) + s[0]
word1 = "Bike"
print(reverse(word1))
print(word1)
|
9887258c26429d97e36e6f0d75bdf99820d86be3 | anshulsharma1011/DataStructures | /ds/linkedList/insertSorted.py | 976 | 4.09375 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.point = 0
def printList(self):
currentNode = self.head
while currentNode is not None:
print(currentNode.data, end... |
31e5850e3643f0586f5255635c2b65d5b0f31da1 | anshulsharma1011/DataStructures | /ds/linkedList/deletion.py | 3,226 | 3.9375 | 4 | """
1. Delete Node with given Data
2. POP operation
3. Delete Complete List
4. Delete every N nodes in a linked list after skipping M nodes
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.p... |
41c4d8704030c93b8be43125559d86245b35cf35 | vs3kulic/python-oxford-eureka | /Course1/4-1-function.py | 183 | 3.703125 | 4 | def greeting():
userName = input("Enter your username: ")
print("Hey",userName,", fam!")
big = max(userName)
print("The biggest letter in your name is: ", big)
greeting()
quit() |
09697102abaf1d1559ef67b1097eed73bce69643 | vs3kulic/python-oxford-eureka | /Course3/13-5-parse-JSON-SUM-comment-count.py | 569 | 3.515625 | 4 | import json
import urllib, urllib.request
#url = 'http://py4e-data.dr-chuck.net/comments_1260893.json'
#passing url as parameter vs prompt as requested in assignment
url = 'http://py4e-data.dr-chuck.net/comments_1260893.json'
uh = urllib.request.urlopen(url)
#read the JSON data from that URL using urllib
data = u... |
35deadf2bbd3dca0ab2820219e4729eaba646d82 | swaroopbharaskar/python-notes | /loop.py | 271 | 4.0625 | 4 | i=int(input("enter start number"))
n=int(input("enter end number"))
print("even numbers are:")
num=0
cnt=0
while (i<=n):
num=num+1
if i%2==0:
print(i,end=' ')
cnt=cnt+1
i=i+1
print("/n iterations",num)
print("/ncount of even numbers:" ,cnt) |
8d35276b3c1ae349be7af3b42b9e116934338d5b | swaroopbharaskar/python-notes | /sum.py | 47 | 3.546875 | 4 | a=10
b=20
sum=a+b
print("the addition is:",a+b) |
dc96bea9a55bdadd86727765ca8ef0a568183f82 | swaroopbharaskar/python-notes | /power.py | 118 | 4 | 4 | print("Enter the Total Number of Terms: ")
tot = int(input())
for i in range(tot):
print("2^", i, " is ", 2 ** i) |
3676ccf3a561e398c11a113b0e0cfc6df17afe89 | swaroopbharaskar/python-notes | /codepps.py | 273 | 4.0625 | 4 | print("Hello World")
print(3)
print("the addition is=",3+5)
print("the substraction is=",3-5)
print("the multiplication is=",3*5)
print("the division is=",3/5)
print("the floor divion is=",3//5)
print("the remender is=",3%5)
a=10
b=20
sum=a+b
print("the addition is:",a+b) |
c8adc78627f853406886103513bad4e0a81cb0d4 | muellerd/advent_of_code20 | /puzzle7/7a.py | 1,291 | 3.578125 | 4 | childToParentBags = {}
def printDictionaryChildren(bagsdict, bag, list):
if bag in bagsdict:
for bg in bagsdict[bag]:
if not bg in list:
list.append(bg)
printDictionaryChildren(bagsdict, bg, list)
print(bag)
with open("C:\\Privat\\advent_of_code20\\puzzle7\\exam... |
8b28927b327b42a749b032c640fe364dae349d26 | chaseeby/python_projects | /tiy_p60.py | 243 | 3.578125 | 4 | # 4.3 counting to 20
values = []
for value in range(1, 21):
values.append(value)
print(values)
million = []
for num in range(1, 1000001):
print(num)
million.append(num)
print(sum(million))
print(min(million))
print(max(million))
|
b6be73359ad3749e9016077aeae73ea3a05e5bc7 | chaseeby/python_projects | /guest_list.py | 257 | 3.890625 | 4 | guest_list = ['Chase', 'Madison', 'Lila']
print(guest_list)
guest_list.remove('Chase')
guest_list.append('Alex')
print(guest_list)
guest_list.insert(1, 'Joan')
print(guest_list)
for name in guest_list:
print(f"{name}, you are welcome to the party")
|
c7eac91012f47782f8c1e1abc1f59892c563504f | zenzee08/labpy03 | /latihan1.py | 205 | 3.53125 | 4 | jumlah = int (input("Masukan Nilai N : "))
import random
jumlah = 5
a = 0
for x in range (jumlah):
i = random.uniform(0.0,0.5)
a+=1
print ('Data ke :',a,'==>', i)
print ("^^^^Selesai^^^^^")
|
9a2e6b0fec4009ca8e193a4415aa53882637a6f9 | huiminwu/SpringSoftDevHW | /ClassWork/0430/hmw.py | 922 | 3.828125 | 4 | #def inc(x):
# return x+1
#f=inc
#print(f(10))
#def adder(a,b):
# return a + b
#
#def caller(c):
# print(c(2,4))
# print(c(3,5))
#
#caller(adder)
#def outer(x):
# def contains(l):
# return x in l
# return contains
#
#contains_15 = outer(15)
#contains_15([1,2,3,4,5])
#contains_15([13,14,15,16,... |
05df3650d229b60185a1b7cd61b69d9db5178b58 | sotrnguy92/udemyPython | /udemy4/pythonDataTypesAndVariables/variablesHomework3.py | 247 | 3.765625 | 4 | num1, num2, num3, num4, num5, num6, num7, num8 = map(int, input("Enter 8 numbers seperated by a space: ").split())
oddSum = num1+num3+num5+num7
evenSum = num2+num4+num6+num8
print("odd index sum: ", oddSum);
print("even index sum: ", evenSum);
|
915eb81a97d795ae0a28adcbb1f8755ce5bb4e9f | sanchopanca/clrs | /python/tests/test_max_subarray.py | 711 | 3.578125 | 4 | import unittest
import max_subarray
class TestMaxSubarray(unittest.TestCase):
def test_max_subarray(self):
a = [1, 2, 3, 4, 5, 6]
i, j, s = max_subarray.find_max_subarray(a)
self.assertEqual(i, 0)
self.assertEqual(j, len(a)-1)
self.assertEqual(s, sum(a))
a = [-1, ... |
c02baca16ac7f5e0c0431d91336f409599d90443 | BlaiseMarvin/pandas-forDataAnalysis | /indexObjects.py | 689 | 3.875 | 4 | #pandas index objects are responsible for holding axis labels and other meta data
import pandas as pd
obj = pd.Series(range(3),index=['a','b','c'])
print(obj)
index=obj.index
print(index)
#Index objects are immutable and cannot be modified by the user
#frame 3
data={
'state':['Ohio','Ohio','Ohio','Nevada','Nev... |
ecedcca7da6cd799acc1bce8c0e2b4361c9652a4 | BlaiseMarvin/pandas-forDataAnalysis | /sortingAndRanking.py | 1,820 | 4.34375 | 4 | #sorting and ranking
# to sort lexicographically, we use the sort_index method which returns a new object
import pandas as pd
import numpy as np
obj=pd.Series(range(4),index=['d','a','b','c'])
print(obj)
print("\n")
print(obj.sort_index()) #this sorts the indices
#with a dataframe, you can sort by index on either ... |
56a905baaaab0829c5de41feb40a32eca8ec1393 | shipd/miniUrl | /miniUrl/encode.py | 1,250 | 3.78125 | 4 | import string
import re
SYMBOLS = string.digits + string.ascii_lowercase + string.ascii_uppercase
SYMBOL_TO_DECIMAL_MAP = dict((symbol, decimal) for (decimal, symbol) in enumerate(SYMBOLS))
BASE = len(SYMBOLS)
OFFSET = 3877
is_encoded = re.compile("[0-9a-zA-Z]+")
def encode(number):
"""
given a positive inte... |
0e215f1e233b8d2c7f7bcb5ef794e16fec9d81bc | fernandalozano/AprendiendoPythonF | /MerariPython/Acumulado.py | 557 | 3.765625 | 4 | # Se declaran las variables
acumulado=int(0)
numero=str("")
# Al colocar true como condición en while, se forma un ciclo
while True:
numero=input("Dame un número entero: ")
if numero=="":
# Si el número es vacío, muestra la situación y sale
print("Vacío. Salida del programa.")
break
else... |
194fecb2a5209cad592e60f98d09563370c470a0 | vandent6/basic-stuff | /practice.py | 714 | 3.96875 | 4 | def sum_elements(elems):
"""
list(int) -> int
sum all elements in list
"""
sum = 0
for elem in elems:
sum += elem
return sum
def multiply_elements(elems):
"""
list(int) -> int
multiply all elements in list
"""
sum = 1
for elem in elems:
sum *= elem
... |
7d44b3978280fed567e2422c24f0d2488c28d89d | vandent6/basic-stuff | /elem_search.py | 893 | 4.15625 | 4 |
def basic_binary_search(item, itemList):
"""
(str, sequence) -> (bool)
Uses binary search to split a list and find if the item is in the list.
Examples:
basic_binary_search(7,[1, 4, 6, 7, 8, 9, 11, 15, 70, 80, 90, 100, 600]) -> True
basic_binary_search(99,[1, 4, 6, 7, 8, 9, 11, 15, 70, 80, 90... |
fd812841985dc3d98087d06fb20f2c05f8a743a9 | Berzok/EFREI | /TP3/exo7.py | 336 | 3.828125 | 4 | #coding: utf-8
import math
def facto(x):
if x == 1:
return x
return x*facto(x-1)
def expo(x, iter):
result = float(1+x)
for i in range(2, iter):
result += (x**i)/facto(i)
return result
x = float(input('Choisissez votre nombre: '))
iter = int(input("Nombre d'itérations: "))
print... |
2817f68fa0dc08ba61921f04a3c4ea5eccc31b38 | ltrii/Intro-Python-I | /src/cal.py | 1,702 | 4.6875 | 5 | # """
# The Python standard library's 'calendar' module allows you to
# render a calendar to your terminal.
# https://docs.python.org/3.6/library/calendar.html
# Write a program that accepts user input of the form
# `calendar.py month [year]`
# and does the following:
# - If the user doesn't specify any input, you... |
89ec3843d38332399ec1c9b64933ffb416cc94b8 | Jabi7/P342 | /Project/RandomWalk/randomWalk.py | 921 | 4.09375 | 4 | ## Library of relevant funtion ##
from math import *
import random
import matplotlib
import matplotlib.pyplot as plt
random.seed(1028)
# funtion for generating the set of coordinates in random walk
def rand_walk(N):
x, y = [0], [0]
for i in range(N):
x.append(x[i] + cos(2*pi*random.random(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.