blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b958db92193f988a09ff1a5ca3ba31f6b4951ff1 | clevercoderjoy/Competitive-Coding | /CN_getProductArrayExceptSelf.py | 2,143 | 3.734375 | 4 | # Product Of Array Except Self
# Difficulty: EASY
# Avg. time to solve
# 26 min
# Problem Statement
# You have been given an integer array/list (ARR) of size N.
# You have to return an array/list PRODUCT such that PRODUCT[i] is equal to the product of all the elements of ARR except ARR[i]
# Note :
# Each product can c... |
07c55744e7dbf005e787fc4957c00f9920be5ad4 | nirajann/tkinter | /tkinter class/messagebox.py | 343 | 3.796875 | 4 | from tkinter import *
from tkinter import messagebox
root = Tk()
def popup():
response = messagebox.askyesno("this is my popup","hello world")
if response == 1:
Label(root,text="clicked yes").pack()
else:
Label(root,text="clicked NO").pack()
Button(root,text="popup",command=popup).pac... |
823da841baad8dc729c34cf8da0b1c025a8b27eb | kealaschultz/python-challenge | /PyBank/main.py | 1,827 | 3.75 | 4 | import csv
import os
count = 0
budget_csv = os.path.join("budget_data.csv")
print("Financial Analysis")
print("-----------------------")
#Total Months
with open(budget_csv, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
for row in csvreader:
count += 1
print("Total Months: " + str(co... |
ebbe6dde0481bbdc352ad63edb7a79e37dd8359f | GersonCity/Python | /ATBS/chap2.py | 1,441 | 4 | 4 | # print('Hola mundo')
# print('Cual es tu nombre?')
# myName = input()
# print('Es bueno conocerte, ' + myName)
# print('El largo de tu nombre es:')
# print(len(myName))
# print('Cual es tu Edad?')
# myAge = input()
# print('Tu tendras ' + str(int(myAge) + 1) + ' en un año mas.')
# while True:
# print('Who are you... |
1acce405cb75cafefea069f696a9e50b43ca0c8b | GersonCity/Python | /ATBS/chap4_PracticeProjects.py | 2,125 | 4.0625 | 4 | # Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item
spam = ['apples', 'bananas', 'tofu', 'cats', 'dogs']
# Solucion mia
def commaCode(formatLista):
popped = formatLista.pop() # toma el ultimo... |
bc40b83252453c729c38350845c4c8873b99c3c8 | GersonCity/Python | /begginer/Numbers.py | 749 | 4.40625 | 4 | # type = Muestra el tipo de formato del numero
# num = 3.14
# print(type(num))
# Arithmetic Operators:
# Suma: 3 + 2
# Resta: 3 - 2
# Multiplication: 3 * 2
# Division: 3 / 2
# Floor Division: 3 // 2
# 10/4=2,5 <----normal division
# 10//4=2 <----floor division
# it basically cuts of the part a... |
c80365b188688215cb76c8556c00c610615b87c1 | panghanwu/matplotlib_demo | /05_legend.py | 403 | 3.515625 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2 - 4
plt.figure()
l1, = plt.plot(x, y1, color='red', linewidth=1., linestyle='--', label='Line')
l2, = plt.plot(x, y2, label='Curve')
# add legend
plt.legend(handles=[l1,l2,], loc='best')
plt.xlim((0,3))
plt.ylim((... |
c378e4cdb860de2c9c32cc8fc85169f3d495bb32 | jisshub/python-development | /myPracticeProblems/oops.py | 252 | 3.796875 | 4 | # oops
class Parrot:
# class variable
species = "bird"
# instance variables
def __init__(self, name, age):
self.name = name
self.age = age
obj = Parrot("blue", 22)
print(f"{obj.name} and {obj.age}, {Parrot.species}")
|
45f217c93577b716b03633bd597c1c21c38570be | jisshub/python-development | /pythonAdvanced/newFiles.py | 554 | 3.8125 | 4 | # python files
with open("./contents.txt", "r") as file:
# print(file.read())
# readingeach line at a time
# use end attribute to remove unwanted lines
# f_cont = file.readline()
# print(f_cont, end="")
# f_cont = file.readline()
# print(f_cont, end="")
# iterating over contents
# ... |
bc184183df5c18d9767a6e01e129f7b7150489e8 | jisshub/python-development | /myPracticeProblems/python_list.py | 617 | 4.15625 | 4 | # list slicing
myList = ["a", 4, True, "b"]
print(myList[1:])
print(myList[::1])
print(myList[::-1])
print(myList.append(5))
print(myList)
print(myList.extend([7, 3, 33]))
print(myList)
# delete/ remove from list
# del myList
print(myList)
# using remove method
print(myList.remove(True))
print(myList)
# pop metho... |
303dde43830705e4d25b5fafed60024d7b567c40 | jisshub/python-development | /advanced_oops/encapsulation2.py | 774 | 3.78125 | 4 | class Rectangle:
def __init__(self, length, breadth, height):
self.__length = length
self.__breadth = breadth
self.__height = height
def set_length(self, len_value):
self.__length = len_value
def get_length(self):
return self.__length
def set_breadth(self, br_v... |
9d20f2ee5d8417449857ce792c8246c0ebf2b13f | jisshub/python-development | /myPracticeProblems/bankProblem.py | 1,711 | 3.9375 | 4 | class MyBank:
initialBal = 5000
holderacc = None
holdername = None
def __init__(self, hello):
self.hello = hello
print("1. Add Account" '\n' "2. deposit cash" '\n' "3. withdraw cash"
'\n'"4. Bank Statement" '\n' "5. Exit")
def options(i):
if i == 1:
... |
a1f5f5724e74715987bdf5a761f7d5816cdceb03 | jisshub/python-development | /myPracticeProblems/phoneBook.py | 664 | 3.609375 | 4 | # problem 3
class MyPhoneBook:
def __init__(self):
self.limit = None
self.dict = dict()
def addPhones(self):
self.limit = int(input("Enter total: "))
while self.limit > 0:
user_name = input("Enter user name: ")
self.dict[user_name] = int(input("Enter Phon... |
4e4a180aef38b4795e4d6d999043404f5de8daa9 | jisshub/python-development | /myPracticeProblems/nested_list.py | 1,064 | 4.25 | 4 | # Given the names and grades for each student in a Physics class of students, store them in a nested list
# and print the name(s) of any student(s) having the second lowest grade.
namesGrades = [['jissmon', 20], ['ajith', 50], ['nikhil', 40]]
print(namesGrades)
print(namesGrades[2][0])
# print(namesGrades[1])
# pri... |
988b5800e29191f89949c19fadadc9f633d1fa8b | innovationcode/Queue_Stack_Questions | /Queue_using_stack.py | 1,476 | 4.25 | 4 | """Implement Queue using Stack"""
# Need Stack class
class Stack:
def __init__(self):
self.stack = []
def push(self, data):
self.stack.append(data)
def pop(self):
if len(self.stack) > 0:
return self.stack.pop()
def length(self):
return len(... |
7c86fdadfed4131b9e774408aa4ddde431f5ddb4 | sudarshan1754/practPy | /Inhert.py | 1,425 | 4.28125 | 4 | __author__ = 'sid'
# An example of class inheritance
class SchoolMember:
def __init__(self, id, name, age):
self.id = id
self.name = name
self.age = age
print "Intializing School Member %s" % self.name
def display(self):
print "Id: %s Name: %s Age: %s" % (self.id, self... |
dceb32c699e85835674104b39dce69cb184d9c4b | RonghuiZhou/pdf_merge | /pdf_merge.py | 544 | 3.609375 | 4 | import glob
# Scan current directory for a list of all PDF files
pdf_files=glob.glob("*.pdf")
# print the list of PDF files
print(pdf_files)
# merge pdf
from PyPDF2 import PdfFileReader, PdfFileMerger
result_pdf=PdfFileMerger()
for pdf in pdf_files:
with open(pdf,'rb') as fp:
pdf_reader=PdfFile... |
c9057657602109e21c0ea088d18d65312e499765 | hhyojin/practice | /PythonP/control statement/for.py | 697 | 3.734375 | 4 | # for waiting_no in [0,1,2,3,4]:
# print ("대기번호 : {0}".format(waiting_no))
# for waiting_no in range(5): # 0~4
# print ("대기번호1 : {0}".format(waiting_no))
# for waiting_no in range(1,6): # 1~5
# print ("대기번호1 : {0}".format(waiting_no))
#출석번호 1, 2, 3, 4 앞에 100 붙이기로 함. 101, 102, 103
# student = [1,2,3,4,... |
8d91f1c317c1b5380540c88831a99032cceac938 | web-at-berkeley/education-sample-starter-code | /Database Development I/before-class-material/todo.py | 2,112 | 3.5 | 4 | from flask import Flask
from flask import jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///todo.db'
db = SQLAlchemy(app)
# m = Todo("buy milk.")
# print(m)
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = ... |
a2939350db8489e6be6fae07742f6e7356cb4a1b | fengrenxiaoli/Mypython | /设计模式/simplefactory.py | 1,414 | 3.859375 | 4 | #/usr/bin/env python3
#-*- coding:utf-8 -*-
class Operation(object):
'''定义操作父类'''
def getresult(self):
pass
class Add(Operation):
'''加'''
def getresult(self):
result=self.numberA+self.numberB
return result
class Sub(Operation):
'''减'''
def getresult(self):
res... |
2abf74bc6f4dfebb4094492b1254bafd755c6f0b | fengrenxiaoli/Mypython | /练习实例/练习实例4.py | 451 | 3.703125 | 4 | #!/usr/bin/env python3
#-*- coding:utf-8 -*-
'''
输入某年某月某日,判断这一天是这一年的第几天
'''
year=int(input('year:'))
month=int(input('month:'))
day=int(input('day:'))
x=[31,28,31,30,31,30,31,31,30,31,30,31]
sum=0
if month>13 or month<0:
print('month is error')
else:
for i in range(month):
sum+=x[i]
sum+=day
... |
995172ceac52aa64b512775d68ac31d7959f1978 | douglasgoodwin/PCV | /pcv_book/camera.py | 1,810 | 3.5625 | 4 | from numpy import *
from scipy import linalg
class Camera(object):
""" Class for representing pin-hole cameras. """
def __init__(self,P):
""" Initialize P = K[R|t] camera model. """
self.P = P
self.K = None # calibration matrix
self.R = None # rotation
self.t = Non... |
5cd1bcee854623ab5391b2f38b66ed803e9394d4 | douglasgoodwin/PCV | /examples/unsharp.py | 649 | 3.609375 | 4 | from PIL import Image
from pylab import *
from scipy.ndimage import filters
"""
This is an example of unsharp masking using Gaussian blur.
"""
# load sample eye image from http://en.wikipedia.org/wiki/Unsharp_masking
im = array(Image.open("unsharpen.jpg").convert("L"), "f")
# create blurred version of the image
sig... |
e5ca2d9ffe9571865c12daf41a4da621ca833068 | VishalKanakamamidi/AssociationRuleMining | /apriori.py | 5,068 | 3.671875 | 4 | #Importing essential libraries
from itertools import combinations
#Reading the dataset(groceries.csv) into groceries
groceries = open('./groceries.csv')
#Minimum support
min_support = 250
#Minimum confidence
min_confidence = 1.0
#Preprocessing of the data
data = []
for line in groceries:
data.append(line.split... |
b8436962bbdaf6ec31050b8bde364d3b7d39c37b | armooey/Algorithms | /Sorting Algorithms/Quick Sort/QuickSort.py | 467 | 3.53125 | 4 | def partition(arr, l, h):
pi = arr[h]
i = l - 1
for j in range(l, h):
if arr[j] < pi:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[h] = arr[h], arr[i + 1]
return i + 1
def quick_sort(arr, l, h):
if l < h:
pi = partition(arr, l, h)
... |
274106ccc7bcdfceda57518985962cd2a44cabb6 | bodutton/automate-your-page | /html_generator.py | 2,629 | 3.953125 | 4 | def generate_lesson_HTML(lesson_title, lesson_content):
html_text_1 = '''
<div class="lesson-title">
''' + lesson_title
html_text_2 = '''
</div>
<div class="lesson-content">
''' + lesson_content
html_text_3 = '''
</div>
</div>'''
full_html_text = html_text_1 + html_t... |
0133e3e0e86e9bf4153c511b1f2c62ed3a434f42 | Ammad-ud-din/paint_factory_puzzle | /paintfactory/order_services/customer_order.py | 1,848 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Paint Factory Puzzle
# Author: mu.ammad.ud.din@gmail.com
# Last Update: 09 March 2019
# License: MIT
class CustomerOrder(object):
def __init__(self, orderLocation):
self.orderLocation = orderLocation
self.orderInfo = None
def readOrde... |
3070219ce5344c184e98fba8757fe3d592c11593 | Smile-L/leetcode | /leetcode/Valid_palindrome.py | 413 | 3.5625 | 4 | import string
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s)<2:return True
s = s.lower()
s = s.replace(' ', '')
s = "".join([c for c in s if c not in string.punctuation])
l = len(s)/2
for ... |
3d048b97afa0dc362771f4ace7049035986f617f | zhiwilliam/geekcoding | /src/1-500/148/SortList.py | 1,184 | 3.953125 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1: return l2
if not l2: return l1
head = ListNode(0)
move = head
while l1 and l2:
if ... |
82a7738a5aefd97189d6ae242442acdd971cce57 | zhiwilliam/geekcoding | /src/1-500/028/Findstr2.py | 237 | 3.703125 | 4 | class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle not in haystack: return -1
if not needle: return 0
return [i for i in range(len(haystack)) if haystack[i:].startswith(needle)][0]
|
50a3a8c4599b8f43c5b6e488964d58950ef35a79 | zhiwilliam/geekcoding | /src/1-500/073/IntuitiveSolution.py | 574 | 3.515625 | 4 | from typing import List
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
zeros = [(row_idx, col_idx) for row_idx, row in enumerate(matrix)
for col_idx, value in enumerate(row) if n... |
ce623d4e544019851d5f95b87b232ba143ff58b7 | zhiwilliam/geekcoding | /src/1-500/019/RemoveNth.py | 712 | 3.71875 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
root = ListNode(0)
root.next = head
fast, slow, pre = root, root, root
while n - 1:
fast = fast.next
... |
ea24e7d8ae12c937cec015c89fdbebb08c7e2fe1 | zhiwilliam/geekcoding | /src/1-500/405/convert_to_hex.py | 777 | 3.546875 | 4 | class Solution:
def toHex(self, num: int) -> str:
if num == 0: return '0'
chars = '0123456789abcdef' # a string that serves as a map of index => hex value for index in 0 ... 15
result = ''
i = 0
while i < 8 and num != 0: # build the result string one character (4 bits) at a t... |
731f9e7c92a7414f805784e74108c221df504087 | zhiwilliam/geekcoding | /src/1-500/098/ValidateBinarySearchString.py | 861 | 3.71875 | 4 | from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
return self.valid(root, float('-inf'), float('inf'))
def valid(self, root, min, max):
if n... |
be21ebb9e43e9cb4491fc2a5870e6edb0a4d69f0 | zhiwilliam/geekcoding | /src/1-500/055/JumpGame.py | 323 | 3.609375 | 4 | from typing import List
class Solution:
def canJump(self, nums: List[int]) -> bool:
reach = 0
for i, num in enumerate(nums):
if i > reach:
return False
reach = max(reach, i + num)
return True
solution = Solution()
print(solution.canJump([2,3,1,1,4]... |
7ad851d9fbbd79e0671561f4c08461b89597ffac | zhiwilliam/geekcoding | /src/1-500/059/SpiralMatrixII.py | 1,027 | 3.828125 | 4 | from typing import List
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
matrix = [[1 for i in range(n)] for i in range(n)]
left, right, top, bottom = 0, n, 0, n
count = 1
while left < right:
x, y = left, top
while x < right:
... |
b40b62a0dee14b78796fc9aecb7e485551d3d60f | zhiwilliam/geekcoding | /src/1-500/117/Solution2.py | 838 | 3.703125 | 4 | class Solution:
def findNextChild(self,root):
while root.next:
root = root.next
if root.left:
return root.left
if root.right:
return root.right
return None
def connect(self, root: 'Node') -> 'Node':
if not root:
... |
b0560a99ecd1d2d462356ad376c28a11dffe2a2e | zhiwilliam/geekcoding | /src/1-500/100/SameTree.py | 767 | 3.828125 | 4 | from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q: return True
if not p or not q: return False
return p.val ... |
06d2b9797ff4db66f53503bdb6116af04a21baeb | zhiwilliam/geekcoding | /src/1-500/097/InterLeaving.py | 1,599 | 3.75 | 4 | class Solution:
def helper(self, s1: str, s2: str, s3: str, p1: int, p2: int, p3: int):
if p1 < 0 and p1 < 0 and p3 < 0:
return True
# base case for pointers
if p3 < 0 and (p1 >= 0 or p2 >= 0):
return False
if (p1, p2) not in self.memo:
ans = Fa... |
b0f87e85fcd75451c535cb95ba3e0c1f5d507ea1 | zhiwilliam/geekcoding | /src/1-500/433/MinGeneMutation.py | 710 | 3.53125 | 4 | from typing import List
from collections import deque
class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
bank = set(bank)
if end not in bank:
return -1
queue = deque([(start, 0)])
while queue:
cur_str, distance = queue.pople... |
8616f50e35712ee5e176cf72c2de93a89b4b78e4 | EricaLem/project1 | /import.py | 1,010 | 3.53125 | 4 | import csv
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
engine = create_engine(os.getenv("DATABASE_URL"))
#// create a db engine; an object created by sqlalchemy which will manage connections to db
db = scoped_session(sessionmaker(bind = engine))
#// db is ... |
74b1d9f35e85e86bc59781f491ecdd0c675afb14 | ps9610/python-web-scrapper | /02-01/built_in_function.py | 598 | 3.921875 | 4 | #첫 시간부터 사용했던 print()도 함수!
#함수로 적용하고자 하는 기능을 작성해서 계속 반복할 수 있음
#print(), type(), lef()같은 function은 built-in-function
#built in function끼리 조합해서 사용도 가능함
print(len("dsfeadfsfeaefse"))
#>>>15
#많이 쓰이는 빌트인 함수 | int() bool() str() float()
#int() / type을 바꿔줌
age = "18"
print(type(age))
#>>><class 'str'>
n_age = int(age) ... |
f3885c2507938e66973e4df54721dbb8dac82486 | ps9610/python-web-scrapper | /02-01/keyword_argument.py | 1,022 | 4.21875 | 4 | #입력 인수의 갯수와 대입할 값의 갯수가 같지 않을 수도 있을까?
#keyword argument
#인자의 갯수, 인자 위치에 상관 없이 인자 자체에 값을 줌
#아주 많이 쓰이는 방법
#인자가 아주 많을 때, 순서대로 입력하지 않아도 된다는 것이 가장 큰 장점
def plus(a, b):
return a - b
result = plus(b=30, a=1)
print( result ) #>>>-29
#문자열로 결과값 받기
def say_hello(name, age):
return f"Hello {name} you are {a... |
06658c9bdad780b7d5c989898abedeba98257bfc | SmetjukVlad/HomeWork | /HomeWork_Urok5_Zadanie0.py | 318 | 3.71875 | 4 | def inp():
line = input('Enter line: ')
return line
def search(x):
dict = {}
for i in x:
if i in dict:
dict[i] += 1
else:
dict[i] = 1
print('Max value is {}, num: {}'.format(*max(dict.items(), key = lambda x: x[1])))
line = inp()
search(line) |
4ba0dc38874a227d7d07dd09ffd97e178534708b | SmetjukVlad/HomeWork | /HomeWork_Urok4_Zadanie1.py | 374 | 3.75 | 4 | import string as st1
num = input('Enter word: ')
signs = st1.punctuation
index = signs.find('_')
signs_new = signs[0:index] + signs[int(index+1):len(signs)]
counter = 0
for i in signs_new:
if i == num[0]:
counter += 1
if counter == 0:
print('This word {} is identifier'.format(num))
else:
... |
2ec9d4b5540d19240fc62335673b522218d30122 | Kartturi/CodewarsPython | /temp.py | 212 | 3.875 | 4 | n = 40
if n % 2 != 0:
print('Wierd')
if n % 2 == 0 and n <= 5 and n >= 2:
print('Not Wierd')
if n % 2 == 0 and n <= 20 and n >= 6:
print('Wierd')
if n % 2 == 0 and n > 20:
print('Not Wierd')
|
dc69fcbf272dcc2fdd99e056b2dca929c58244f7 | Kartturi/CodewarsPython | /ExpressionAddOperators.py | 653 | 4.3125 | 4 | # Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.
# Example 1:
# Input: num = "123", target = 6
# Output: ["1+2+3", "1*2*3"]
# Example 2:
# Input: num = "232", target = 8
... |
99aba7baa1ad394c456c6c368e16a481bd3336ae | HyoungSunChoi/Coding-Test | /알고리즘/2. 선택정렬.py | 754 | 3.96875 | 4 | '''
2. 선택정렬 (selection sort) 란?
- 1. 주어진 데이터 중, 최소값을 찾음
- 2. 해당 최소값을 데이터 맨 앞 위치한 값과 교체
- 3. 맨 앞의 위치를 뺀 나머지 데이터를 동일한 방법으로 교환
'''
def selection_sort(data):
for idx in range(len(data) - 1): # 1을 빼야하는 이유 -> 전체 횟수는 총 길이 -1 번만큼 반복한다
lowest = idx
for idx2 in range(idx + 1, len(dat... |
1bc61d1b5a666589dd45ef285507e2127c21f71f | HyoungSunChoi/Coding-Test | /프로그래머스 코딩테스트/LEVEL 2/4. 124 나라의 숫자Ver2.py | 159 | 3.734375 | 4 | def solution(n):
num = ['1','2','4']
answer=""
while n>0:
n-=1
answer = num[n%3] + answer
n//=3
return answer |
6e66f3a2f6d21344382c2957f1177f3424e0c87e | HyoungSunChoi/Coding-Test | /알고리즘/1. 버블정렬.py | 822 | 3.921875 | 4 | # 가장 끝자리에 있는 원소 제외하고 정렬시키는 방법
def bubble_sort(data):
for idx in range(len(data)-1):
for idx2 in range(len(data)-idx-1):
if data[idx2]<data[idx2+1]:
data[idx2],data[idx2+1]=data[idx2+1],data[idx2]
# 조금더 개선된 알고리즘 ( swap 이 일어나지 않았다면? 바로 종료)
def bubble_sort_ver2(data):
... |
c20fbcc5e5f78383bab50e3cca82463682db741c | HyoungSunChoi/Coding-Test | /프로그래머스 코딩테스트/LEVEL 1/6. 음양 더하기.py | 290 | 3.53125 | 4 | def solution(absolutes, signs):
answer=0
for x in range(len(signs)):
if signs[x]:
answer+=absolutes[x]*1
else:
answer+=absolutes[x]*(-1)
return answer
absolutes=[4,7,12]
signs=[True,False,True]
print(solution(absolutes,signs)) |
dea4553edea13c14e42abc48ce9fbb009a0280b3 | tacticalcheese/Andras89 | /Python/Practice/Basic.py | 442 | 3.890625 | 4 | myStr = "Hello"
myInt = 4
myFloat = 5.2
myList = [1, 2, 3, 'Hello']
myDict = {'a': 1, 'b': 2, 'c': 3}
print(type(myStr), myStr)
print(type(myInt), myInt)
print(type(myFloat), myFloat)
print(type(myList), myList)
print(type(myDict), myDict)
print(myList[3])
greetings = myStr + ' World'
print(greetings)
peoples = ['... |
c7200585e74eb8d680093134aed015593bf0921d | gengar93/calculator | /home.py | 8,157 | 3.6875 | 4 | import tkinter as tk
import functools
from menu_bar import MenuBar
from custom_buttons import NumberButton, OperatorButton, SpecialButton
win = tk.Tk()
win.resizable(False, False)
win.title("Simple Calculator")
win.config(background='#243313')
# marked true once equals has been pressed (and answer has been displayed)... |
d4e11f1569635abf350f64b0a0b1e5a12d3753c5 | MihailMecetin/killingCode | /ex4.py | 723 | 3.59375 | 4 | spaceships = 200
cargo_space_in_a_spaceship = 50.0
space_captains = 60
passengers = 180
spaceships_not_driven = spaceships - space_captains
spaceships_driven = space_captains
spaceship_capacity = spaceships_driven * cargo_space_in_a_spaceship
average_passengers_per_spaceship = passengers / spaceships_driven
print("Th... |
b95db6d75510c234819280db10c7c0c49955b7fc | RaulAlvaradoT/AlgoritmosSistemas | /ago-dic-2020/Jesús Raúl Alvarado Torres/Practica2/Practica2.py | 395 | 3.515625 | 4 | lista_numeros = input().split()
n=lista_numeros[0] #Numero de problemas = n
m=int(lista_numeros[1]) #Minutos para hacer la tarea = m
i = 0
np = 0 #np = numero de problemas
lista_minutos = input().split()
problemas = sorted(lista_minutos) #Ordena de menor a mayor
while i < m:
i = i + int(problemas[i])
... |
995987a479d6cd4658d62a80f761b3b847ecd99a | djeidot/NeutronP | /format.py | 468 | 3.6875 | 4 |
def center(text, length, rightAligned):
spaces = length - len(text)
if spaces <= 0:
return text[0:length]
else:
spacesLeft = int(spaces / 2)
spacesRight = int(spaces - spacesLeft)
if rightAligned:
return spacer(spacesRight) + text + spacer(spac... |
102a17a13c42fda94e316d520e3cd8d337dcf1c3 | mmenavas/memory-game-cli | /app.py | 846 | 3.6875 | 4 | # app.py
import click
import time
from Game import Cards
@click.command()
def play():
"""Simple program that tests your memory skills."""
is_game_over = False
click.clear()
click.echo('How many different cards do you want to play with?')
count = int(click.prompt('Enter a number no greater than 20... |
6be581d7b560cf63e8d472b2c4a506038584275a | jaywrye/CZ1003 | /main.py | 1,637 | 4.28125 | 4 | import datetime
import menuDB
day = datetime.datetime.today().weekday() # Get current day of the week: Monday = 0, Tuesday = 1, Wednesday = 2 ... Sunday = 6
todaysMenu = {} # Empty dictionary to store menu
... |
136d032a5a0af6d5514bfa77c199029025d38284 | KuangyeChen/learning-and-exercises | /cracking_the_coding_interview/1_arrays_and_strings/1.1_is_unique.py | 366 | 3.578125 | 4 | def solution_a(s):
chars = set()
for char in s:
if char in chars:
return False
chars.add(char)
return True
def solution_b(s):
chars = [False for _ in range(48)]
for char in s:
char_int = ord(char) - ord('a')
if chars[char_int]:
return False
... |
49598d04025c79b67e75e1606332b86a421bb569 | KuangyeChen/learning-and-exercises | /cracking_the_coding_interview/1_arrays_and_strings/1.9_string_rotation.py | 144 | 3.765625 | 4 | def is_substring(s1, s2):
pass
def solution(s1, s2):
if len(s1) != len(s2):
return False
return is_substring(s1, s2 + s2)
|
9144262ff0a855ea30e85ad5f02ae234bd925a2d | mtaggart/LPTHW | /ex19.py | 1,195 | 4.625 | 5 | # this section defines the function in pink, starting with variables and text to print
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"... |
447c8e5909b7f210252736ca1d13fd96544d0065 | mtaggart/LPTHW | /ex31.py | 1,879 | 3.984375 | 4 | print "You enter a dark room with two doors. Do you go through door #1 or door #2?"
door = raw_input("> ")
if door == "1":
print "There's a giant bear here eating a cheese cake. What do you do?"
print "1. Take the cake."
print "2. Scream at the bear."
bear = raw_input("> ")
if bear == "1":
print "The bear ... |
270a29fec093e2d4caa41303cb26a991a54d9b7e | AlexGrig42/Python-Coursera | /8_4/8_4_t.py | 237 | 3.984375 | 4 | # romeo.txt
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
tmp_list = line.split()
for word in tmp_list:
if word not in lst:
lst.append(word)
lst.sort()
print(lst)
|
b6288dfe4529ffd42c5aa79e6c6e328c28b12c31 | angstyloop/MyProjects | /algorithms/python/Between.py | 445 | 4.09375 | 4 | # Between(A,x,y) returns the number of elements in that are greater than x and less than y.
def Between(A,x,y):
i=0
j=len(A)-1
while i<=j:
if A[i]<=x:
i+=1
elif A[j]>=y:
j-=1
else:
break
return j-i+1
from sys import argv
try:
x=int(argv[... |
79415b4becc87e30d39c511a0404638996813e88 | MichaelZ1853/Peer-to-Peer-Networks | /CECS327Lab1/server.py | 5,218 | 3.578125 | 4 | #CECS Lab Assignment 1
#Michael Zaragoza
#This is the server side of the program/server also acts as a client
import socket
import ipaddress
import os
import pathlib
from time import sleep
from Node import Node
#Reads the file from a directory and return the file data
def readFile(directoryPath, file):
with open(... |
673d95ef0de4f3744d9c8885e4f85b2d4cec0d81 | cossa0803/heeandho | /snake_dice_game.py | 3,085 | 3.53125 | 4 | import random
class Tile:
def __init__(self, num):
self.num = num
if self.num == 4:
self.num = 16
elif self.num == 8:
self.num = 12
elif self.num == 18:
self.num = 38
elif self.num == 20:
self.num = 74
... |
a94dea9590c37c13aacaafb488c71af5bba27f42 | lucasoooooo/RecipeFinder | /recipesFinder.py | 1,773 | 3.953125 | 4 | #Program will read list of ingredients recommend
# possible meals user could make
# 8/27/2019 By Lucas Balangero
#Errors: dictonary if recipes includes "\n" in titles and ingredients
#Working on: removing the error "\n"
#Missing: check what recipe to give the user based on his choices
# and test
... |
8d245919f2f4928e5dace3d9146aae4192b2b805 | ezquire/AdventOfCode | /2018/5/5.py | 814 | 3.5625 | 4 | from collections import Counter
import re
line = open("5.in", "r").read()
charlist = Counter(line.lower()).most_common()
def react(line, char):
res = []
for i in range(len(line)):
if not res:
res.append(line[i])
elif char != None and (line[i] == char.lower() or line[i] == char.uppe... |
3e9cea849cf55b6501c5f1201d4144a92ebfb23a | Nickhil-Sethi/Simulations | /data_structures/string/parity_checker.py | 503 | 3.890625 | 4 | from stack import stack
input = '()()((()()())()())))()))()))'
def parity_checker(my_str):
if not isinstance(my_str, __builtins__.str):
raise TypeError('input must be type str')
my_str = list(my_str)
s = stack()
balanced = True
index = 0
while index < len(my_str) and balanced:
if my_str[index] == '(':... |
1b197f7b305e86aa2fd4d6f2928065396facd65b | jspigner/calculator | /calculator.py | 440 | 4.15625 | 4 | # Create a calculator
# Define
def calculator(num_1, num_2, op):
result = 0
if op == "+":
result = num_1 + num_2
elif op == "-":
result = num_1 - num_2
elif op == "*":
result = num_1 * num_2
elif op == "/":
result = num_1 / num_2
print(f"{num_1} {op} {num_2}... |
e8059151244f0d11f1f26b258845fb53fa7e0720 | pedersee7734/cti110 | /P4HW3_Factorial_Erik,Pedersen.py | 398 | 4.21875 | 4 | #Erik Pedersen
#CTI-100
#P4HW3-Factorial
#5 March 2018
userInteger = int (input("Please enter a nonnegative number: " ) )
while userInteger <1:
userInteger = int ( input ("Please enter a positive number:" ) )
factorial = 1
for currentNumber in range(1, userInteger + 1):
factorial = factorial ... |
8da2a22ae800edbcf37504210445648fd363507e | pedersee7734/cti110 | /P2T1_Sales_Prediction_Erik Pedersen.py | 337 | 3.828125 | 4 | # CTI-110
# P2T1 - Sales Prediction
# Erik Pedersen
# 3 Feb 2018
#Get the projected sales.
total_sales = float(input('Enter the total sales: '))
# Calculate the profit as 23 percent of total sales.
annual_profit = total_sales * 0.23
# Display the profit.
print ('The annual profit is $', format(annual_pro... |
eddac588e0f961041a3ed565a81ade0d39498a78 | ujrc/RealPython | /Chapter8/election.py | 746 | 3.734375 | 4 | #Probability of winning election
from __future__ import division
from random import random
totalA=0
totalB=0
trials=10000
for trial in range(0,trials):
winA=0
winB=0
# probability of both A and B in region 1
if(random()< .87):
winA+=1
else:
winB+=1
#probability of both A and B n region 2
if random()< ... |
7cc67ddf36e89616b8402635ace171ba2c685ee4 | ujrc/RealPython | /Chapter9/capital_city_loop.py | 419 | 3.953125 | 4 |
#Capital_list
from capitals import capitals_dict
import random
def guess_capital(state, capital):
while True:
guess = raw_input("Name the capital of {} ".format(state.upper()))
if guess == (capital.upper()):
print "That's correct."
break
elif guess =="exit":
print "Goodbye!"
break
State = ... |
b64bcf5cd0363e83e51e257a5fce65d0b061f4da | ujrc/RealPython | /Chapter2/Chapter2Exercises.py | 331 | 3.515625 | 4 |
#Exercise on errors
#1
"""
my_string= "This script has syntax error"
print my_string)
#2
my_text="this script has runtime error
print my_text
"""
# Save code in a script and run it
print "Use print to display text on screen. "
Text="This string is stored in a variable and will be displayed after using print"
pri... |
197f3265d2072316786f11a47a84f1219d04a6b1 | anjaligr05/interviewBit | /checkpoint4.1.py | 1,345 | 3.6875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @return the head node in the linked list
def subtract(self, A):
temp = A
totLen = 0
... |
a275f7effdaeffc79feed3bc1f6c315ec230d8b0 | bopopescu/luminar2 | /FuncitoinalProgramming/map-lambda-filter/DoubleTheElementsOfList.py | 91 | 3.578125 | 4 | lst=[1,2,3]
def double(num):
return num+num
lst = list(map(double,lst))
print(lst)
|
8704c025b3a0ea24381d3aa5ac011567e3ca042c | bopopescu/luminar2 | /FuncitoinalProgramming/SetCrossRelation.py | 128 | 3.75 | 4 | lst1=[1,2,3]
lst2=[4,5,6]
lst=[]
for i in lst1:
for j in lst2:
lst3 = (i,j)
lst.append(lst3)
print(lst)
|
5716f2dfd5528836a3c7ebaca8dd73e9f201598b | bopopescu/luminar2 | /LF/swap.py | 145 | 4.0625 | 4 | num1 = int(input("enter the first number"))
num2 = int(input("Enter the second number"))
num3 = num1
num1 = num2
num2 = num3
print(num1,num2)
|
1fecdcc55f4692c2269039eb998db7df7831c366 | bopopescu/luminar2 | /Collections/ListProgramming/movieRating.py | 327 | 3.9375 | 4 | movie=[[1,"half girlfriend",4,1991],[2,"mission impossible",5,1991],[3,"batman",4.5,1991]]
flag=0
for item in movie:
if(item[2]>4.5):
print(item[1], "is the movie have rating greater than 4.5")
if(item[3]==1991):
flag=flag+1
print(item,"is the movie released in 1991 and total count is :"... |
1b663c7f8f0c33f4f1c2a3ab39a4d71ed2a51085 | bopopescu/luminar2 | /Collections/ListProgramming/listHW-aptitudeQuestion.py | 296 | 3.640625 | 4 | flag=0
nlst=[]
lst=[]
# len=int(input("Enter the number"))
# for i in range(0,len):
# num = int(input("Enter the element:"))
# lst.append(num)
while (flag<3):
lst=[2,3,4]
lst.pop(flag)
mul=lst[0]*lst[1]
nlst.append(mul)
flag=flag+1
print(nlst) |
7a8ca2ca1d4f13e5b18093a6800b3e2b5299357f | AakashBelide/sample-programs | /archive/p/python/convex_hull.py | 2,845 | 3.9375 | 4 | #! usr/bin/env python
from math import sqrt
import sys
X = [ int(i.strip()) for i in sys.argv[1].split(',') if i]
Y = [ int(i.strip()) for i in sys.argv[2].split(',') if i]
assert len(X) == len(Y), 'Wrong Input'
Z = list(set((zip(X, Y))))
X = [i for i, j in Z]
Y = [j for i, j in Z]
def dist(point1, point2):
"... |
3ef71d05d07110e0c914e33a4b7d2756cc6a1260 | Kestajon/MLP_NeuralNetwork | /AnnComp.py | 16,149 | 3.78125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import math
import sys
import csv
import pickle # Used to serialise Neural_Networks for later use
# ANN Neural Network Class, adapted from stephencwelch's code on GitHub
# https://github.com/stephencwelch/Neural-Networks-Demystified
#
# This Neural_Network class has a... |
66a87137f4cd0f7ccc7566b2f4193b2484892738 | Leebz/nfsp | /leduc/deck.py | 1,637 | 3.765625 | 4 | from __future__ import print_function
from random import shuffle as rshuffle
import cardmatrix as cm
class Card:
"""A standart playing card with rank and suit."""
def __init__(self, rank, suit):
self._rank = rank
self._suit = suit
_cm = cm.Cardmatrix()
self._named_rank, self._na... |
07b0c65ddcbeb107a9a5bfce587a6a61f0ad9581 | the-brainiac/contests | /codeforces/cf_697/problem1.py | 178 | 3.5625 | 4 | from math import log2
def solve(n):
p = log2(n)
if p!=int(p):
return 'YES'
return 'NO'
for _ in range(int(input())):
n = int(input())
print(solve(n)) |
1dbbd38333e4bdfa695a265eab97dede7839959c | the-brainiac/contests | /codeforces/cf_beta_85/problem2.py | 838 | 4.0625 | 4 | N = 10**5
is_prime = [1]*N
# We know 0 and 1 are composites
is_prime[0] = 0
is_prime[1] = 0
def sieve():
"""
We cross out all composites from 2 to sqrt(N)
"""
i = 2
# This will loop from 2 to int(sqrt(x))
while i*i <= N:
# If we already crossed out this number, then continue
if ... |
0db673d7654ce689000e6219fd772d54b8e931dd | CataHax/lab3-py | /ex3.py | 492 | 4.15625 | 4 | # INPUT a string
x = input("Tell me somwthing, anything! PLEASEEEE!:")
print(x)
# contains only letters
if x.isalpha():
print("contains only letters")
if x.isupper():
print("contains only uppercase letters")
if x.islower():
print("contains only lowercase letters")
if x.isdigit():
print("contains on... |
be1cf91eacef6c3d4dd5e0d120fbb7fb4eb3bfc9 | WILDCHAP/python_study_std | /python_Project_03/tuple函数返回元组.py | 344 | 4.125 | 4 | def demo1():
print('demo1')
a = 3
#return (1, 2, a) 可以省略括号
return 1, 2, a
# 1. 直接用元组接收
a = demo1()
#a[1] = 1
print(type(a), a)
a = list(a)
a[1] = 3
print(type(a), a)
a = set(a)
print(type(a), a)
a.add(3) #set无重复
print(type(a), a)
# 2. 用多个元素接收
a, b, c = demo1()
print(a, b, c) |
902071d77bbf577875f80a7c79ef42b1780028c7 | WILDCHAP/python_study_std | /python_Project_03/id取元素存储地址.py | 260 | 3.734375 | 4 | a = 1
print("a=1", id(a))
b = a
print("b=1", id(b))
b = 2
print("a=1", a)
print(id(a))
def f(a): #传入引用地址
print(id(a))
return 2
print("函数返回a=2", f(a))
print("return 2", id(f(a)))
print("b=2", id(b))
a = {'a':1, 'b':2} |
92f29f46d37a702ba158658bbcd792b274a096f5 | lisamokhonko/python_introduction | /task_17.py | 468 | 3.734375 | 4 | #Task #17
#Написать функцию решения квадратного уравнения.
import math
def solve_quadratic_equation(a, b, c): # returns 2 values: either 2 roots, 1 root and None or 2 Nones
d = pow(b, 2) - 4*a*c
if d > 0:
return (-b + math.sqrt(d))/2/a, (-b - math.sqrt(d))/2/a
else:
if d == 0:
... |
931c2172c14225b8ff07f3d08d7154c04479e4b8 | lisamokhonko/python_introduction | /task_2.py | 332 | 4.0625 | 4 | #Task #2
#Найти результат выражения для произвольных значений a,b: (a2 + b2) % 2
import math
a = 3
b = 6
ab_result = (pow(a, 2) + pow(b, 2))%2
#Need to know how to put % sign in such string
print('Result of (a**2 + b**2)%2', 'for a = %.2f and b = %.2f is %d'
%(a, b, ab_result)) |
ba150d06f70b3492ad2f0657a61857cef46e84f8 | lisamokhonko/python_introduction | /task_16.py | 699 | 3.578125 | 4 | #Task #16
#Два поезда движутся на скорости V1 и V2 навстречу друг другу.
#Между ними 10 км. пути. Через 4 км пути первый поезд может свернуть на запасной путь.
#При заданных скоростях узнать столкнутся ли поезда.
#Предположим, что скорость поездов измеряется в км/час
def have_trains_crashed(v1, v2): # returns boolean ... |
193fd6dcbe0e7fcf31ebbc8492ba0964170205eb | lisamokhonko/python_introduction | /task_20.py | 891 | 4.25 | 4 | #Task #20
#Написать функцию для поиска разницы сумм всех четных и всех нечетных чисел среди num_limit
#случайно сгенерированных чисел в указанном числовом диапазоне.
#Т.е. от суммы четных чисел вычесть сумму нечетных чисел.
import random
def diff_even_odd(num_limit, lower_bound, upper_bound): # returns int
sum_eve... |
2fec6d59a80262cc3222e5462c8cfa3006fb34d6 | lisamokhonko/python_introduction | /task_9.py | 603 | 3.953125 | 4 | #Task #9
#Написать программу, которая преобразует имя переменной в формате snake_case в формат CamelCase.
# Для простоты считаем, что имя переменной всегда состоит из 3-х слов.
# Например: 'employee_first_name' -> 'EmployeeFirstName'
variable_snake = 'employee_first_name'
variable_list = variable_snake.split('_')
vari... |
c89dac2497d06f5ae9c705c7a374b7ff3d57713a | alannesta/algo4 | /src/python/oa/383_ransom_note.py | 428 | 3.5625 | 4 | """
https://leetcode.com/problems/ransom-note/
"""
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
result = [0] * 26
for letter in magazine:
result[ord(letter) - ord('a')] += 1
for letter in ransomNote:
result[ord(letter) - ord('a')... |
47b4cdf0320429644a7f04e69f01f749c0c76bc7 | alannesta/algo4 | /src/python/data_structure/bit_operation/287_duplicate_number_bitarray.py | 1,046 | 3.71875 | 4 | """
https://leetcode.com/problems/find-the-duplicate-number/
using bit array(map)
"""
import math
from typing import List
class BitMap:
def __init__(self, max_num):
"""
initialize bit array based on the maximum value that needs to be stored
"""
self._size = math.ceil((max_num + 1) ... |
d8845b40bda9473c5026bb51d7770038c472b3c2 | alannesta/algo4 | /src/python/data_structure/stack/71_simplify_path.py | 586 | 3.71875 | 4 | """
https://leetcode.com/problems/simplify-path/
"""
class Solution:
def simplifyPath(self, path: str) -> str:
parts = path.split('/')
stack = []
for part in parts:
if part == '..':
if stack:
stack.pop()
elif part == '.':
... |
480d67c7b8d34a36ab8487e05d94fce9b9f474bd | alannesta/algo4 | /src/python/lc_submission/198_robber.py | 1,619 | 3.890625 | 4 | """
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed,
the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and
it will automatically contact the police if two adjacent houses were broken in... |
28f7301867eedaa72b733e1a6b9e69160925f737 | alannesta/algo4 | /src/python/sort/merge_two_sorted_list.py | 1,437 | 3.96875 | 4 | """
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.... |
f7b0ed0a5654ed7d7aa57ebd89724a5d0cf841fe | alannesta/algo4 | /src/python/data_structure/heap/480_sliding_window_median.py | 4,480 | 4.15625 | 4 | """
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
Examples:
[2,3,4] , the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Given an array nums, there is a sliding window of size k which is moving ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.