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 |
|---|---|---|---|---|---|---|
57c7bd9f0660d9fcf67453640d8a9f0fd99d297b | eMostyn/Project-Euler-Problems | /problem 56.py | 730 | 3.8125 | 4 | #Function to compute problem
def compute():
#Holds maximal digit sum so far
maxi = 0
#For each a <100
for i in range(0,100):
#For each b <100
for j in range(0,100):
#Generate number
num = i**j
#Set maxi to be the largest of the current maxi and the dig... |
06c9057de2cf89bf24c404b162c2b22d765bf495 | eMostyn/Project-Euler-Problems | /problem 52.py | 654 | 3.875 | 4 | #Function to check if the condition is met
def checkCondition(n):
#Convert it to string so that we can 'sort' the string
string = sorted(str(n))
#For each multiplier
for i in range(2,7):
#Create the new string
newString = sorted(str(n*i))
#If the strings dont match, return False... |
afe01f68163e25ad7f5c385a2c2ee5b7b037c57c | eMostyn/Project-Euler-Problems | /problem 23.py | 1,105 | 3.796875 | 4 | #Function to generate the sum of all divisors of n
def sumOfDivisors(n):
total = 0
for i in range(1,n):
if n%i == 0:
total+= i
return total
#Generates the list of abundants
def generateAbundant():
abundant = []
for i in range(1,28123):
#If the sum is greater add it
... |
494d933abd398d1d8136e9073c2c8f5ff42ae4b9 | SergeyVegero/G134 | /ДЗ6.py | 231 | 3.6875 | 4 | import random
nyx=[random.randint(0,10) for i in range(10)]
print(nyx)
z=int(input("Укажите число:"))
x=nyx.index(z)
print("Число "+str(z)+" находится в списке под номером "+str(x)) |
e0334e857bed3460736a05791dcd7469ac2fdeab | jakelorah/highschoolprojects | /Senior(2018-2019)/Python/Chapter 2/P2.8.py | 781 | 4.25 | 4 | #Name: Jake Lorah
#Date: 09/14/2018
#Program Number: P2.8
#Program Description: This program finds the area and perimeter of the rectangle, and the length of the diagonal
#Declaring the sides of a rectangle
Side1 = 24
Side2 = 13
Side3 = 24
Side4 = 13
print("The 4 sides of the rectangle are 24 inches, 13 in... |
649a3d084e0195df00ffd31273d999bfdc12e576 | jakelorah/highschoolprojects | /Senior(2018-2019)/Python/Turtle-Methods/turtle_square - size.py | 456 | 3.890625 | 4 | #Jake Lorah
#Coded in: Python 3.4.3
#Uses turtle Graphics to create square
import turtle
aScreen = turtle.Screen()
shelly = turtle.Turtle()
#Change color to orange and blue
shelly.color('orange', 'blue')
shelly.begin_fill()
#Make all forward numbers 200 instead of 100
shelly.forward(200)
shelly.l... |
cdf0b54074aa96db6c30c21d0aaf9026ca250317 | jakelorah/highschoolprojects | /Senior(2018-2019)/Python/Tkinter GUI/3by3grid _ Window Project/7.Button_Event_handler.py | 815 | 4.125 | 4 | #Name: Jake Lorah
#Date: 11/26/2018
#Program Number: 7.Button_Event_handler
#Program Description: This program adds a button event handler.
from tkinter import *
window = Tk()
window.title("Welcome To Computer Science 4")
window.geometry('1100x500')
addtext= Label(window, text="Hello How are you tod... |
eb7b40527b95009c30786729293ceeee92e1056e | jakelorah/highschoolprojects | /Senior(2018-2019)/Python/Tkinter GUI/10.Check_box_Updated.py | 1,739 | 3.953125 | 4 | #Name: Jake Lorah
#Date: 12/5/2018
#Program Number: 10.Check_box
#Program Description: This program adds a check box.
from tkinter import *
from tkinter.ttk import *
window = Tk()
window.title("Welcome To Computer Science 4")
window.geometry('350x200')
chk_state = BooleanVar()
chk_state.set(Tr... |
afec42e00509bc8ae26cf9f73bde35d5b47d2ee7 | jakelorah/highschoolprojects | /Senior(2018-2019)/Python/Chapter 4/average.py | 317 | 4.15625 | 4 | #Find the average
total = 0.0
count = 0
inputStr = input("Enter value: ")
while inputStr != "" :
value = float(inputStr)
total = total + value
count = count + 1
inputStr = input("Enter value: ")
if count > 0 :
average = total / count
else :
average = 0.0
print (average)
|
72a3aa9ffa9a35f8c05298f516f65fc91ab5a53f | jakelorah/highschoolprojects | /Senior(2018-2019)/Python/Tkinter GUI/3by3grid.py | 420 | 3.765625 | 4 | #Name: Jake Lorah
#Date: 11/26/2018
#Program Number: 3by3grid
#Program Description: This program adds a 3 by 3 grid and adds something in each box.
from tkinter import *
window = Tk()
window.title("3 x 3 Grid Lab - Jake Lorah")
window.geometry('1100x500')
pcti = PhotoImage(file='pic1.gif')
image = ... |
20eb46a647a6868ca13589e57c85612ac2dbcb79 | jakelorah/highschoolprojects | /Senior(2018-2019)/Python/Chapter 3/P3.4.py | 558 | 4 | 4 | #Name: Jake Lorah
#Date: 09/26/2018
#Program Number: P3.4.py
#Program Description: This program reads three numbers and prints either all the same, all different, or neither depending on what numbers they are.
userInput = input("Please enter your first number: ")
userInput2 = input("Please enter your second numb... |
939412528610843959ee52b2b4fbd620083c5cb9 | T-D-Wasowski/Small-Projects | /Turtle Artist/Prototype.py | 473 | 4.15625 | 4 | import random
import turtle
turtle.stamp()
moveAmount = int(input("Enter the amount of moves \
you would like your Turtle Artist to make: "))
for i in range(moveAmount):
turtle.right(random.randint(1,51)) #<-- For circles.
turtle.forward(random.randint(1,101))
turtle.stamp() #Do you collec... |
5f858e6f036ee77eee30a92bc7b0efe63fc385f7 | dutcjh/learnpython | /examp5_13.py | 224 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
例5.13 lambda函数的应用
"""
def func():
x,y,m,n = 1,2,3,4
add = lambda x,y:x+y
print(add)
sub = lambda m,n:m-n
print(sub)
return add(x,y)+sub(m,n)
print(func()) |
fa839d925257533c6ac055cf94edb77a1516f4a2 | dutcjh/learnpython | /examp4_1.py | 233 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 2 20:36:41 2016
@author: ChenJianhui
"""
a = input("a:")
a = int(a)
if a > 0 :
print(a,"是正数。")
elif a < 0 :
print(a,"是负数。")
else:
print(a,"是零。")
|
918e60f3a788fadd9c6049d723261fabfef285e5 | dutcjh/learnpython | /examp4_14.py | 268 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 2 21:36:16 2016
@author: ChenJianhui
"""
#def judge(num):
# if num % 7 != 0:
# return True
#p = lambda x: True if x%7 != 0 else False
print(list(filter(lambda x: True if x%7 != 0 else False,\
range(1,101))))
|
22c8ec5ff56fb5e126340d15834d0b3e329a5bcc | dutcjh/learnpython | /examp2_6.py | 238 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
例2-6:根据美元不同硬币个数计算美分总额
"""
n = int(input('Nickels? '))
d = int(input('Dimes? '))
q = int(input('Quarters? '))
total = 5*n + 10*d + 25*q
print()
print(str(total)+" cents")
|
3e2930186e5ad47dd72590b4d7d7b4f12395c0c1 | dutcjh/learnpython | /assign6_2.py | 383 | 3.921875 | 4 | s1 = input('Please enter a string of lowercase letters: ')
s1 = s1.lower()
s2 = s1[0]
s3 = ''
for i in range(len(s1)-1):
if s1[i] <= s1[i + 1]:
s2 = s2 + s1[i + 1]
else:
if len(s3) < len(s2):
s3, s2 = s2, s1[i + 1]
else:
s2 = s1[i + 1]
if len(s3) < len(s2):
s3... |
ee9d8bc5a220a0f6ad65a92a22b6057cf6394240 | Ehsankingb/ElliottWaveAnalyzer | /models/WaveOptions.py | 5,091 | 3.8125 | 4 | from abc import ABC, abstractmethod
class WaveOptions:
"""
WaveOptions are a list of integers denoting the number of intermediate min / maxima should be skipped while
finding a MonoWave.
E.g. [1,0,0,0,0] will skip the first found maxima for the first MonoWaveUp.
"""
def __init__(self, i: int,... |
f6ce3dbf553b06732bd5e21ca21eb1ffeca65a50 | GabrielForchesatto/Jogo-da-Forca | /functions.py | 2,113 | 4.03125 | 4 | def linha():
print('-=' * 10)
import os
def string(value): #Valida para que a entrada seja apenas letras, sem números
if value.isalpha() == True:
return True
else:
return False
def asteriscos(palavra):
return print("*" * len(palavra))
def Desafiante():
while ... |
042e82cf7feadb8c7d5b827f370384c0a8a8d21c | shiqiuwang/exam_for_python | /chapter03/3_4.py | 198 | 3.953125 | 4 | string_number = input("请输入一个5位数字:")
if string_number == string_number[::-1]:
print("输入的这个数字是回文数")
else:
print("输入的这个数字不是回文数")
|
b5ed77e0259e50e5073b79eb08547ffe0609a3bd | shiqiuwang/exam_for_python | /chapter05/5_1.py | 266 | 3.953125 | 4 | def isNum(string: str) -> bool:
expression = eval(string)
if type(expression) == int or type(expression) == float or type(expression) == complex:
return True
else:
return False
test_string = "5.0+3j"
ret = isNum(test_string)
print(ret)
|
6729d34d16ddfb2af1c654fd038e974d83c93e09 | shiqiuwang/exam_for_python | /chapter05/5_2.py | 716 | 3.984375 | 4 | import math
def isPrime(number: int) -> bool:
if number == 1:
return False
elif number == 2:
return True
else:
for i in range(2, number):
if number % i == 0:
break
else:
return True
return False
if __name__ == '__mai... |
b46807c8c954d5fb88d2c4fcdc5432b32eb76ac5 | heeyoung1002/LIKELION | /check_assginment.py | 1,326 | 3.609375 | 4 | def check_assignment ():
print("Camilla 님 안녕하세요")
print("과제는 다 해오셨나요?")
print("고생많으셨습니다. 또 과제를 드리겠습니다")
check_assignment()
def check_assignment (name):
print(f"{name} 님 안녕하세요")
print(f"과제는 다 해오셨나요 {name}님?")
print("고생많으셨습니다. 또 과제를 드리겠습니다")
check_assignment("Camilla")
def check_assignment (na... |
dbcfc1870ef6d5264f4590dc99bef371502814d7 | heeyoung1002/LIKELION | /for_loop_with_range.py | 141 | 3.6875 | 4 | #for loop을 통해서 0-9까지 번째 주식매수 출력
for number in range(10):
print(f'{number+1} 번째 주식매수 입니다.')
|
4d04868e0ebd5557f277ff7d9e39b7317082a86d | AMFTech512/austins-leetcode-solutions | /problems/2 - Add Two Numbers/add2nums.py | 1,663 | 3.890625 | 4 | '''
Solution by Austin Fay.
This is a recursive solution for problem "2. Add Two Numbers" on leetcode.com
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# this function converts the singly-linked list in... |
5fdb9555e14e0de2dcd8db73f47fe0d11281e0d1 | SecurityAnalysts/AlteMatrix | /altematrix/converter/hexadecimal.py | 2,154 | 3.734375 | 4 | def hexadecimal_to_binary(data):
print("Hexadecimal value:",data)
try:
bnr = int(data,16)
bnr = bin(bnr).replace('0b','')
except ValueError:
raise ValueError("Non-hexadecimal number entered!")
print("Binary value:",bnr)
def hexadecimal_to_binary_s(data):
try:
bnr = in... |
612733b55fa65e97e9e93c093ad8af71a74ecf60 | AdityaGupta1/python-pacman | /Game.py | 6,070 | 3.515625 | 4 | from tkinter import *
import random as seed
import time
class Game:
def __init__(self):
self.root = Tk()
self.text = Text(self.root, height = 1, width = 50)
self.text.pack()
self.text.insert(END, "Use the arrow keys to control PacMan!")
self.root.bind('<KeyPress-Up>', self.... |
fb9f7cdb7e933b2096fc0e81df07b5b64933c64a | CoderXAndZ/Python_demo | /LearnText/计时器.py | 569 | 3.546875 | 4 |
import time
global total
# 类似倒计时功能实现
def start(total_time):
while (total_time > 0):
print("total_time:", total_time)
time.sleep(1)
total_time -= 1
def end():
print("调用停止打印")
start(0)
if __name__ == '__main__':
global total
total = 10
start(total)
end()
print(... |
92d5c2c76194931cdd0ef42fbca2fd753ff9d6a0 | laneenget/Python-Intro | /CamelCase.py | 325 | 3.671875 | 4 | sentence = input('Enter a sentence: ')
split_sentence = sentence.split()
i = 0
while i < len(split_sentence):
if i == 0:
split_sentence[i] = split_sentence[i].lower()
i += 1
else:
split_sentence[i] = split_sentence[i].capitalize()
i += 1
s = ''
s = s.join(split_sentence)
pri... |
9f2a54ad03401505fbfae58a9c35df0a5caac756 | gengyuming/CaseBuilder | /Client.py | 3,858 | 3.609375 | 4 | import tkinter as tk
from tkinter import filedialog
from Main import main
window = tk.Tk()
window.title('Xmind用例生成器')
form_width = [10, 30, 10]
form_height = 2
# 获取屏幕分辨率
def get_screen_size(win):
return win.winfo_screenwidth(), win.winfo_screenheight()
# 窗口居中
def center_window(root, width, height):
scree... |
9ec819faa8c548aa643eacc85e916ec766fa5090 | Raper-programista/first | /date.py | 146 | 3.828125 | 4 | import datetime
now = datetime.datetime.now()
hour = now.hour
if hour == 9 or hour == 12:
print('Napij się kawy')
else:
print('aaa już nic') |
7cd790949679889275177d44f2c467b21af1d645 | Raper-programista/first | /logo_olompijskie.py | 296 | 3.78125 | 4 | import turtle as t
x = [-130,0,130,-60,70]
y = [0,0,0,-60,-60]
color = ['blue', 'black', 'red','yellow','green']
def draw_circle(x, y, color):
t.penup()
t.pensize(10)
t.setposition(x,y)
t.pendown()
t.color(color)
t.circle(60)
for i in range(0,5):
draw_circle(x[i],y[i],color[i]) |
f23381c1053e45ac2892da02c6dbf51122e7210c | brands-d/NumLinAlg-Project | /model.py | 11,580 | 3.921875 | 4 | """Models (MVC pattern) for numerical solutions of differential equations.
This module defines the model used in the MVC pattern (Model-View-Controller)
for a program disgned to solve and display numerical solutions to for example
the stationary heat equation. This module contains an abstract model as well
as concret ... |
75fe28fc3b45b40bd35cb62b2da65f6726edd875 | alexandr308/Python_basics | /week 4/5.py | 259 | 4 | 4 | def IsPrime(n):
i = 2
while i <= (n ** 0.5):
if n % i == 0:
return n % i == 0
else:
i += 1
else:
return n % i == 0 and n != i
n = int(input())
if IsPrime(n):
print('NO')
else:
print('YES')
|
8973031c5f483136a3abbcd129306cd7245f071a | wangzeming666/Class-Exercise-For-Learning | /text20.py | 142 | 4 | 4 | num = input("Please enter a number:")
if num.isdigit():
if num == num[:: -1]:
print("True")
else:
print("False")
else:
print("False")
|
d34b0bc1206c88948e5cfbbf4850332f91a60f3e | wangzeming666/Class-Exercise-For-Learning | /text28.py | 179 | 3.84375 | 4 | def isprime(x):
if x < 2:
return False
for i in range(2, x+1):
if x % i == 0:
return False
if i > x // 2 + 1:
return True
|
f79c3482f6ff9b217068b53806dc6c520d47321c | wangzeming666/Class-Exercise-For-Learning | /text23.py | 104 | 3.90625 | 4 | list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
C = {}
for i in range(3):
C[list1[i]] = list2[i]
print(C)
|
9c5c4fe4f20788f9fdd9ef79dc5f1720adeee469 | talianzakowski/neos | /write.py | 3,840 | 3.75 | 4 | """Write a stream of close approaches to CSV or to JSON.
This module exports two functions: `write_to_csv` and `write_to_json`, each of
which accept an `results` stream of close approaches and a path to which to
write the data.
These functions are invoked by the main module with the output of the `limit`
function and... |
7ef16b31d28fcb4decdf26af3558090637e01214 | Fullsize/practice_python | /basic/dictionaries/index.py | 703 | 3.65625 | 4 | '''
Author: Fullsize
Date: 2021-07-27 10:52:32
LastEditors: Fullsize
LastEditTime: 2021-07-27 11:27:03
FilePath: /practice_python/basic/dictionaries/dictionaries.py
'''
# 和js的json差不多,key:value形式; value可以是任何形式数据
p = dict()
p['a'] = 1
print(p)
p['b'] = 2
p['c'] = 3
print(p)
# 也可以这样声明同js的json 字面量声明
p2 = {}
p2['d'] = 1
pri... |
c7f218a5a4abc21743f68b6e190d7f31a12698c6 | Fullsize/practice_python | /basic/string.py | 858 | 3.84375 | 4 | '''
Author: Fullsize
Date: 2021-07-15 11:17:47
LastEditors: Fullsize
LastEditTime: 2021-07-15 12:08:56
FilePath: /practice_python/basic/string.py
'''
# 字符串数组?
user_name='benming'
print(user_name[0])
print(user_name[3-1])
# len 获取数据长度
print(len('123'))
print(len([1,2,3]))
print(len({'a':1,'b':2}))
# 可以for in
for i in us... |
da7d8ab7cf09107e188155ba255a986db7edbb07 | lydiah2015/Pass-Locker | /test_credential.py | 1,210 | 3.578125 | 4 | import unittest
from credential import Credential
class TestCredential(unittest.TestCase):
def setUp(self):
"""
run before each test
"""
self.credential= Credential()
def tearDown(self):
'''
tearDown method that does clean up after each test case has run.
... |
bd940f09734b661d4902b0f304f1d38d1530fa44 | MichaelAlonso/MyCSSI2019Lab | /WeLearn/M3-Python/L1-Python_Intro/hello.py | 1,107 | 4.21875 | 4 | print("Hello world!")
print("Bye world!")
num1 = int(raw_input("Enter number #1: "))
num2 = int(raw_input("Enter number #2: "))
total = num1 + num2
print("The sum is " + str(total))
num = int(raw_input("Enter a number: "))
if num > 0:
print("That's a positive number!")
print("Do cherries come from cherry bloss... |
0845572b157a946550ec00a4078ec772e114e446 | djonathan/Module_1_Challenge | /loan_analyzer.py | 4,273 | 4.40625 | 4 | #! python
# coding: utf-8
import csv
from pathlib import Path
# Use a discount rate of %20 for all calculations
annual_discount_rate = 0.20
"""Part 1: Automate the Calculations.
Use builtin functions to produce a loan summary
"""
loan_costs = [500, 600, 200, 1000, 450]
# Print the number of loans from the lis... |
30c442d6452611b7b020eaff57709abc89a81674 | anthony-angel/NetReader | /NetReader_test.py | 1,530 | 3.546875 | 4 | from bs4 import BeautifulSoup
import requests
r = requests.get('https://novel12.com/the-crystal-shard/4-the-crystal-shard-68738.htm')
soup = BeautifulSoup(r.text, 'html.parser')
print(soup.prettify())
links = [a.get('href') for a in soup.find_all('a', href=True)]
print(links)
#reccomendation for structure
"""cla... |
ffbc04ff78be2c34d2d5590f31b2a2a0f2abef12 | Marcopy123/sum-up | /sum_up.py | 1,352 | 3.890625 | 4 | from collections import Counter
import sys
import string
from nltk.corpus import stopwords
import pandas as pd
file_name = input("Enter the file name you would like to sum up : \n")
text = ''
number_words = 0
try:
with open(file_name,'r') as file:
for line in file.readlines():
text += line
e... |
6ca54e920857c0855d16fe5272d98bc9f005e2f3 | devonzuegel/Project_Euler | /Problem1.py | 92 | 3.859375 | 4 | sum = 0;
for x in range(1,1000):
if ((x % 3 == 0) or (x % 5 == 0)):
sum += x
print(sum) |
31c9632a5925fc3ff7c5d6fe98f5dda3bce80128 | alexthemonkey/interviewBit | /Array/merge_overlapping_intervals.py | 977 | 4 | 4 | """
Merge Overlapping Intervals
https://www.interviewbit.com/problems/merge-overlapping-intervals/
Given a collection of intervals, merge all overlapping intervals.
For example:
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
Make sure the returned intervals are sorted.
"""
# Definition for an in... |
2680c78a27f4feef2ddfc6672cfa64ffd830968e | alexthemonkey/interviewBit | /Array/Max_Sum_Contiguous_SubarrayBookmark.py | 615 | 4 | 4 | """
Max Sum Contiguous Sub array
https://www.interviewbit.com/problems/max-sum-contiguous-subarray/
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example:
Given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum ... |
d0a82db653e642d5ebe526979f0824beeaaae19b | alexthemonkey/interviewBit | /DP/Length_Of_Longest_Subsequence.py | 934 | 3.953125 | 4 | """
Length Of Longest Subsequence
https://www.interviewbit.com/problems/length-of-longest-subsequence/
Given an array of integers, find the length of longest subsequence which is first increasing then decreasing.
For the given array [1 11 2 10 4 5 2 1]
Longest subsequence is [1 2 10 4 2 1]
Return value 6
"""
clas... |
8a9a37f3371ef508e5d6d6d9e4502d759688060a | alexthemonkey/interviewBit | /Hashing/Longest_Substring_Without_Repeat.py | 858 | 3.9375 | 4 | """
Longest Substring Without Repeat
https://www.interviewbit.com/problems/longest-substring-without-repeat/
Given a string,
find the length of the longest substring without repeating characters.
Example:
The longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
For "bbbbb" ... |
5bfbed8f5537e68607f82ce6b5234804e14d7344 | alexthemonkey/interviewBit | /Trees/Max_Depth_of_Binary_Tree.py | 517 | 3.8125 | 4 | """
Max Depth Of Binary Tree
https://www.interviewbit.com/problems/max-depth-of-binary-tree/
Given a binary tree, find its maximum depth.
"""
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solu... |
d50db0eceb6158b5b50ac5ae8d61f2e074b5825a | alexthemonkey/interviewBit | /Two_Pointer/Counting_Triangles.py | 1,452 | 3.59375 | 4 | """
Counting Triangles
https://www.interviewbit.com/problems/counting-triangles/
You are given an array of N non-negative integers, A0, A1, ..., AN-1.
Considering each array element Ai as the edge length of some line segment,
count the number of triangles which you can form using these array values.
Notes:
You can... |
79f7e5b921221228c1af9e794240bc2dade14f7f | alexthemonkey/interviewBit | /Array/max_distance.py | 961 | 3.8125 | 4 | """
Max Distance
Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j].
If there is no solution possible, return -1.
Example :
A : [3 5 4 2]
Output : 2
for the pair (3, 4)
"""
"""
One observation is that:
if i and j are the answer, then
1. A[i] is the min num ... |
c7d4ecd40958e1e1801dadb0964524664986a736 | alexthemonkey/interviewBit | /DP/Longest_Valid_Parentheses.py | 1,318 | 3.9375 | 4 | """
Longest Valid Parentheses
https://www.interviewbit.com/problems/longest-valid-parentheses/
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another... |
ab631a8f16be070bb556ed662c1af5931cd9cbe7 | vishalagg/Using_pandas | /bar_plot.py | 1,829 | 4.625 | 5 | import matplotlib.pyplot as plt
'''
In line charts, we simply pass the the x_values,y_values to plt.plot() and rest of wprk is done by the function itself. In case of bar graph, we have to take care of three things:
1.position of bars(ie. starting position of each bar)
2.position of axis labels.
3.width o... |
0255523e1d56706903427e08fb711b63969a4e60 | Oksana0407/Oksana | /new_file.py | 205 | 3.796875 | 4 | name = raw_input('What is your name? ')
age = int ('How old are you?')
prediction = (2015 - age) + 100
text = 'you will have 100 years at '
text2 = ' year'
print name + ', ' text + str(prediction) + text2
|
3226ed2ec4e7ee5b520dffefa009406ec8340a2e | knishina/disaster_response | /PY/ETL.py | 2,628 | 3.703125 | 4 | """
The purpose of this python file is to gather the data, clean it, and save the resulting dataframe.
"""
# import libraries
import pandas as pd
from sqlalchemy import create_engine
def merge_data():
"""
Input: None
Output: merged dataframe
Tasks Performed:
- read in csv for messages and cate... |
7468894bd845927f88abdc8c1a604f2639477488 | IgorSonehara/project-euler | /Problem7_10001st_prime.py | 398 | 3.765625 | 4 | import math
def isPrime(n):
flag = 1
if n <= 1:
flag = 0
else:
for i in range(2, (int)(math.sqrt(n))+1):
if n % i == 0:
flag = 0
break
return flag
i = 2
count = 0
while True:
if isPrime(i):
count = count + 1
... |
a3a922e0589b97af51d2a7d7e6e3c449ec80d23e | syedfaiqyazdani/scheduling | /fcfs.py | 1,108 | 3.890625 | 4 | '''
Online Python Compiler.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
'''
arrival_time=[]
burst_time=[]
ch=int(input("Enter number of processes:"))
i=0
while i<ch:
a=int(input("Ente... |
3cb86970951a4c592edf191fb44af65aca41e321 | rachelprisock/python_hard_way | /ex3.py | 1,014 | 4.21875 | 4 | from __future__ import division
print "I will now count my chickens:"
# PEMDAS so 30 / 6 = 5 and 25 + 5 = 30
print "Hens", 25 + 30 / 6
# 25 * 3 = 75, 75 % 4 = 3, so 100 - 3 = 97
print "Roosters", 100 - 25 * 3 % 4
print "Now I will count the eggs:"
# 4 % 2 = 0, 1 / 4 (no floats with /) = 0
# so 3 + 2 + 1 - 5 + 0 - 0... |
bd7f32919c7ecf0ddf985039ba7c962d7f7c730b | MickFlyHigh/computerclub_2015 | /graph.py | 13,439 | 3.53125 | 4 | '''
Created on Aug 16, 2015
@author: Mr Goldschmidt
'''
import node,edge
import random,math
import sys
# import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
# import matplotlib.animation as animation
class Graph:
'''
implement graphs function
'''
def __init__(self):
'''... |
2b09ef39b940045874a0d8203605507459d76b0f | ldunekac/Pandemic | /src/View/Console/Level/cities_view.py | 1,788 | 3.953125 | 4 |
class CitiesView:
""" Represents the view of the cities """
MAX_CITIES = 10
def __init__(self, cities):
""" Initialize the Cities View """
self.cities = cities
self.section = 0
def display(self):
""" Display all the cities """
... |
bbcaa54d346aa3a859bc010a3dcbb8d918c7378c | ldunekac/Pandemic | /src/View/Console/Level/Infection/infection_view.py | 432 | 3.8125 | 4 |
class InfectionView:
""" Represents the view for an Infection """
def __init__(self, city):
""" Initialize the view """
self.city = city
def display(self):
""" Display the Infection """
print "{0} was infected!\r".format(self.city)
for diseas... |
5f1b7ecae6a4cfd4903fbeffa5d5d98038101ff1 | ldunekac/Pandemic | /src/Level/Disease/Outbreak/Test/outbreak_test.py | 2,781 | 3.59375 | 4 | import unittest
from Level.Disease.disease import Disease
from Level.Disease.Outbreak.outbreak import Outbreak
from Test.test_helper import BuildCityList
class breakout(unittest.TestCase):
""" Test cases of breakout """
def setUp(self):
""" Build the Cities and Outbreak for the test """
... |
b1daf2b123dd2a0913caf68febb60cce7b8ff88c | ZenVendor/Python | /basiccourse/axb.py | 704 | 3.96875 | 4 | import math
print("ax2 + bx + c = 0")
a = int(input("Enter number a: "))
b = int(input("Enter number b: "))
c = int(input("Enter number c: "))
if a == 0:
print("Function {}x + {} has zero at x = {} and intercept at y = {}.".format(b, c, -c/b, b))
else:
delta = pow(b, 2) - 4 * a * c
if delta > 0:
x... |
bf16ab9f42b9e7115339abc939ed6a9ceaf5ac76 | ZenVendor/Python | /basiccourse/nwd.py | 174 | 3.625 | 4 | #euklidean algorithm
import math
math.gc
x = input("Enter integer x: ")
y = input("Enter integer y: ")
while x != y:
if x > y:
x -= y
else:
y -= x
|
94241d72f6b7133e7ef087fb9cd41f4549c77948 | ZenVendor/Python | /basiccourse/hello2.py | 62 | 3.609375 | 4 | name = input("Enter name: ")
print("Hello, {}!".format(name))
|
687c4731b29f6843006bca2598c5d545cd158f27 | luciorq/dcluster | /dcluster/util/collection.py | 2,353 | 3.828125 | 4 | '''
Utility functions for collections.
'''
import collections
import copy
try:
collectionsAbc = collections.abc
except AttributeError:
collectionsAbc = collections
def update_recursively(d, u):
'''
Updates the dictionary d with the contents of dictionary u.
Will add new key/value pairs for eve... |
59b08bedd46f3c4ae4ddca84107f393cc3a3086c | kavikamal/PythonPractice | /rna-transcription/rna_transcription.py | 570 | 3.8125 | 4 | def to_rna(dna_strand):
dna_strand = dna_strand.upper()
rna_strand=""
for i in dna_strand:
if i=="G":
rna_strand = rna_strand + "C"
elif i=="C":
rna_strand = rna_strand + "G"
elif i=="T":
rna_strand = rna_strand + "A"
elif i=="A":
r... |
84624532f56dc44454724851da51c8fa3525f226 | Pablinki/QA-System | /qa_sys.py | 6,769 | 3.734375 | 4 | #### mini_qa.py
#
# A toy question-answering system, which uses Google to attempt to
# answer questions of the form "Who... ?" An example is: "Who
# discovered relativity?"
#
# The design is a simplified version of the AskMSR system developed by
# researchers at Microsoft Research. The original paper is:
#
# Brill, L... |
45f2ee0ff1c05000da52d3dad0d924257df44a6b | chepkoy/python_collections | /tuples/packing.py | 812 | 4.09375 | 4 | # Packing and unpacking in python
def packer(**kwargs):
print(kwargs)
packer(name = 'allan', language = 'swahili', country = 'Kenya', tribal = None)
# Explicit definition of an argument
def packer(tribal = None, **kwargs):
print(kwargs)
packer(name = 'allan', language = 'swahili', country = 'Kenya', triba... |
6a9813cf7f1e5cf1d940b48adeefcd95d45dba36 | cmyser/tasks | /laba4/task2.py | 153 | 3.65625 | 4 | n = int(input(' i need a value: '))
n = format(n, 'b')
print(type(n))
count = 0
for i in n:
if i == '1':
count += 1
print(count) |
4cb586544f7ac01cd18994144caccaf8fc9ac9f4 | cmyser/tasks | /lab1!/laba3!.py | 1,943 | 3.875 | 4 | # /////////////////////////////////////square
# count = 10
#
# for i in range(10):
#
# for k in range(10):
#
# if ( k == 0 or i == count-1 or k == 9 or i == count - 10):
#
# print("*", end=" ")
#
# else:
#
# print(" ", end=" ")
#
# print("")
#
... |
54eb5da2f4ad96170ace933b5246d44595e1dbcf | morrisongraeme/q_learning | /agents/q_table_tictactoe.py | 6,972 | 3.5625 | 4 | import numpy as np
import random
import math
# Q-table learning agent and environment for tic-tac-toe, created by Chris Nash
class Agent:
def __init__(self, n_states, discount=0.99, max_explore=1,
min_explore=0.01, decay_explore=0.0001, max_learn=0.5, min_learn=0.1, decay_learn=0.0001):
#... |
570df1e64589e69025e2e5afcedbfb5197040c49 | adizim/dsa | /algo/search.py | 699 | 3.984375 | 4 | def binary_search(lst, x):
s, e = 0, len(lst) - 1
while s <= e:
mid = (s + e) // 2
if x == lst[mid]:
return mid
elif x < lst[mid]:
e = mid - 1
else:
s = mid + 1
return -1
def binary_search_recursive(lst, x):
return binary_search_helpe... |
d630735f5374ba6027edfaed217eeb9bc65655fc | Xarct/Matematica-Financeira- | /taxa aparente real .py | 450 | 3.5625 | 4 | ir = float ( input ( " Digite a taxa de juros real anual : "))
i =float ( input ( " Digite o valor da inflação anual: "))
import math
x =(( ir / 100 ) * ( (i /100 )+ 1) )
taxaaparente =(( x + ( i /100 + 1 )) - 1)
taxamensal =((( 1 + taxaaparente )**0.08333) - 1)
tp = taxaaparente * 100
tm =(( taxamensal ) ) * 100
pri... |
c3f4193213e9d6270af3a8f4836d6460ebda3dc3 | sdk1926/python_hard | /classmethod2.py | 4,011 | 3.78125 | 4 | # 클래스 메소드, 인스턴스 메소드, 스태틱 메소드
# 기본 인스턴스 매소드
class Student(object):
'''
Student class
Author : sdk
Date : 2021.04.13
Description : Class, Static, Instance Method
'''
# Class 변수
tuition_per = 1.0
def __init__(self, id, first_name, last_name, email , grade, tuition, gpa):
... |
0656ff5e5cd9400d7871b1cc5ef741e375b0ab70 | sdk1926/python_hard | /higher_order_function.py | 3,582 | 3.59375 | 4 | # 일급함수(일급 객체)
# 파이썬 함수 특징
# 1. 런타임 초기화
# 2. 변수등에 할당가능
# 3. 함수 인수 전달 가능
# 4. 함수 결과로 반환 가능
# 함수 객체 예제
def factorial(n):
'''Factorial Function -> n:int'''
if n == 1:
return 1
return n * factorial(n-1) # 5 * 4 * 3 * 2 * 1
class A:
pass
print('EX1-1 -', factorial(5)) # EX1-1 120
print(... |
a39be1f54f3396ea83aeaa6bb92553fa63a26c25 | rushabhkumbhani/Tkinter-Projects | /Tkinker Projects/File Sorting Application/sort.py | 1,992 | 3.859375 | 4 | import os, shutil
folders={
'videos':['.mp4'],
'audios':['.wav','.mp3'],
'images':['.jpg','.png'],
'documents':['.doc','.xlsx','xls','.pdf','.zip','rar']
}
# print(folders)
# for folder_name in folders:
# print(folder_name, folders[folder_name])
def rename_folder():
for folder i... |
00de017661574bce9d08ba11d10bb30503dae9c9 | UJHa/Codeit-Study | /(11) 알고리즘 기초 - Dynamic Programming/01) 1003 피보나치 함수/seonga.py | 318 | 3.671875 | 4 | # Tabluation방식으로 0, 1이 호출되는 횟수를 저장함.
zero = [1, 0]
one = [0, 1]
for i in range(2, 41): # 40까지
zero.append(zero[i-1]+zero[i-2])
one.append(one[i-1]+zero[i-2])
# index로 접근해서 출력
for _ in range(int(input())):
n = int(input())
print(zero[n], zero[n])
|
f2ac9ece8f2a4fe69e0cce71b19ef43d87ede9b0 | UJHa/Codeit-Study | /(09) 알고리즘 기초 - Brute Force/09) 1182 부분수열의 합/seonga.py | 633 | 3.609375 | 4 | from itertools import combinations # combinations 조합 모듈 (순열 모듈도 존재)
def partitional_sequence(n, sum_m, lst):
count = 0
for i in range(1, len(lst)+1):
lst_com = list(combinations(lst,i)) # lst에서 i개 만큼 뽑는 모든 경우의 수 추출
for list_value in lst_com: # 추출된 경우의 수 반복적으로 돌면서 합 확인
... |
536058c77f1a43c567417b364fd1e0f46ff2a15d | UJHa/Codeit-Study | /프로그래머스/00_코딩테스트_고득점_Kit/01_해시/1_완주하지 못한 선수/Seonga.py | 784 | 3.546875 | 4 | # 완주하지 못한 선수
# 정확성: 50.0
# 효율성: 50.0
# 합계: 100.0 / 100.0
# 완주하지 못한 선수
def solution(participant, completion):
answer = ''
bucket = 0
dict_ = {} # 마라톤에 참여한 선수들의 이름을 담을 딕셔너리
for m in participant:
dict_[hash(m)] = m # 마라톤 참여 선수의 해시값을 key, 마라톤 참여 선수 이름을 value
bucket += int(h... |
fedf33361a317a1d9784b36b9d6289a547bbae5d | UJHa/Codeit-Study | /(09) 알고리즘 기초 - Brute Force/05) 1018 체스판 다시 칠하기/jinhwan.py | 1,249 | 3.640625 | 4 | # (1018) 체스판 다시 칠하기
def redraw_count(board, pos_x, pos_y, start_color):
wrong_count = 0
correct_color = start_color
# 입력받은 시작 좌표를 통해서 8x8 크기의 체스판의 각 칸 흑백 색깔 확인
for y in range(pos_y, pos_y + 8):
for x in range(pos_x, pos_x + 8):
if board[y][x] != correct_color:
wrong... |
c85afe779b97eabd311814d91e6e3d9337b5daa0 | UJHa/Codeit-Study | /(09) 알고리즘 기초 - Brute Force/04) 14912 숫자 빈도수/seonga.py | 393 | 3.625 | 4 | # 입력값 받기
value = list(map(int, input().split()))
def num_frequency(lst):
count = 0
for i in range(1,value[0]+1):
nums = list(map(int, str(i))) # 숫자의 자리수를 리스트로 쪼개어 변수에 담음.
for j in range(len(nums)):
if nums[j] == value[1]:
count +=1
return count
print(nu... |
a1bce42b0355793388d269495bb3187077427347 | UJHa/Codeit-Study | /프로그래머스/00_코딩테스트_고득점_Kit/01_해시/2_전화번호 목록/jinhwan.py | 781 | 3.90625 | 4 | # 1차 풀이 : 정확성 11,14번 실패, 효율성 성공
# 2차 풀이 : 정확성 성공, 효율성 4번 실패
# 3차 풀이 성공
# # 2차 풀이에서 prefix_dict의 value를 list > dictionary로 변경
# # 변경 이유 : list보다 dictionary의 key를 통해서 찾는 것이 빠름
def solution(phone_book):
answer = True
prefix_dict = {}
for p in phone_book:
prefix_dict[p] = 1
for number in phone_boo... |
6ee024fd04c78cab456919cb5973a74df93d2efc | UJHa/Codeit-Study | /(10) 알고리즘 기초 - Sort, Binary Search/01) 2750 수 정렬하기/seonga.py | 1,251 | 3.6875 | 4 | # 합병정렬로 정렬
# 입력받기
N = int(input())
ANSWER = [int(input()) for _ in range(N)]
def merge(list1, list2):
i = 0
j = 0
# 정렬된 항목들을 담을 리스트
merged_list = []
# list1과 list2를 돌면서 merged_list에 항목 정렬
while i < len(list1) and j < len(list2):
if list1[i] > list2[j]:
me... |
e5dddf54e76e6b32aa69c3bc6c37dda4b87447d9 | UJHa/Codeit-Study | /(10) 알고리즘 기초 - Sort, Binary Search/03) 10815 숫자 카드/seonga.py | 2,276 | 3.625 | 4 | # 퀵 정렬과 이진탐색을 이용하여 문제 풀이 (Python3 시간초과 PyPy3 정답)
# 두 요소의 위치를 바꿔주는 helper function
def swap_elements(my_list, index1, index2):
my_list[index1], my_list[index2] = my_list[index2], my_list[index1]
# 퀵 정렬에서 사용되는 partition 함수
def partition(my_list, start, end):
# 리스트 값 확인과 기준점 이하 값들의 위치 확인을 위한 변수 정의
i = s... |
e5158f7d81a006c0f033570f618bdbd5a497d038 | UJHa/Codeit-Study | /프로그래머스/00_코딩테스트_고득점_Kit/01_해시/2_전화번호 목록/Seonga.py | 806 | 3.640625 | 4 | # 전화번호 목록
# 정확성: 83.3
# 효율성: 16.7
# 합계: 100.0 / 100.0
def solution(phone_book):
answer = True
hash_map = {} # 전화번호를 담을 딕셔너리
for phone_number in phone_book:
hash_map[phone_number] = hash(phone_number) # 전화번호에 해당하는 hash 값을 키로 value를 phone number로 딕셔너리 생성
for phone_... |
69edf05626851fcc28fbd6767ef9845569b5a0b1 | sfk14/Twitter | /storeTweetData.py | 3,702 | 3.53125 | 4 | '''
Takes a collection of tweet IDs saved by my other program and downloads and saves all the data associated with them.
Johne Rzodkiewicz
Command line usage:
Arg 1: Input file name.
Arg 2: Output file name.
If both are blank, my hardcoded debugging defaults are used. If only one is supplied, it is assumed to b... |
8df3aa81ce023d96ec0f32f48a894ca9724c74d7 | Kyle-Everett10/cp_1404_pracs | /practical_8/taxi_service.py | 1,565 | 3.84375 | 4 | from practical_8.taxi import Taxi
from practical_8.silverservicetaxi import SilverServiceTaxi
MENU = "q-Quit, c-Choose Taxi, d-Drive Taxi\n Input:"
def main():
taxis = [Taxi("Prius", 100), SilverServiceTaxi("Hummer", 150, 2), SilverServiceTaxi("Limo", 150, 3)]
taxi = None
bill = 0
user_input = input(... |
34a8d045b8b194670396993143d998ff0ffc8605 | Kyle-Everett10/cp_1404_pracs | /practical_3/oddName.py | 562 | 4.125 | 4 | """Kyle"""
def main():
name = input("Enter your name here: ")
while name == "":
print("Not a valid name")
name = input("Enter your name here: ")
frequency = int(input("How frequent do you want the names to be taken?: "))
print(extract_characters(name, frequency))
def extract_characters... |
18f967ece44b293dd5cca6e07d9b5f869559f124 | Kyle-Everett10/cp_1404_pracs | /practical_2/files.py | 644 | 3.796875 | 4 | user_name = input("Enter your name please: ")
file_with_names = open("name.txt", "w")
print(user_name, file=file_with_names)
file_with_names.close()
file_to_read_from = open("name.txt", "r")
read_name = file_to_read_from.readline()
print("Your name is: ", read_name)
file_to_read_from.close()
number_file = open("numbe... |
499ae570b97d1327082f26b17007d31a99ad9575 | tanacchi/practice | /python/game/othello/board.py | 2,047 | 3.78125 | 4 | class BoardInfo(object):
def __init__(self, row: int, col:int, width: int, height: int):
self.row, self.col = row, col
self.width, self.height = width, height
self.row_unit, self.col_unit = height // row, width // col
def __str__(self):
return '<row: {}, col: {}>\n<height: {}, w... |
5536d5bf0689156156e257522381bc2122351be7 | thinpyai/python-assignments | /python_small_exercises/sum_matix_crosses.py | 745 | 4.28125 | 4 | def sum_all_cross(matrix):
"""
Sum all cross direction of matrix.
matrix: input integer value in list.
"""
sum = sum_cross(matrix)
reversed_matrix = list(reversed(matrix))
sum += sum_cross(reversed_matrix)
return sum
def sum_cross(matrix):
"""
Sum matrix in one cross direction.... |
de9325d80d1942fec3c7298d01dedc2bd4b864d5 | thinpyai/python-assignments | /python_small_exercises/flatten.py | 1,566 | 4.375 | 4 | # Approximate 1 ~ 1.5h
# For this exercise you will create a global flatten method. The method takes in any number of arguments and flattens them into a single array. If any of the arguments passed in are an array then the individual objects within the array will be flattened so that they exist at the same level as the... |
a48bc1e32c50f0b28b126fca091ae969bcf51a31 | thinpyai/python-assignments | /python_small_exercises/array_differ.py | 533 | 3.828125 | 4 | def array_diff(a: list = [], b: list = []) -> list:
"""
Diff two arrays by removing same iteams of b from a
Args:
a (list, optional): List of items. Defaults to [].
b (list, optional): List of items_. Defaults to [].
Returns:
list: Remaing items in a after removing sam... |
a8e086625443083aa2ec1dc324fabacd23f369b3 | Aaloknry/Face-RecogniZer | /askname.py | 835 | 3.671875 | 4 | from tkinter import *
import os
from PIL import ImageTk, Image
def saveimg():
global val
val = name.get()
print(val)
id.destroy()
id = Tk()
id.title("Enter Your Name")
name = StringVar()
img = Image.open("face.png")
img = ImageTk.PhotoImage(img)
Label(id, text ='Password Manager... |
f4291c2cc1fb648f6cb11ceb8dd5de3fb8d078ed | CarlosArro2001/Little-Book-of-Programming-Problems-Python-Edition | /cards.py | 1,100 | 4.375 | 4 | #...
#Aim : Write a program that will generate a random playing cards , when the return return is pressed.
# Rather than generate a random number from 1 to 52 . Create two random numbers - one for the suit and one for the card.
#Author : Carlos Raniel Ariate Arro
#Date : 09-09-2019
#...
#... |
10fb5b41fe44b01202e46f0650d868bee1352075 | periwinkleFTW/python-unittest | /first_challenge.py | 535 | 3.90625 | 4 | """
Coding challenge #1
This counter function purpose is tho count how many english letters does your contain.py
After writing your tests, develop the counter function as needed to pass all your tests.
"""
def counter(name):
if name is None:
raise Exception('You cannot input None values')
name = nam... |
3e9a48414d26d8458dc9271c8e652beb163c6cae | shiyuan1118/Leetcode-in-Python | /Leetcode in Python/linked lists/Merge two sorted Linked List(21).py | 667 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 24 20:31:38 2021
@author: baoshiyuan
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.