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 |
|---|---|---|---|---|---|---|
c5b87a3edc367f76c12b0fa2734ee8deafa4b965 | jcbain/fun_side_projects | /unique_digits/unique_digits.py | 1,948 | 4.1875 | 4 | from collections import Counter
def separate_digits(val):
"""
separate the digits of a number in a list of its digits
Parameters
-----
val : int
number to separate out
Returns
-----
list
a list of ints of the digits that make up val
"""
return [int(x) for x in str(... |
e3aa84ec0856e98ffabb93f8972e58880e39ca80 | sbjacobs231/Black_Box_Game | /Board.py | 2,326 | 3.71875 | 4 | # Author: Sky Jacobson
# Date: 8/13/20
# Description: Board class has all methods relating to reading and writing to the board.
class Board:
"""
Class representing the different aspects of the board.
It has methods of retrieving the board and printing the board.
This class will be accessed by the Black... |
802480d75cc45bb911de93e28e8e830b743b4db6 | Mattx2k1/Notes-for-basics | /Basics.py | 2,087 | 4.6875 | 5 | # Hello World
print("Hello World")
print()
# Drawing a shape
# Programming is just giving the computer a set of instructions
print(" /!")
print(" / !")
print(" / !")
print("/___!")
print()
# console is where we have a little window into what our program is doing
# Pyton is looking at these instructions line ... |
cdd823dbe94b600742ba2158e50f516446aba57e | Mattx2k1/Notes-for-basics | /Try Except.py | 1,072 | 4.53125 | 5 | # Try Except
# Catching errors
# Anticipate errors and handle them when they occur. That way errors don't bring our program to a crashing halt
number = int(input("Enter a number: "))
print(number)
# if you enter a non number, it will cause the program to crash. So you need to be able to handle the exceptions
# Try e... |
0896dad37cd3b5d93a60fb30672ccd902fcdc337 | Mattx2k1/Notes-for-basics | /Guessing Game.py | 564 | 4.25 | 4 | # guessing game
# start with the variables
secret_word = "giraffe"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
# use a while loop to continually guess the word until they get it correct
# added in the "and not" condition, and new variables to create a limit on guesses
while guess != secret_wor... |
c291411a49d3b4359018649b8687df61d5ce21bc | Gogapain/Programming | /Practice/03/Phyton/333.py | 340 | 3.78125 | 4 | print ("Введите первое число")
a = int(input())
print ("Введите второе число")
b = int(input())
print ("Сложение")
c = a + b
print(c)
print ("Умножение")
d = a * b
print(d)
print ("Вычитание")
f = a - b
print(f)
print ("Деление")
j = a / b
print(j)
|
8431b32905986952c2270139068ab52b5620e2e8 | asyrul21/recode-live | /gibberish.py | 146 | 3.546875 | 4 |
def factorial(number):
# set a base condition
if(number == 0 or number == 1):
return 1
# call itself
return ?
|
05dbb92432de2d6c6abf4440096b46703959c665 | TrevorJackson1/saoroleplay | /viewmobs.py | 662 | 3.5625 | 4 | import sqlite3
try:
sqliteConnection = sqlite3.connect('mobspawn.db')
cursor = sqliteConnection.cursor()
print("Successfully Connected to SQLite")
sqlite_insert_query = """select * from Location"""
count = cursor.execute(sqlite_insert_query)
sqliteConnection.commit()
print("Rec... |
5284bda9251b8da6fe08e0c44d2721e87738e3ad | samsonwang/ToyPython | /PlayGround/26TicTacToe/draw_pattern.py | 1,813 | 4.34375 | 4 | #! /usr/bin/python3.6
'''
Tic Tac Toe Draw
https://www.practicepython.org/exercise/2015/11/26/27-tic-tac-toe-draw.html
- For this exercise, assume that player 1 (the first player to move) will always be X and player 2 (the second player) will always be O.
- Notice how in the example I gave coordinates for where I wan... |
d513ffbff8feeeb5420c90ad2f1406de501696b0 | samsonwang/ToyPython | /PlayGround/01DiceSimulator/01DiceSimulator.py | 602 | 3.953125 | 4 |
'''
dice simulator
author: Samson Wang
data: 2018-04-16
'''
import random
# 最大最小值
num_min = 1
num_max = 6
is_need_exit = False
while not is_need_exit :
print("==dice simulator==")
print("dice is rolling!\n min=%d, max=%d" % (num_min, num_max))
num_rand = random.randint(num_min, num_max)
print(" rand number", n... |
83b4a6df6bd9e5c2ec00c587a0f72e4877a4f81d | arun-p12/project-euler | /p0001_p0050/p0043.py | 1,226 | 3.6875 | 4 | '''
In 1406357289 (a 0 to 9 pandigital number), 406 (digits 2, 3, and 4) is divisible by 2.
063 (digits 3, 4, and 5) is divisible by 3, 635 (digits 4, 5, 6) is divisible by 5, etc.
The last set, 289 (digits 8, 9, and 10) is divisible by 17.
To find the sum of all 0-9 pandigital numbers with this property.
'''
def subs... |
5521559091299b2af7b6c72fa20cea4dcffe9a03 | arun-p12/project-euler | /p0001_p0050/p0025.py | 1,056 | 4.125 | 4 | '''
In a Fibonacci series 1, 1, 2, 3, 5, 8, ... the first 2-digit number (13) is the 7th term.
Likewise the first 3-digit number (144) is the 12th term.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
'''
def n_digit_fibonacci(number):
digits = 1
fibonacci = [1, 1]
whil... |
154cf1ad66e4d8fab9b523676935b615ef831d3d | arun-p12/project-euler | /p0001_p0050/p0038.py | 2,093 | 4.125 | 4 | '''
192 x 1 = 192 ; 192 x 2 = 384 ; 192 x 3 576
str(192) + str(384) + str(576) = '192384576' which is a 1-9 pandigital number.
What is the largest 1 to 9 pandigital 9-digit number that can be formed as the
concatenated product of an integer with (2, ... , n) digits?
Essentially n > 1 to rule out 918273645 (formed by... |
77f747af457b9369b29af4eeea70e270b1eec04d | arun-p12/project-euler | /p0051_p0100/p0058.py | 1,530 | 3.875 | 4 | '''
Starting from the center, the diagonals are the four corners of a sqaure, and in
crement by 2n.
The center point is a 1x1 square, the next is a 2x2, and so on. Thus, the corners of a 4x4
square would increment by 2x4 = 8, and the diagonals would follow a pattern of
1, 3,5,7,9, 13,17,21,25, 31,37,43,49, ... |
4161a7c9e8861f47152e6c307c4717803824db80 | arun-p12/project-euler | /p0051_p0100/p0097.py | 729 | 3.578125 | 4 | '''
2**6972593 −1 is the first known prime number with over one million digits. Such prime numbers of
the form 2**p - 1 are called Mersenne primes.
What are the last ten digits of 28433(2**7830457)+1 ... a non-Mersenne prime.
'''
def large_non_mersenne_prime(digits=10):
print("last 10 digits = ", ((28433*(2**78304... |
4b2acbf02454ae23294d59f96ed2ea5325fb3b2b | arun-p12/project-euler | /p0051_p0100/p0053.py | 1,255 | 3.71875 | 4 | '''
For values of n <= 100, how many combinations of nCr produces a value greater than 1,000,000
'''
def combinatoric_selection():
def ncr(n, r):
import math
return (math.factorial(n) / (math.factorial(r) * math.factorial(n - r)))
'''
nCr values for a Pascal's triangle ... 1; 1 1; 1 2 1; ... |
a2e760d49f973f472f2de9051e24d9003ac9341c | arun-p12/project-euler | /p0001_p0050/p0046.py | 1,503 | 3.90625 | 4 | '''
The smallest odd composite number that cannot be represented as the sum of a prime
and twice a square. E.g. 9 = 7 + 2(1**2) ; 27 = 19 + 2(2**2)
Originally had maintained the list of 2x^2; and then check if for every i, if
the (odd_composite - i) is in that lis. This logic took about 7s to execute.
Modified logic ... |
4cbef49ee1fd1c6b4a15eae4d2dee12be49475a8 | arun-p12/project-euler | /p0001_p0050/p0017.py | 2,376 | 4.125 | 4 | '''
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then
there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words,
how many letters would be used? Ignore spaces
'''
def number_letter_count(number=1000):
... |
1b7220240760b68c282dadd3f1f68c38e276421c | James-Lee1/Unit_3-03 | /rock_paper_scissors.py | 1,073 | 3.65625 | 4 | # coding: utf-8
import ui
import random
box = ['Rock', 'Paper', 'Scissors']
global user_picked
def rock_paper_scissors_touch_up_inside(sender):
if sender.name == "rock_button":
user_picked = 'Rock'
view['user_pick_label'].text = 'You picked Rock'
elif sender.name == "paper_button":
user_picked = 'Paper... |
98013899a93003177c9962f71beb435dad8d755f | ibrahima99/projet_ap2_ibra | /probleme 1/Probleme2.py | 3,185 | 3.75 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
:mod:`Probleme1` module
:author:Arnaud Kaderi, Elhadj Ibrahima BAH, Aboubakar Siriki DIAKITE
:date: 2019, october
:last revision: 2019, october
"""
from random import*
from Individual1 import*
from math import*
class Problem_interface():
def __init__(self, ... |
343749f699d3ab58b87183db7ff4f7c01194defc | rustamhse/pythonstudy | /second_program.py | 189 | 3.546875 | 4 | A = int(input('Введите A >> '))
B = int(input('Введите B >> '))
for i in range(A, B + 1):
if (i // 1000) == i % 10 and (i // 100) % 10 == (i // 10) % 10:
print(i)
|
923db06933c29ae9f9c526ce5f8289506efebf8f | novdima1/TAU-intro-selenium-1 | /tests/test_search.py | 1,167 | 3.75 | 4 | """
These tests cover DuckDuckGo searches.
Run: F:\Дима\_IT Info\tau-selenium-pytest\tau-intro-selenium-py-1>python -m pytest -n 2
"""
import pytest
from pages.search import DuckDuckGoSearchPage
from pages.result import DuckDuckGoResultPage
# Pytest parametrization — passing multiple data-items to a single test
PHR... |
c891fec31546ed93374bc833e0bb4870c7e3e188 | rmrodge/python_practice | /format_floating_point_in_string.py | 800 | 4.4375 | 4 | # Floating point number is required in programming for generating fractional numbers,
# and sometimes it requires formatting the floating-point number for programming purposes.
# There are many ways to exist in python to format the floating-point number.
# String formatting and string interpolation are used in the f... |
ee8b15b4515267f7742a2f0721f594e721cf7e0c | iOSDevD/EMR_System | /model/Patient.py | 12,580 | 3.96875 | 4 | """
Nikunj Upadhyay
Class: CS 521 - Fall 1
Date: 10/16/2021
Homework Problem # Project
Description of Problem (1-2 sentence summary in your own words):
Patient object which represents columns in the CSV. For example `Patient Id`
is re-presented by attribute `self.__patient_id`.
"""
import copy
from utilities.AppConst... |
66d3bd16816f657948253919015033a89e499f2b | iOSDevD/EMR_System | /utilities/LoginUserValidation.py | 3,544 | 4.3125 | 4 | """
Nikunj Upadhyay
Class: CS 521 - Fall 1
Date: 10/16/2021
Homework Problem # Project
Description of Problem (1-2 sentence summary in your own words):
The program illustrate that it has functions which can be used
to validate the user name and password.
"""
from utilities.AppConstants import LoginConstants
def is_l... |
f7d17b2ecf5cb69aa2aa8d4f4f9042fe8ed3d471 | BuringSky/Breaking-Captchas-with-a-CNN | /utils/cnnhelper.py | 611 | 3.59375 | 4 | import matplotlib.pyplot as plt
import numpy as np
def plotHistory(H, numEpochs):
# plot the training loss and accuracy
plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0, numEpochs), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, numEpochs), H.history["val_loss"], label="val_l... |
6f4ffe18454ea3a2fcda85afde322bdda9f99861 | Lyunchenko/Game_of_Life | /generation.py | 1,757 | 3.546875 | 4 |
class Generation:
def __init__(self, checked_cells, gui, widht, height):
self.widht = widht
self.height = height
self.gui = gui
self.generation = checked_cells
def __eq__(self, other):
if isinstance(other, self.__class__):
return(self.generation == other.generation)
else:
return(False)
def ge... |
c0504a4d9f2c6e6dd501dfc6e20df6d65341d013 | IonutPopovici1992/SentDex | /Python_3_Basics/built-in_functions.py | 420 | 3.59375 | 4 | import math
exampleNumber1 = -5
exampleNumber2 = 5
if abs(exampleNumber1) == exampleNumber2:
print('These are the same.')
# Help
exampleList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(min(exampleList))
print(max(exampleList))
x = 5.123
print(round(x))
x = 5.789
print(round(x))
print(math.floor(x))
print(math.ceil... |
213404dbfd2c60129e1f9d6268c1d1df36ca18bb | pbelko/primenumbers | /prime/prime.py | 540 | 3.859375 | 4 | __author__ = 'tony'
import sys
print(sys.argv)
def main() -> object:
sentence = "Enter in a number to calculate: "
number = int(input(sentence))
calculate_prime(number)
def calculate_prime(a):
if a < 2:
sentence = 'The number { } must be greater than 2.'.format(a)
print(sentence)
... |
1c9dc6ed91a583328aab2cfe887a1d8fce2ea0dc | yashdevilking/Data-Structure-and-Algorithm | /Code Workspace/Algorithms/5.1 HeapSort.py | 2,275 | 4 | 4 | class MaxHeap():
#we receive a list of items
def __init__(self,items = []):
self.heap = [0]
# we create a heap list and store 0 at first Index
# we will not use first Index
for i in items:
# we will store the items received in items[] in heap
self.heap.append(i)
#now we will float... |
f3de6fc8407e822afc5b0d3f3b9224e62aa5d527 | jakesauter/Intro_to_Data_Science_in_Python | /single_files/nearest_coin.py | 1,494 | 3.75 | 4 |
"""
reticulate::repl_python()
"""
"""
--------------------------------------
| . | . | . | . | . | . | . | . | . |
| . | x | . | . | . | . | . | . | . |
| . | . | . | . | o | . | . | . | . |
| . | . | . | . | . | . | . | . | . |
| o | . | . | . | . | . | . | . | . |
| . | . | o | . | . | . | . | . | . |
| . | . | .... |
de66237aad79ee32992daff4259adbbbda6d3323 | Cracktuar/RebirthItemTracker | /game_objects/floor.py | 1,701 | 3.640625 | 4 | import pygame
class Curse:
No_Curse, Blind, Darkness, Lost, Maze, Unknown, Labyrinth, Cursed = range(8)
class Floor(object):
'''
Stolen from item_tracker - used as an easy way to convert floors into
shortened names
'''
__floor_id_to_label = {
"f1": "B1",
"f2": "B2",
... |
1030db41147c9a63694e861c7fea4dcf9da85549 | hnuyx/work | /other/test/002-python/mpi.pyx | 791 | 3.84375 | 4 | #!/usr/bin/env python3
import time #时间模块
# Caculate PI with Taylor series
cpdef double TaylorPi(int k):
cdef double sum = 0.0
cdef int odd = 1
cdef int i = 0
for i in xrange(k):
if odd == 1:
sum += 1.0/(2.0*i+1.0)
odd = 0
else:
sum -= 1.0/(2.0*i+1.0)
... |
49658ba8dcf065cdfeb9dff7b86fa48b703191bc | hnuyx/work | /other/test/002-python/x-properity.py | 176 | 3.578125 | 4 |
class T:
a = 1
b = 2
@property
def c(self):
return self.a * self.b
if __name__ == '__main__':
a = T()
print(a.c)
a.a = 3
print(a.c)
|
9d6df0f9941d77ce9331371bfacb0688efbb442f | jtschoonhoven/ledmatrix | /ledmatrix/utilities/colors.py | 1,459 | 3.890625 | 4 | """Constants for working with colors in the terminal.
https://pypi.org/project/ansicolors/
"""
from typing import NamedTuple, Optional
from colors import color as ansicolor
ColorOrder = NamedTuple(
'ColorOrder',
[('red', int), ('green', int), ('blue', int), ('white', Optional[int])],
)
RGB = ColorOrder(re... |
cb99d7bbb1c4f770ca09a0c5148fb29b7de8a662 | dev1315/Multi-label-Classification-using-NLP | /Final_Toxic_Comment_Classification.py | 17,683 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Toxic Comment Classification
# >Access dataset from [here](https://www.kaggle.com/c/jigsaw-toxic-comment-classification-challenge/data)
# In[1]:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplo... |
eef82d4c537441db718cadba2b8aa98998fe7418 | Jeff-ust/D002-2019 | /L6/connect-4.py | 3,759 | 3.59375 | 4 | def printcell(cells):
print("-" * 29)
for i in range(0, 6):
for j in range(0, 7):
print("| %s " % cells[i][j], end="")
print("|")
print("-" * 29)
cells = [[" "," "," "," "," "," "," "], [" "," "," "," "," "," "," "], \
[" "," "," "," "," "," "," "], [" ... |
b82b3928481d538244ec70a34fecb0b7ed761f3c | Jeff-ust/D002-2019 | /L2/L2Q6v1.py | 1,387 | 4.375 | 4 | #L2 Q6: Banana Guessing game
#Step 1: Import necessary modules
import random
#Step 2: Welcome Message
print('''Welcome to the Banana Guessing Game
Dave hid some bananas. Your task is to find out the number of bananas he hid.''')
#Step 3: Choose a random number between 1-100
n = random.randint(1,100)
print ("s... |
70ca08346178f87b3e7afae3e746481369cba82a | shuhsienhsu/X-Village-DS-Exercise | /bonus3.py | 746 | 4.1875 | 4 | def insertion_sort(list):
for i in range(1, len(list)):
for j in range(i):
j = i - j - 1
if(list[j] > list[j + 1]):
temp = list[j]
list[j] = list[j + 1]
list[j + 1] = temp
else:
break
def bubble_sort(list):
... |
c44b0015fc91eb0dde169cf2de386c7d8b16ddd0 | yash-kedia/Competitve-Coding | /Graphs/trie_in_python.py | 1,614 | 3.96875 | 4 | class node:
def __init__ (self):
self.key = None
self.value = None
self.children = {}
class trie:
def __init__ (self):
self.root = node()
def insert(self,word,value):
currentword = word
currentnode = self.root
while len(currentword)>0:
if... |
6a0bc17deb88782279a2dc66446ff5853a27f21b | kevinychen/code-crunch | /problems/subtract/subtract.py | 152 | 3.515625 | 4 | import fractions
n = input()
nums = []
for i in range(n):
nums.append(input())
u = nums[0]
for z in nums[1:]:
u = fractions.gcd(u, z)
print u
|
b9ad75ed20cc080f6ad33041289f82d8669d4cb5 | rodipm/IA | /falling_ball/utils.py | 1,822 | 3.640625 | 4 | import random
import pygame
from initializer import *
from classes import *
def new_state_after_action(s, act):
rct = None
if act == 2:
if s.rect.right + s.rect.width > windowWidth:
rct = s.rect
else:
rct = pygame.Rect(s.rect.left + s.rect.width, s.rect.top, s.rect.widt... |
93c7334ce86f88739043c5823b28df446df088f6 | junqfisica/SDP | /backend/flaskapp/utils/file_utils.py | 5,952 | 3.75 | 4 | # Util methods to handle files.
import os
import shlex
import shutil
import subprocess as sp
import tarfile
import tempfile
from typing import List
from zipfile import ZipFile
def get_file_extension(file_name: str) -> str:
"""
Get the file extension,
file.jpg returns jpg
file returns ""
... |
fbf0406858a0b3cdb529472d4642b2acea5fa3d2 | shouryacool/StringSlicing.py | /02_ strings Slicing.py | 820 | 4.34375 | 4 | # greeting="Good Morning,"
# name="Harry"
# print(type(name))
# # Concatining Two Strings
# c=greeting+name
# print(c)
name="HarryIsGood"
# Performing Slicing
print(name[0:3])
print(name [:5]) #is Same as [0:4]
print(name [:4]) #is Same as [0:4]
print(name [0:]) #is Same as [0:4]
print(name [-5:-1]) # is ... |
a7e13dc9ed5445badc81418f39e58a168bfd37b8 | AlexanderIvanofff/Python-OOP | /Multidimensional Lists/matrix_shuffling.py | 949 | 3.828125 | 4 | def is_valid(pos, rows, cols):
return 0 <= pos[0] < rows and 0 <= pos[1] < cols
rows, cols = [int(x) for x in input().split()]
matrix = []
for _ in range(rows):
matrix.append([x for x in input().split()])
line = input().split()
while not line[0] == 'END':
if line[0] == 'swap' and len(l... |
e18e0182112fee9e9e303b9a3bb7d3d09b219509 | AlexanderIvanofff/Python-OOP | /Classes and Instances/time.py | 1,379 | 4.0625 | 4 | # Create class Employee. Upon initialization, it should receive id (number), first_name (string),
# last_name (string), salary (number). Create 3 more instance methods:
# - get_full_name() - returns "{first_name} {last_name}"
# - get_annual_salary() - returns the salary for 12 months
# - raise_salary(amount) - increase... |
3d88fc4d3f467d12de6a74adb46bbeee20b013e6 | AlexanderIvanofff/Python-OOP | /Multidimensional Lists/knight_game.py | 1,874 | 3.546875 | 4 | """
Chess is the oldest game, but it is still popular these days. For this task, we will use only one chess piece - the Knight.
The knight moves to the nearest square but not on the same row, column, or diagonal. (This can be thought of as moving
two squares horizontally, then one square vertically, or moving one sq... |
6ec8208d9bcfe684c064577483dcad29b874de27 | AlexanderIvanofff/Python-OOP | /List as Stacks and Queues/reverse_str.py | 194 | 4.09375 | 4 | string = input()
stack = []
for char in string:
stack.append(char)
reversed_str = ""
while len(stack) > 0:
item = stack.pop()
reversed_str += item
print(reversed_str) |
d8f89c6f971a5378300db593da07310ed7dfa31d | AlexanderIvanofff/Python-OOP | /defending classes/programmer.py | 2,311 | 4.375 | 4 | # Create a class called Programmer. Upon initialization it should receive name (string), language (string),
# skills (integer). The class should have two methods:
# - watch_course(course_name, language, skills_earned)
# o If the programmer's language is the equal to the one on the course increase his skills with the... |
7d94fef672a5ab068b48129009d0876e39745452 | panzervi8/practice | /约瑟夫环问题.py | 969 | 3.53125 | 4 | """
《幸运的基督徒》
有15个基督徒和15个非基督徒在海上遇险,为了能让一部分人活下来不得不将其中15个人扔到海里面去,
有个人想了个办法就是大家围成一个圈,由某个人开始从1报数,报到9的人就扔到海里面,他后面的人接着从1开始报数,
报到9的人继续扔到海里面,直到扔掉15个人。由于上帝的保佑,15个基督徒都幸免于难,
问这些人最开始是怎么站的,哪些位置是基督徒哪些位置是非基督徒。
"""
persons = [True] * 30 #定义一个30个人的列表
#counter 记录扔掉的人
#index 是列表的index
#number是报数
counter, index, number = 0, 0, 0
while c... |
6847b974bfa860f4dcec26f502a5b7c6c307e7e8 | learn-co-curriculum/cssi-4.8-subway-functions-lab | /subway_functions.py | 1,870 | 4.625 | 5 | # A subway story
# You hop on the subway at Union Square. As you are waiting for the train you
# take a look at the subway map. The map is about 21 inches wide and 35 inches
# tall. Let's write a function to return the area of the map:
def map_size(width, height):
map_area = width * height
return "The map is %... |
53d5ac88f60a661a68847ca3fcde58e7288d9a85 | elizabeth-dayton/Leet-Code | /Easy Problems/palindromenumber.py | 505 | 3.59375 | 4 | def isPalindrome(x):
# :type x: int
# :rtype: bool
#Try 1 - ran in 44 ms and took 12.9 MB of memory
# if x == 0:
# return True
# x = str(x)
# y = x[::-1]
# y = y.lstrip('0')
# return x == y
#Try 2 - ran in 40 ms and took 12.9 MB of memory
# if x < 0:
... |
d67a8234cc79c9cf02e5268625143dec55dd273a | elizabeth-dayton/Leet-Code | /Easy Problems/twosum.py | 912 | 3.625 | 4 | def twoSum(nums, target):
# :type nums: List[int]
# :type target: int
# :rtype: List[int]
#Try 1 - too slow (5696 ms) and takes up too much memory (13.6 MB)
# for x in range(len(nums)):
# for y in range(len(nums)):
# if nums[x] + nums[y] == t... |
5da2a267ea0fa9785db99ed1598eb2457809f5d0 | jingnie0222/ex_leetcode | /binary_search.py | 1,072 | 3.828125 | 4 | import pysnooper
#@pysnooper.snoop()
#递归方式,传入的数组长度一直在变,所以不能返回正确的下标,返回True或False比较好
def binary_search(lst, val):
if not lst:
return False
mid = (len(lst) - 1) // 2
if val == lst[mid]:
return True
elif val < lst[mid]:
return binary_search(lst[0:mid], val) #注意r... |
5ca8069bc59bfc01c86ad9c67f5792fb4f09e247 | lonewolf2799/Hello-World | /class.py | 1,049 | 3.984375 | 4 | class Vector:
def __init__(self,d):
""" create d-dimensional vector of zeroes"""
self._coords = []
for i in range(d):
l = float(input())
self._coords.append(l)
def __len__(self):
return len(self._coords)
def __getitem__(self,k):
return self._c... |
588f4ba78f0024c2e178b914ff2381f8e2468e7d | gserafim283010/python-520 | /classes/animal.py | 503 | 3.65625 | 4 | #!/usr/bin/python3
class Animal():
def __init__(self, **kwargs):
# def __init__(self, peso=0, idade=0, cor='', nome='', especie=''):
#def __init__(self, *args):
for k in kwargs:
self[k] = kwargs[k]
def __str__(self):
return 'Voce printou o gatinho {0}'.format(self.nome)
... |
18bf2a7be90921ddd8111580e9627ef58b3f6c87 | gserafim283010/python-520 | /classes/humanos.py | 964 | 3.8125 | 4 | class Humano():
def __init__(self, nome, idade, cor, peso):
self.nome = nome
self.idade = idade
self.cor = cor
self.peso = peso
def envelhecer(self):
self.idade += 1
class Homem(Humano):
def __init__(self, nome, idade, cor, peso, veiculo):
# Chama o constr... |
b808f7a662759a214d9b81319b32a648ca6eaa97 | wwkkww1983/LeetCode-1 | /42.接雨水/数学解法.py | 896 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/6/29 14:48
# @Author : lxd
# @File : 数学解法.py
class Solution:
def trap(self, height: list):
if len(height) < 3:
return 0
max_height, S1, S2 = 0, 0, 0
juzhen_area = max(height) * len(height)
zhuzi_area = sum(height)
for i in... |
dd9e8c63606b8e415372e3b880a3cb8a5f220959 | wwkkww1983/LeetCode-1 | /102.二叉树的锯齿形层次遍历/栈方法.py | 893 | 3.5625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def zigzagLevelOrder(self, root):
dp1 = [root,]
dp2 = []
score = []
while dp1 or dp2:
line = ... |
d3fc9921681c489242a1aaae6f56f8251109bd6b | wwkkww1983/LeetCode-1 | /84. 柱状图中最大的矩形/栈方法.py | 1,159 | 3.53125 | 4 | class Solution:
def largestRectangleArea(self, heights):
FILO = []
area = 0
# area列表中初始化一个0, 防止heights为空时area为空
# area = [0, ]
for i in range(len(heights)):
while FILO and heights[i] < heights[FILO[-1]]:
index = FILO.pop()
if FILO:
... |
1c832205ec93dc322ab47ed90c339a9d81441282 | nyu-cds/asn264_assignment3 | /product_spark.py | 590 | 4.1875 | 4 | '''
Aditi Nair
May 7 2017
Assignment 3, Problem 2
This program creates an RDD containing the numbers from 1 to 1000,
and then uses the fold method and mul operator to multiply them all together.
'''
from pyspark import SparkContext
from operator import mul
def main():
#Create instance of SparkContext
sc = Spark... |
dd98e062bdeb4a660ecb8974e170ccaa80bc9f25 | nyu-cds/asn264_assignment3 | /mpi_assignment_2.py | 1,401 | 3.84375 | 4 | '''
Aditi Nair (asn264)
April 13 2017
Assignment 10, Problem 2
In this program there is an arbitrary number of processes.
Process 0 reads a value (val) from the user and verifies that it is an integer less than 100.
Process 0 sends the value to Process 1 which multiplies it by its rank (which is 1).
Process 1 sends... |
8f9fcf819fa462c40c2336cc4e10d3d63adfe334 | zoleikha-mousavipak/pythonPro | /s2_objects_boundMethods.py | 328 | 3.546875 | 4 | class A:
def __init__(self, x):
self.x = x
def get_x(self):
return self.x
class B:
def __init__(self, x):
self.x = x
def get_x(self):
return self.x
a = A(10)
print(a)
print(a.get_x())
print(A)
print(A.get_x(a))
b = B(12)
print(b.get_x())
print(B.get_x(b))
print(B.g... |
17865909ee7bd76bbe9e08d22d06ff1981a48352 | posccis/FlyFood | /FLYFOOD_BRUTE.py | 5,379 | 3.578125 | 4 | import itertools as it #Importando a biblioteca itertools
import time
ini = time.time()
'''__Abrindo e lendo o arquivo de texto com a matriz__'''
with open("rota.txt", "r") as rotas:
rota = rotas.read()
'''__Transformando a matriz do arquivo em uma matriz para o codigo__'''
rota = [x.split() for x in rota.split(... |
3cf484e90822067f388eb3eafb4736bafbe028d9 | hoyeonkim795/solving | /progeammers/프린터.py | 566 | 3.59375 | 4 | from collections import deque
def solution(priorities, location):
answer = 0
arr = [i for i in range(len(priorities))]
queue = deque(arr)
priorities = deque(priorities)
while queue:
a = queue.popleft()
b = priorities.popleft()
for i in range(len(priorities)):
if ... |
38a4004172e95104aadc8cd171d9e94181ceb4b7 | hoyeonkim795/solving | /progeammers/단속카메라.py | 379 | 3.515625 | 4 | def solution(routes):
answer = 0
routes = sorted(routes, key = lambda x: x[1])
print(routes)
last_camera = routes[0][1]
print(last_camera)
for i in range(1,len(routes)):
if last_camera > routes[i][0]:
answer += 1
last_camera = routes[i][1]
return answer
print(so... |
400a48e4f79f4152a583e96d97c8117e369343ed | hoyeonkim795/solving | /linecodingtest/1.py | 1,331 | 3.5625 | 4 | def solution(inputString):
a,b,c,d = 0,0,0,0
result = []
for i in range(len(inputString)):
if inputString[i] == '(' and (a == 0 or a ==2):
a = 1
elif inputString[i] == '{' and (b== 0 or b == 2):
b = 1
elif inputString[i] =='[' and (c == 0 or c == 2) :
... |
70c89a27b9d760536ef586509d4d92f88ce5c5a8 | hoyeonkim795/solving | /swexpert/회전.py | 503 | 3.734375 | 4 | def queue(arr,M):
for _ in range(M):
front = arr[0]
rear = arr[-1]
new_arr = [0]*N
new_arr[-1] = front
for i in range(N-1):
new_arr[i] = arr[i+1]
arr = new_arr
return arr[0]
tc = int(input())
for tc in range(tc):
N,M = map(int,input().split()) ... |
c110b1f9558c93f3f9e2cec7af06ae7b2d0fe2bc | hoyeonkim795/solving | /progeammers/MaxProductOfThree.py | 336 | 3.9375 | 4 | def bubble_sort(arr):
for i in range(0, len(arr)):
for j in range(len(arr)-1, i, -1):
if arr[j-1] > arr[j]:
arr[j-1], arr[j] = arr[j], arr[j-1]
return arr
def solution(A):
A.sort()
a = A[-1]*A[-2]*A[-3]
b= A[0]*A[1]*A[-1]
if a>b:
return a
else:
... |
5d4e014222a74268b16a5f8c9f35992f63e32b7f | JacobStephen9999/Linked-List-2 | /Intersection.py | 1,739 | 3.765625 | 4 | #Brute Force :
#Time Complexity : O(N)
#Space Complexity : O(N)
# 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:... |
e68cc119f736a7a63a84858824a2c512c2a23ea5 | Jtonna/Sprint-Challenge--Hash-BC | /hashtables/ex2/ex2.py | 1,883 | 3.75 | 4 | # Hint: You may not need all of these. Remove the unused functions.
from hashtables import (HashTable,
hash_table_insert,
hash_table_remove,
hash_table_retrieve,
hash_table_resize)
class Ticket:
def __init__(self, s... |
4bdf83247446b49e1a3f063e7d62c114b9c4de13 | jeevakamal/guvi1 | /factorial.py | 83 | 3.515625 | 4 | n=int(input())
factorical=1
while n>1:
factorical*=n
n -= 1
print(factorical)
|
c1e42b7bff83e0b4a95176375f9a4c6d1c86d3f4 | Andrew7-cloud/ParkingGarage | /dictionary_examples.py | 2,922 | 4.09375 | 4 | """ Dictionaries: Unordered, Changeable, Duplicate keys not allowed """
# GENERAL #
# 1 Calcuate Dictionary Length
this_dict = {"lot1": "False", "lot2": "False", "lot3": "False"}
dict_length = len(this_dict)
print(f"GENERAL #1 Calculate Dictionary Length: {dict_length}")
# ACCESING #
# 1 Access value of key using ... |
4e41495c528bcfb17742592d900fb09e6d2bd84f | dansobolev/my_python | /HW4/del_element_list.py | 212 | 3.796875 | 4 | # Упражнение 6.3
names = ['John', 'Paul', 'George', 'Ringo']
list1 = []
for i in range(len(names)):
if names[i] == 'John' or names[i] == 'Paul':
list1.append(names[i])
names = list1
|
2f3eabc6a0dd23aedd8ed61d329ac5429d5c050c | dansobolev/my_python | /HW4/new_list.py | 402 | 3.828125 | 4 | # Упражнение 6.2
from math import sqrt
# На основе цикла for
spisok1 = [2, 4, 9, 16, 25]
spisok2 = []
for i in range(len(spisok1)):
spisok2.append(sqrt(spisok1[i]))
# На основе функции map
spisok = [2, 4, 9, 16, 25]
list1 = list(map(sqrt, spisok))
# В виде генератора списка
a = [sqrt(spisok[i]) for i in range... |
1b0bc967a5688ca315c1a7b4235fdb22d075d1e3 | dansobolev/my_python | /call_tel.py | 561 | 3.5 | 4 | # Упражнение 2.5
code = int(input("Введите код города: "))
per_min = int(input("Введите длительность переговора (в минутах): "))
def call_tell(v1, v2):
if v1 == 343:
print("Ваш звонок стоит",15*v2, "р")
elif v1 == 381:
print("Ваш звонок стоит",18*v2, "р")
elif v1 == 473:
print("Ваш... |
adae8c5b8680d5efddddbe0c47e6aeb26a7b0446 | manishshiwal/guvi | /ex1.py | 1,103 | 3.984375 | 4 | print "hello guys"
print """this is paragraph not a sngh;e lin
this is secong line """
a=10
b=20
print "sum=",a+b
def plus (a,b):
print"funtion sum= a+b"
return a+b
print plus(a,b)
print
print
ten_things="Apples Oranges Crows Telephone Light Sugar"
print "wait there'snot 10 things in that lost, let's fix... |
1175e24869bfd60f46748e147879eb33e16630d1 | manishshiwal/guvi | /eveninterval.py | 123 | 3.90625 | 4 | a=int(raw_input("enter the number"))
b=int(raw_input("enter the number"))
for n in range(a+1,b):
if(n%2==0):
print n
|
c7a3e5891b5f2fa62016e98032f38d4408a4fed8 | manishshiwal/guvi | /factorial1.py | 83 | 3.59375 | 4 | az=int(raw_input("enter the number"))
sa=1
for n in range(1,az+1):
sa*=n
print sa
|
a0ddd524732e01fede68508430b956dbd0f989f1 | hadibus/scratch_nn | /mnist_runner.py | 3,223 | 3.796875 | 4 | # file mnist_runner.py
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
import numpy as np
import random
import neuralNetwork as NN
mnist = input_data.read_data_sets("/tmp/data/") # or wherever you want
# to put your data
X_train = mnist.train.images
y_train = mnist.train.la... |
b7e37b9dd086a3a4e1dbcce709e378a87769fab3 | ChillBroYo/DataStructures | /trie.py | 1,745 | 3.890625 | 4 | # create Trie data structure
from trie_node import TrieNode
from collections import deque
class Trie:
def __init__(self):
self.root = TrieNode(None)
self.count = 0
def dfs_traversal_print(self):
if self.root == None:
print("None")
return False
... |
266dd9f4d92681236380165d828e127a8dafb7ef | jagruti756/PythonTraining_Jagruti | /Assignment 2.py | 6,585 | 4.4375 | 4 | #1 Write a program in Python to perform the following operation:
If a number is divisible by 3 it should print “Consultadd” as a string
If a number is divisible by 5 it should print “Python Training” as a string
If a number is divisible by both 3 and 5 it should print “Consultadd - Python Training” as a string.
a... |
8cd7f43659172e76b0e5dfcc688912228119bf36 | pavantej934/HackerRank_30DaysofCode | /30Days_P4.py | 301 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 17 23:11:15 2017
@author: pavantej
"""
#!/bin/python3
import sys
N = int(input().strip())
if (N % 2 != 0) or (N % 2 == 0 and 6<= N <= 20):
print ("Weird")
elif (N % 2 == 0 and (2 <= N <= 5 or N > 20)):
print ("Not Weird")
|
7f59edbbd8298d1c6c34c1f646819cb28333c5a7 | mshazman/data_munging | /weather/reader.py | 921 | 3.703125 | 4 | """This Module Contain Class To read Data from data file"""
import re
class ReadData():
"""This class object takes data file and return desired data in form of dictionary"""
def __init__(self, file):
self.file = file
def get_data(self, key, index_first, index_second):
"""This method will... |
f6a391044b4bf87edf998971b1a0d2a8924bd182 | shawsuraj/dailyCode | /100-days-of-code/python/Day005/fibonacci.py | 222 | 3.984375 | 4 | n = int(input("Enter the range of fibonacci: "))
a = 0
b = 1
for _ in range(0, n) :
(a, b) = (b, a + b)
print(a, end=' ')
# a = 0
# b = 1
# for _ in range(20):
# (a, b) = (b, a + b)
# print(a, end=' ')
|
66e9c916b7ea5908c091f4fd5a7a5e2821efd3de | shawsuraj/dailyCode | /100-days-of-code/python/Day006/combination.py | 270 | 4.15625 | 4 | print ("Combination finder.")
n = int(input("Enter n: "))
r = int(iinput("Enter r: "))
def factorial ( n ):
result = 1
for num in range ( 1 , n + 1 ):
result *= num
return result
print (factorial( n ) // factorial( r ) // factorial( n - r ))
|
443313237c0f2944f7531d8421ec77d5a0269cba | Alispirale/PythonTraining | /Nom_Age.py | 277 | 3.78125 | 4 | print('Quel est ton nom ?')
monNom = input()
print('Nice to meet you, ' + monNom)
print('La longueur de ton nom est de ' + str(len(monNom)) + ' caracteres')
print('Quel est ton age ?')
monAge = input()
if int(monAge)<35:
print('Tu es jeune !')
else:
print('Ok boomer') |
6a2afeb38e6a67e1412c5c86c8930cd0bd9b02f3 | AlvaroLuz/CalculoNumerico | /CN/P1/mpf.py | 284 | 3.5 | 4 | import math
import numpy as np
def funcx(x):
return np.log(x**3 - x**2 +2 )
a , b = 0.4, 1.6
epsilon = 1e-2
x =0.5
xant = x
x = funcx(x)
print(xant-x)
while (((x%100000000)-(xant%100000000))%100000000)> epsilon:
xant = x
x = funcx(x)
print(xant-x) |
6cd27984d4037cf6c9f088852427b9d780dcba83 | jkleve/Presidential-Prediction | /state_by_state/numpy_utils.py | 1,919 | 3.828125 | 4 | import numpy as np
################################################
#
# Add 2 np arrays row wise
#
################################################
def add_row_to_array(a, b):
if a.shape == (0,0):
return b
if a.shape[1] != b.shape[1]:
print("Number of columns doesn't match. %d vs %d" % (a.shap... |
a97e9afcfe054249032c537dd182116bf29b01ba | jkleve/Presidential-Prediction | /demographics/demo_histograms.py | 442 | 3.5625 | 4 | import numpy as np
import matplotlib.pyplot as plt
# feature 1
f1 = [69.8, 80.91, 69.72, 80.39]
bins = np.arange(65,85,1)
def gen_histogram(accuracies, bins):
mu, sigma = 100, 15
hist, bins = np.histogram(accuracies, bins=bins)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
... |
a5c01e4e665069b608dd1c9185ce8edd74c985d5 | JeffreyBenjaminBrown/play | /_not_music/machineLearn/obsolete/older_flow/it.py | 10,887 | 3.859375 | 4 |
# coding: utf-8
# # Programming Exercise 4: Neural Networks Learning
# In[1]:
get_ipython().magic('matplotlib inline')
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import scipy.io #Used to load the OCTAVE *.mat files
import scipy.misc #Used to show matrix as an image
import matplotlib.cm a... |
4ccc972af4b0662d9b062ad8dec4fb60eafb1e98 | redkins/Demo | /code/jump7.py | 164 | 3.546875 | 4 | for i in range(1,101):
if ( i / 7 == 0 ):
continue
elif ( i % 10 == 7 ):
continue
elif ( i // 10 == 7 ):
continue
print (i)
|
6d6831c5fc145e6dc17c6679154af2549c858512 | PercivalN/Class-Notes-Graphs | /ClassNotesPt1.py | 323 | 3.609375 | 4 | """
Notes for hash table day1
class LinkedListNodes:
def __init__(self, value):
self.value = value
self.next = value
class GraphNode:
def __init__(self, value):
self.value = value
self.edges = [] # This gives as much edges as we want, These are adjacency list
"""
... |
19f21e5e66535ce20858639289ddf946c016d91d | wang-xian-yan/python-example | /basis.py | 258 | 3.921875 | 4 | print('hello python')
strList = ['a', 'b', 'c']
print(len(strList))
for st in strList:
print(st)
print(strList[2])
person = {'name': 'drew.wang', 'age': 20}
print('age:', person['age'])
def showInfo():
print('name:', 'drew.wang')
showInfo()
|
c1a562f556dc8169d74e922f5ebaa2d7eb90e45f | MauricioMucci/Udemy | /Python - Aprendizado/Projeto3/lista3.py | 3,835 | 3.90625 | 4 | #Questao 1
for num in range(3,18,3):
print(num, end=" ")
print()
print()
#Questao 2
for _ in range(3):
for num in range(1,11):
print(num, end=" ")
print()
print()
aux = 0
while aux < 3:
num = 1
while num <= 10:
print(num, end=" ")
num = num + 1
print()
aux = aux ... |
b148c5ec3df262c70703c1e6839c3d375f7a4363 | kulbir-ahluwalia/Implementing_A_star_on_Turtlebot3 | /Phase 3/How to plot curves_modified.py | 1,186 | 3.640625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import math
fig, ax = plt.subplots()
def plot_curve(Xi,Yi,Thetai,UL,UR):
t = 0
r = 0.033
L = 0.160
dt = 0.1
Xn=Xi
Yn=Yi
Thetan = 3.14 * Thetai / 180
# Xi, Yi,Thetai: Input point's coordinates
# Xs, Ys: Start point coordinates for plot fun... |
e76c7cc1e6789df6037f603849e2dbd81e38a7b4 | olzhas23/Flask-blog | /sql.py | 471 | 3.859375 | 4 | import sqlite3
with sqlite3.connect ("blog.db") as connection:
c=connection.cursor()
c.execute("""CREATE TABLE posts (title TEXT, post TEXT)""")
c.execute ("""INSERT INTO posts VALUES( 'hi', 'its a great morning')"""),
c.execute ("""INSERT INTO posts VALUES( 'Good', ' its a great morning')"""),
c.execut... |
ac084f4d68ad55ad44690a054bd0938276b989fc | Kids-Hack-Labs/Winter2021 | /Week01/code/challenges.py | 3,695 | 4.28125 | 4 | """
Kids Hack Labs
Winter 2021 Term
Week 01
Homework Challenges: Number-guessing game
Note: Both challenges implemented at the same time
No extensions are marked as such, only challenges
The score system works by adding remaining tries as points,
meaning it's possible ... |
94cf5385b4d09e2b215c5bf964f7575247b6e441 | Kids-Hack-Labs/Winter2021 | /Week02/code/activity01_base.py | 623 | 4.0625 | 4 | def rewrite_message(first, last, day, month, year):
return f"{first} {last} was born in {month} {day}, {year}."
first_name = "John"
last_name = "Doe"
day = 27 #int
month = "September"
year = 2016
message = rewrite_message(first_name, last_name, day, month, year)
print(message)
first_name = input("What is your fi... |
71c12cbfbace9a5e7604cfcd87323b5d686ca464 | medecau/aoc | /2018/1a.py | 284 | 3.640625 | 4 | import sys
file_path = sys.argv[1]
frequency = 0
with open(file_path) as input_file:
for line in input_file:
sign, num = line[0], int(line[1:])
if sign == "+":
frequency += num
elif sign == "-":
frequency -= num
print(frequency)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.