blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
979093c905b804a76b375c2ea676aa26914065f0 | mozilla-campus-club-bvducoep/PYTHON-SCRIPTS | /fibonacci.py | 431 | 4.09375 | 4 | def Fibonacci(Num):
if Num==0:
print("Zero")
elif Num==1:
print("0")
elif Num < 0:
print("Invalidnumber",end=' ')
else:
fib1=0
fib2=1
fib3=0
print(fib1,end='')
print(fib2,end='')
for i in range(2,Num):
... |
483094f158f171cda5339f95d15d742ad4b7c243 | icefyre127/destruct | /bintree.py | 2,820 | 4.0625 | 4 | #!/usr/bin/python
DEBUG = True
def printer(msg):
print msg
def inc(node):
node.value+=1
print node
class Node():
def __init__(self,value):
self.value = value
self.left = None
self.right = None
#print "Node with value %s created" % value
def __str__(self):
... |
f40c2e54ae29f94e885c7f8887c73dc904cec546 | boknowswiki/mytraning | /lintcode/python/0167_add_two_numbers.py | 1,014 | 4 | 4 | #!/usr/bin/python -t
# linked list
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param l1: the first list
@param l2: the second list
@return: the sum list of l1 and l2
"""
de... |
e7c6d1b4e604380c2599c1b9f8d628f9fc92d91d | ccheraa/python-test | /files/m10_if.py | 215 | 4.1875 | 4 | a = -5
b = 0
if a > b:
print('a is bigger')
elif a == b:
print('a equals b')
else:
print('b is bigger')
if b == 0: print('b equals 0')
print("A") if a > b else print("=") if a == b else print("B") |
7954f013fcf893549a72ae5cdc416538a650646f | littlecodemaster/python_practice | /armstrong_number_or_not_not_working.py | 1,061 | 3.796875 | 4 | print("Give me a number and I will tell you if it is an armstrong number or not.")
x=int(input())
digits_in_number_list=[]
j_power_digits_in_number_list=[]
sum_of_j_power_digits_in_number_list=[]
i=x
j=0
import pdb
pdb.set_trace()
while i>1:
j=j+1
i=i/10
print(j)
for m in range(j):
digits_in_number_list.app... |
8c85d7e213f8b30a4c169405dcadd62d071e8022 | SylviaJitti/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 569 | 3.84375 | 4 | #!/usr/bin/python3
"""Unittest for max_integer
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
"""unittests for the function def max_integer(list=[])"""
def test_max_integer(self):
self.assertEqual(max_integer([1, 2, 3]), 3)
... |
4f977f9e177001f68fb64e4238401d93066de7b8 | shreyash0023/Python-Implementations | /Data Structures in Python/Queue.py | 2,605 | 4.125 | 4 | #Queue Implementation with Linked List
class Node:
def __init__(self,data=None):
self.data = data
self.next = None
class Queue_List:
def __init__(self):
self.head = Node()
self.tail = Node()
def length(self):
if self.head.next == None:
print 'EMPTY QUEU... |
9bca0db19fe2a4708a92fbbc0877222a9364f88d | vladwoguer/CODEFORCES-URI-UVA | /URI_1722.py | 628 | 3.625 | 4 | # -*- coding: utf-8 -*-
def fibo_ate_pos(pos):
valores = []
valores.append(1)
valores.append(2)
valores.append(3)
for i in range(3, pos):
valores.append(valores[i-1] + valores[i-2])
return valores
fibonaccis = fibo_ate_pos(1000)
while True:
linha = map(int,ra... |
87eafd7592f10aef918f70d832133318ce29d88d | mas-ker/pythonSecurity | /webBrowser.py | 3,103 | 3.734375 | 4 | #!/usr/bin/python
# coding:utf-8
# filename: webBrowser.py author: pengfei
'''
Building this file to learn owasp10 related knowledge.
'''
import mechanize
import logging
class WebBrowser(mechanize.Browser):
'''
This browser inherit from mechanize's Browser, and we extend it to support some
user-de... |
493c406dc4060709ae242ba2f8d2ffb1b80a13a1 | jongiles/python_data_apy | /session_02_working_files/inclass_exercises/inclass_2.23.py | 426 | 3.8125 | 4 | # 2.23: Result set: .fetchmany(). Use the cursor object to
# .execute() a SELECT query for all columns in the revenue
# table. Use .fetchmany(3) to retrieve just 3 rows, then use
# .fetchmany(4) again to retrieve the remaining 4 rows. Close
# the database connection when done.
import sqlite3
db_filename = '../se... |
1dcc7dc687624ecb4752d4db6bdec8f1050328a6 | YashMistry1406/data-structures-and-algo | /trees/binarysearch_io/medium/pruning_tree.py | 734 | 3.515625 | 4 | # class Tree:
# def __init__(self, val, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def solve(self, root):
def allZeros(root):
if not root:
return True
leftZeros = allZeros(root.left)
... |
6927c3a03a8a76591b8304f61017fb4229c182b4 | rh01/gofiles | /lcode1-99/ex23/balancedStringSplit.py | 617 | 3.609375 | 4 | class Solution(object):
def balancedStringSplit(self, s):
"""
:type s: str
:rtype: int
"""
hqueue = []
res = 0
if len(s) < 2:
return 0
i = 0
while i<len(s):
if len(hqueue) != 0 and s[i] != hqueue[-1] :
h... |
7630d75da694aa39772a76a4c3a613362e77bdc2 | SwatiTParshuramkar/Json_python | /EXample.py | 342 | 3.625 | 4 | import json
# JSON string:
# Multi-line string
data = """{
"Name": "Jennifer Smith",
"Contact Number": 7867567898,
"Email": "jen123@gmail.com",
"Hobbies":["Reading", "Sketching", "Horse Riding"]
}"""
# parse data:
res = json.loads( data )
# the result is a Python d... |
d25267f7c32405f2f90f160b6a2fe97387d60509 | Hiver77/Python_test | /Python_test/test/test_hand.py | 2,417 | 3.765625 | 4 | import unittest
from Poker.Hand import Hand
from Poker.Card import Card
class HandTest(unittest.TestCase):
def test_receives_and_stores_cards(self):
ace_of_spades = Card(rank="Ace", suit="Spades")
six_of_clubs = Card(rank="6", suit="Clubs")
cards = [
ace_of_spades,
... |
54826e9fb3f80a32aa9a22d1e46d474f7636f52b | maeng2418/algorithm | /12-1_이분탐색(재귀호출).py | 427 | 3.765625 | 4 | def binary_search(a, x, start, end):
# 리스트 내에 없으면
if start > end:
return -1
mid = (start+end)//2
if a[mid] == x:
return mid
elif x > a[mid]:
return binary_search(a, x, mid+1, end)
else:
return binary_search(a, x, start, mid-1)
d = [1, 4, 9, 16, 25, 36, 49,... |
4a6f0239a44d9944e44ffca1292d8a42f68e1490 | ab6/textanalysis | /utils/fileio.py | 2,263 | 3.765625 | 4 | """
General utility functions
"""
from ntpath import basename
from textanalysis.document import Document
def read_pipes_old(path_to_file):
"""
Reads in a file with documents separated by
:param path_to_file: The full path to the file containing the document.
:type path_to_file: str.
:returns: [D... |
a78143fc1ebbd008bb0ce3a4eb58a531e23f3b30 | eugene01a/algorithms-practice | /problems/top_k_frequent.py | 1,909 | 3.875 | 4 | '''
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
You may assume k is always valid, 1 <=
k <= number of unique elements.
Your algorithm's time complexity must be better than... |
88b2360b2992348ecda08607b705b610b6b619f2 | jsonkao/pclassic | /HistoricReconstruction.py | 2,372 | 3.625 | 4 | import hashlib
# Called once at the start of each test case.
# Don't forget to reset any data structures you might be using!
def initialize(N, Q):
# TODO: implement this method
return
# Adds a road between landmarks a and b, which finishes building at time t.
# t is guaranteed to start at 1 and increase by 1... |
f0f55e0dc4b3293cec96d9e16c7a60c93ee60820 | E-Ranee/HowMuchWillIUnderstand | /scrape.py | 712 | 3.6875 | 4 | import requests as r
from bs4 import BeautifulSoup
# calling it by a shorthand
def scrape(url) -> str:
webpage = r.get(url)
html = BeautifulSoup(webpage.text, 'html.parser')
paragraphs = html.article.find_all('p')
article_text = ""
for p in paragraphs:
article_text += p.text + "\n\n"
r... |
dcefcffba7f2f3e6838a040a845ca92803195e70 | kukgini/my-py | /cp1_4_01_recursion.py | 504 | 3.625 | 4 | words = []
def create_words(level, s):
global words
vowels = ['A','E','I','O','U']
words.append(s)
for i in range(0,5):
if level < 5:
create_words(level+1, s+vowels[i])
def solution(word):
global words
answer = 0
create_words(0, '')
for index, i in enumerate(words)... |
0a8168f0b368b82105b95e3537c591c3ee64f4ac | stephenosullivan/LT-Code | /kth-smallest-element-in-a-bst.py | 1,041 | 3.875 | 4 | __author__ = 'stephenosullivan'
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @param {integer} k
# @return {integer}
def kthSmallest(self, root... |
643d3174a42c4ea5cddbed19e601a7ffb905de56 | ZTong1201/LeetCode | /Python/9. Palindrome Number.py | 1,517 | 4.1875 | 4 |
# coding: utf-8
# ### 9. Palindrome Number
# Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
#
# #### Follow up:
#
# Coud you solve it without converting the integer to a string?
# In[37]:
# Convert the integer to a string.
def isPalindrome1(x... |
f121a8ed0413a7d4c075c6c91a2fd8da32a4c1b3 | herleeyandi/Discrete-Cosine-Transform-BTC-and-Block-Truncation-Coding-BTC- | /btc.py | 2,406 | 3.765625 | 4 | """
Block Truncation Coding (BTC) Algorithm
Herleeyandi Markoni
12/04/2017
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
import math
def btc_block(img_block):
"""
This function will calculate the coefficient and bitmap of the BTC Algorithm.
"""
m = img_block.shape[0] * img_block.s... |
df52c778ea81691d976e188cf0109f90b8505204 | ojrade/CS-540 | /torus_puzzle.py | 5,635 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
class PriorityQueue(object):
def __init__(self):
self.queue = []
self.max_len = 0
def __str__(self):
return ' '.join([str(i) for i in self.queue])
def is_empty(self):
return len(self.queue) == 0... |
826b607d2313cc1c5f8931134a4f75db3f4882fd | zacherymoy/cs | /lpthw/exercise6/findDuplicates.py | 1,832 | 3.5 | 4 | import re
import argparse
import sys
import os
# MATCH ANY PATTERN FROM FILE OR A DIRECTORY(S)
# RUN: python2 regargsFile.py MATCHWORD -f nameoffile.txt
# RUN: python2 regargsFile.py MATCHWORD -d nameofdirectory
def file_cruncher(fname, word):
with open(fname)as searchFile:
lineNum = 0
for line in searchFile.rea... |
98fe72432eac7a90eecb3f70db77ed1b259aacb9 | TalitaCbral/Blue_2b | /Aula 14 exercicios/7.py | 541 | 4.09375 | 4 | #07 - Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que
# mantenha separados os valores pares e ímpares. No final, mostre os valores pares e ímpares em ordem crescente.
num = [[], []]
for item in range(1, 8):
num1 = int(input(f'Digite o valor{item}: '))
... |
e326bc60c7ca49876b9948df9dc5758455a9ce64 | JianxiangWang/LeetCode | /70 Climbing Stairs/solution.py | 525 | 3.671875 | 4 | # encoding: utf-8
# dp[i] = dp[i-1] + dp[i-2]: 跨到第i台阶 == 从i-1跨过来的次数 + 从i-2跨过来的次数
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0: return 0
if n == 1: return 1
dp = [None] * n
dp[0] = 1
dp[1] = 2
... |
338c34a084ce156a43f5e442ad8ca2653d81859a | RajNirmal/HeadFirstPy | /Misc/StringIsomorph.py | 585 | 3.640625 | 4 | #Your code below
str1 = input().strip()
str2 = input().strip()
# print(str1+"\n"+str2)
if len(str1) is not len(str2):
print("NO")
quit()
def checkISO(str1,str2):
dicts = {}
for a in range(0,len(str1)):
chars = str1[a]
if chars in dicts.keys():
if str2[a] is dicts[chars]:
... |
83a52cb4b1269ecd7fad94df026805e0f09bcf7f | ZackMinott/Machine-Learning-Course | /Course_Material/Machine Learning A-Z Template Folder/Part 1 - Data Preprocessing/Section 2 -------------------- Part 1 - Data Preprocessing --------------------/categorical_data.py | 1,199 | 3.78125 | 4 | # Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 3].values
#Handling missing data: take the mean of all the columns
from sklearn.impute im... |
ee466c41d275786c6b6af893a17d3fd68e1e9dff | rabinadk1/Python | /Modules/re-func.py | 306 | 4.0625 | 4 | import re
string = "adasdasdsadsadCheeseadasdsdsasadas sadasdas asdasCake asdasdasd Pizza"
position = re.search("Cheese", string) # this gives the position of the string Cheese in the string
print(string[position.start(): position.end()])
#position.start() and position.end() gives the location of strings
|
7ef78130e3631ce1cda4a0e2ee50c7939e069d2b | pgreisen/pythonscripts | /develop/VerifyNameSeq/GenerateVariantsinFastafile.py | 3,832 | 3.609375 | 4 | #!/usr/bin/env python
import pandas as pd
import argparse
import datetime
import numpy as np
class VerifyNameSeq:
"""
Take a fasta-file with multiple sequences and their header name e.g. >A12F_G36K with a sequence
and verifies that the sequence and name corresponds.
The script is executed
python V... |
f4eac98e26044b2d904db4113fcb161f3e8422a5 | LachezarKostov/SoftUni | /01_Python-Basics/Exercise2/Exersice2.py | 288 | 3.578125 | 4 | num = int(input())
bonus1 = float(0)
if num <= 100:
bonus1 = 5
elif num >= 1000:
bonus1 = 0.1*num
else:
bonus1 = 0.2*num
bonus2 = float(0)
if num % 10 == 5:
bonus2 = 2
elif num % 2 == 0:
bonus2 = 1
print(f"{bonus2+bonus1}")
print(f"{bonus2+bonus1+num}")
|
ce9731d0138aab7fb7607fd9437e51fe3b883293 | KFranciszek/Python-Dla-Kazdego | /turniej_wiedzy.py | 2,243 | 3.546875 | 4 | # gra turniej wiedzy
# gra sprawdza wiedze ogolna ,odczytuje dane z pliku tekstowego
import pickle, shelve
import sys
def open_file(file_name, mode):
"""otworz plik."""
try:
the_file = open(file_name, mode)
except IOError as e:
print("Nie mozna otworzyc pliku", file_name, "Program zostanie zakoncz... |
588facdc3daf820d24c43885d55a6913cbf3df46 | nekapoor7/Python-and-Django | /GEEKS/Core Python/Actual Formal Argument.py | 2,090 | 4.5625 | 5 | """Actual Argument : Function calls arguments are called Actual Argument.
Formal Argument: Function definition parameters are called as formal arguments.
Types of Actual Arguments
1. Positional Argument : These arguments are passed to the function in correct positional order.
The number of arguments and their positi... |
6301e99c460cb77b3e4b036570ec41588bb2a347 | avin82/PythonFoundation | /nearest_square.py | 202 | 3.765625 | 4 | def nearest_square(limit):
num = 1
while num**2 < limit:
num = num + 1
return (num - 1)**2
test1 = nearest_square(40)
print("Expected result: 36, Actual result: {}".format(test1))
|
0e4bd791ccca7b2891ba5c8a1f9f8e079c33ef4c | lijianmin01/Qt5_study | /pyQt5/第十七章 事件处理/17.2 鼠标事件.py | 3,834 | 3.53125 | 4 | # 鼠标移动、按下或者释放动作都会唤起相应的鼠标事件:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, \
QVBoxLayout
class Demo(QWidget):
def __init__(self):
super(Demo,self).__init__()
self.button_label = QLabel('No Button Pressed',self)
self.xy_label = QLabel('... |
7bf61d8613e826d555c86c7086e70310371a0e4d | kruglov-dmitry/algos_playground | /minesweeper_board.py | 1,574 | 3.75 | 4 | import random
#
# Given board size: width x height and number of bombs
# return minesweeper's board filled with randomly distributed bombs
# with neighbourhood cells containing numbers of bombs in adjustment cells
#
def show_board(a):
for row in a:
for cell in row:
print cell,
... |
f4749cc87692df9aa4108a51258a291bead11332 | mendymsuoi/MendyLang | /mlang/mLang/Tokenize2.py | 1,283 | 3.65625 | 4 | from mtypes import *
import library
def startsWith(string, list_):
for item in list_:
if string.startswith(item):
return item
return False
def tokenize(line):
out=[]
easyString=False
while line:
a=startsWith(line, library.library.keys)
if easyString:
... |
7170e0b88f8a4f32f900d324a3a0561cc18eacf2 | navyhockey56/hackerrank | /HRreduceFunciton.py | 197 | 3.59375 | 4 | #https://www.hackerrank.com/challenges/reduce-function/problem
def product(fracs):
t = reduce(lambda x, y : x * y, fracs, Fraction(1,1))
print(str(t.numerator) + " " + str(t.denominator))
|
c66fc2e60aefb652aabc29fdf8e791e39e247842 | stewartrowley/CSE111 | /Week 3/scene.py | 8,020 | 3.890625 | 4 | import tkinter as tk
import math
def main():
# The width and height of the scene window.
width = 800
height = 500
# Create the Tk root object.
root = tk.Tk()
root.geometry(f"{width}x{height}")
# Create a Frame object.
frame = tk.Frame(root)
frame.master.title("Scene")
frame.pa... |
efb5a4c3fd8d8cb459879d1bba05f9b9946b80d8 | acsutt0n/code | /morphology/python/functions/SoupAscii_example.py | 787 | 3.5625 | 4 | # example from python4astronomers.github.io/files/asciifiles.html
# reading input from the web
from BeautifulSoup import BeautifulSoup
def html2tsv(html, index=0):
"""Parse the index'th HTML table in ''html''. Return table as a list of
tab-separated ASCII table lines"""
soup = BeautifulSoup(html)
tables = soup... |
2c2e1ffae8a20a30972118f8e4d2e7ad5f817adf | ChanghaoWang/py4e | /Chapter9_Dictionaries/Text_Parsing.py | 486 | 3.734375 | 4 | # Advanced text parsing Page 121
import string
inp = input("Please enter the filename:")
if inp == '':
inp = 'romeo-full.txt'
try:
fhand = open(inp)
except:
print("Cannot open the file:",inp)
count = dict()
for line in fhand:
line = line.lower()
Tran = line.maketrans('','',string.punctuation) # the ... |
ab2081bedd7e0d167ceb9baf0941e166c780188e | Yue-Du/Leetcode | /2.py | 1,495 | 3.59375 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
set()
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
length1,length2 = 0,0
current1,current2 = l1,l2
while current1:
length1 +=1
current1 = curr... |
17c06dd39df0153a1005164730da37f0a839b088 | Fabii006/HomeWorks | /Atividades/lista decisão/q6.py | 398 | 3.984375 | 4 | n1 = float(
input('Informe o primeiro número: ')
)
n2 = float(
input('Informe o segundo número: ')
)
n3 = float(
input('Informe o terceiro número: ')
)
x=0
if n1>n2 and n1>n3:
maior = n1
elif n2>n3 and n2>n1:
maior = n2
elif n3>n2 and n3>n1:
maior = n3
else:
print("Os três números são iguais... |
7e0213def4f133de0533bcba89dd0f8152b90239 | Barleyfield/Language_Practice | /Python/Others/Pr181030/Ex07_01(SelectionSort).py | 700 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 30 09:18:05 2018
@author: Barley
Selection Sort Example
"""
import random
data = []
i,k = 0,0
## Main Code ##
if __name__ == "__main__" :
for i in range(0,10) :
tmp = random.randrange(0,100000)
data.append(tmp)
print("정렬 전 데이터 : ", end='')
... |
5b1538023886e01d9ea027cd54dea7bdcb82d145 | harishbharatham/Python_Programming_Skills | /Chap6Prob8.py | 1,586 | 4.34375 | 4 | '''
(Turtle: draw points, rectangles, and circles) Use the functions defined in Listing
6.14 to write a program that displays a rectangle centered at (-75, 0) with width
and height 100 and a circle centered at (50, 0) with radius 50. Fill 10 random
points inside the rectangle and 10 inside the circle, as shown in Figur... |
e95be775f63568c96ab74027cc5128e40a2ecb4a | junaidnz97/Competitive-Programming | /SPOJ/GCD2 - GCD2.py | 237 | 3.703125 | 4 | def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
test=int(input())
for i in range(0,test):
inp=input()
inp=inp.split()
a=int(inp[0])
b=int(inp[1])
c=gcd(a,b)
print(c)
|
dbddecdc14c23344a02903ad67b08e18b335fb9e | nash1505/python_mini_projects | /rock_paper_scissor_game.py | 2,872 | 4.1875 | 4 | from tkinter import *
import random #import thw random package
root = Tk()
option = ["Rock","Paper","Scissor"] # created list for storing the value of computer choices
cs = 0 # computer score to store the computer score
us = 0 # user score to store the user score
def Rock(): # defined the rock function... |
e9301c4ea83816c1dc3cbc6f76c70e40c23352bf | varshaammucmr/varshapython | /numbers.py | 87 | 3.734375 | 4 |
x=1
while x<=5:
print(x)
x=x+1
dl211@soetcse:~/varsha$ python numbers.py
1
2
3
4
5
|
f273e80243f9ed748becd949adbf4363e70d8d3b | dan55/challenges | /linked_list_kth_to_last.py | 1,707 | 3.921875 | 4 | '''
Problem:
Get the kth to last node in a singly-linked list
Thoughts:
First instinct was to use a stack, which would save one traversal but is O(n)
space. Two traversals is still O(n) time and requires far less space (a ptr and a function call).
Alternatively, we can use a trailing pointer spaced k steps befor... |
00ca41928147765c72fbb3aae2ff2fae4e1484b5 | XihangJ/leetcode | /DP/198. House Robber.py | 1,412 | 3.6875 | 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... |
87a3cd11f598e40ca2d02670d5a2317ead765227 | ms-wanjira/python-class | /ifstatements.py | 716 | 3.984375 | 4 | # x = input("Enter a number ")
# print(type(x))
y = input("Enter Marks")
print(y)
z = int(float(y))
print(z)
if z<=0 and z>=100:
print("fail")
else:
if z>0 and z <= 50:
print("fail")
else:
print("pass")
# x = float(input("Enter number "))
# y = float(input("Enter a number "))
# z = float(input(... |
b48739ff646e90dd615d9177b79264922711ae02 | orionbearduo/Aizu_online_judge | /ITP1/ITP_1_6_C.py | 1,336 | 3.65625 | 4 | """
Official House
You manage 4 buildings, each of which has 3 floors, each of which consists of 10 rooms.
Write a program which reads a sequence of tenant/leaver notices, and reports the number of tenants for each room.
For each notice, you are given four integers b, f, r and v which represent
that v persons entered ... |
9d7cfe41cbc389dd27d55d6c61e4e78653545ada | Akarthikeyan/Python | /dictionary.py | 78 | 4.0625 | 4 | dict={'a':"ak",'b':"bk"}
print(dict['a'],dict['b'])
for i in dict:
print(i)
|
9926711839a8a5619b0468b588ac0653946739ec | CoolNuttle/havefun-math-bot | /core_script/volume.py | 2,728 | 3.75 | 4 | def cube(x):
return x * x * x
def balok(x, y, z):
return x * y * z
def prism(x, y):
return x * y
def silinder(x, y):
return (3.14 * x * x) * y
def silinder_2(x, y):
return (22 / 7 * x * x) * y
def pyramid(x, y):
return (1 / 3 * x) * y
def sphere(x):
retur... |
469ecfb4977711968437d687a637aee04c30bbb6 | hungapp/leetcode | /sorting_for_lists.py | 614 | 3.6875 | 4 | def stable_sort_list(L):
def merge_two_sorted_lists(L1, L2):
dummy_head = tail = ListNode()
while L1 and L2:
if L1.data < L2.data:
tail.next = L1
L1 = L1.next
else:
tail.next = L2
L2 = L2.next
tail = tail.next
tail.next = L1 or L2
return dummy_head.n... |
bd484a82ff516ef4d71bf1a3f1c260d88f81113a | luluse/python-essential-training | /Chap11 string objects/hello.py | 388 | 4.03125 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
class MyString(str):
def __str__(self):
return self[::-1]
s = MyString('Hello World')
print(s)
print('Hello World'.lower())
#String mehods
#lower()
#upper()
#capitalize()
#title()
#swapcase()
#casefold()
# string is immutable, so when u... |
d1b86d89081bfafd2ddef7721f9eb26e86ef5ccd | David8Zorrilla/TP-2018-1 | /8_OOP/ejemplos/11-Dependency Injection/main.py | 5,423 | 3.5 | 4 | # class Car:
# def __init__(self, dors, fuel_tank, performance, type = "gasoline"):
# self.dors = dors
# self.__isEngeeneOn = False
# self.__fuel_tank = fuel_tank
# self.__performance = performance
# self.__fuel = 0
# self.type = type
#
# @property
# def isOn(... |
40e9a76dc6d6a0653dcae1dfa204796b2272e3d3 | AnLi-Mi/Python_Studying_Projects | /mini_projects/Project Counting Years.py | 1,274 | 4.28125 | 4 | # Create a program that asks the user to enter their name and their age.
# Print out a message addressed to them that tells them
# the year that they will turn 100 years old.
#Extras:
#Add on to the previous program by asking the user for another number
#and printing out that many copies of the previous message.
#Hin... |
25cc7ba325aaca3fee74c38cc7f40d5730ee0cc4 | elllot/Algorithms | /Sorting/quicksort.py | 584 | 4.03125 | 4 | import random
def quicksort(arr, start, end):
if start < end:
piv = random.randint(start, end) # randint is inclusive
arr[piv], arr[end] = arr[end], arr[piv]
lower = start
for i in range(start, end):
if arr[i] < arr[end]:
arr[i], arr[lower] = arr[lower], arr[i]
lower += 1
arr[lower], arr[end] = ... |
48864152551ae7b32e5910e345428a16074f8c76 | johndgiese/python | /discretemath.py | 747 | 3.875 | 4 |
def mtable(n):
"""A multiplication table for a ring of natural numbers."""
table = []
headers = [None]
headers.extend(range(n))
table.append(headers)
for x in xrange(n):
row = [x]
for y in xrange(n):
row.append(x*y % n)
table.append(row)
return table
... |
8500d12f69bbdfd5e0fe2d13f3c555c1a5acc7cc | manastole03/Programming-practice | /python/String/no_to_percentage.py | 85 | 3.84375 | 4 | #no to percentage
a=float(input('Enter a number: '))
print('Percentage: ',a*100,'%')
|
7e81f9dd920c7fc75e5d673c98b4970953b0d0a5 | jan25/code_sorted | /leetcode/majority_elem_2.py | 871 | 3.578125 | 4 | '''
https://leetcode.com/problems/majority-element-ii/
'''
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
elema, elemb = -1, -1
counta, countb = 0, 0
for num in nums:
if num == elema:
counta += 1
elif num == elemb:
... |
52cb90d456dd66c5036658b3d7f20ce25aca4747 | TCSS456/Summary | /emails.py | 374 | 3.75 | 4 | import sqlite3
class emails(object):
def __init__(self):
self.conn = sqlite3.connect('database.sqlite')
self.cursor = self.conn.cursor()
def get_emails(self):
to_return = []
temp = self.cursor.execute('SELECT RawText FROM Emails')
for entry in temp:
... |
26630170e530c2dec43019175a14ffc3b583f002 | IngridFanfan/python_course | /Functional Programming/return.py | 1,416 | 3.671875 | 4 | #函数作为返回值
#可以不返回求和的结果,而是返回求和的函数:
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
#当我们调用lazy_sum()时,返回的并不是求和结果,而是求和函数:
#f = lazy_sum(1, 3, 5, 7, 9)
#f
#<function lazy_sum.<locals>.sum at 0x101c6ed90>
#调用函数f时,才真正计算求和的结果:
#f()
#25
#闭包
#注意... |
e4ea691f6217f612c48795cfa5d776b590044d6c | mkozel92/algos_py | /graphs/edge.py | 2,369 | 4 | 4 |
class Edge(object):
"""implementation of weighted graph edge"""
def __init__(self, v_1: int, v_2: int, weight: float):
"""
initialize edge with adjacent vertices and weight
:param v_1: first vertex
:param v_2: second vertex
:param weight: weight of edge
"""
... |
35bbc5821f64292a7d5eba667bf4cd508edd7c92 | ronielramos/playground_django | /risk/src/insurance/auto.py | 1,031 | 3.609375 | 4 | import datetime
from typing import NewType, Optional
QuestionsForAuto = NewType('QuestionsForAuto', {
'vehicle': {
'year': int
},
'income': int
})
class AutoInsurance:
def __init__(self, questions: QuestionsForAuto):
self.__income_count = self.__has_income(questions['income'])
self.__prod... |
ecac74cc03a39189de71a5f1a9886fc045815e59 | coderzyt/python3 | /ReverseListNode.py | 678 | 4.0625 | 4 | from Node import Node
class ReverseListNoe(object):
def reverseListNoe(self, head: Node) -> Node:
if head is None or head.next is None:
return head
pre = None
next = None
cur = head
while cur is not None:
next = cur.next
cur.next = pre
... |
4091bcc289879949f1a710540781edc9282a025a | JeeyaTalati/ATM-Python | /ATM.py | 756 | 3.765625 | 4 | class ATM():
def __init__(self):
self.ATMNumber=""
self.pinNumber=""
self.Amount=""
def enterATMNumber(self):
self.ATMNumber=int(input("Enter Your ATM Number"))
def enterPinNumber(self):
self.pinNumber=int(input("Enter Your Pin Number"))
def enterAmou... |
45be956eae661b0ee76b3d71975311e3fd793806 | Tutkovics/mernoki-modellalkotas | /graph.py | 794 | 3.609375 | 4 | class Node:
def __init__(self, name, prefix=None, label=None):
self.childs = []
self.name = name
self.prefix = prefix
self.label = label
def add_child(self, node, label):
self.childs.append({"label": label, "node": node})
#print(self.childs)
def print(se... |
dfc36b59a8e9506676330c6a347ea3254257d44c | MelaniPrathibha/Guess-the-word | /Guess_the_word.py | 1,668 | 4.25 | 4 | #Guess the word
import random
def introduction():
global letter_count
global turns
#introduction
print("\nLet's play Guess the Word")
print(f"You have {turns} turns to guess the word!")
#to show length of the word
print(" _ "*letter_count)
def main():
global turns
global guesses
... |
99add1602d1cf58834aa2679f1c14c4480617da8 | sammynjihia/Python-Algorithms-DataStructures | /technical_question.py | 7,195 | 4.375 | 4 | """
More resources can be found at : https://hackernoon.com/50-data-structure-and-algorithms-interview-questions-for-programmers-b4b1ac61f5b0
HackerRank videos, cracking the coding interview; https://www.youtube.com/watch?v=7ArHz8jPglw&index=2&list=PLI1t_8YX-Apv-UiRlnZwqqrRT8D1RhriX
Top job interview questions: http... |
45ca5fd777ef83e0446e2da36b256b0e89a1fa7f | geoffreyhughes/DB_Assignment2 | /Main_UI.py | 2,102 | 3.96875 | 4 |
import DB
# Welcome!
print('\n')
print("Welcome to the Student Database.")
print('\n')
# Create DB table, if it does not already exist
DB.create_table()
# UI
selection = 0
while (selection == 0):
print("Please make a selection:")
print(" [1] Display all students")
print(" [2] Add a student")
... |
e3b22fd972712f451632dbdaa55d6188cf5a6d9b | aserbezo/-Loops | /Loops/While Loops/05. Account Balance.py | 281 | 3.828125 | 4 | account = 0.0
amount = input() # "50.56"
while amount != "NoMoreMoney":
amount = float(amount)
if amount < 0:
print("Invalid operation!")
break
account += amount
print(f"Increase: {amount:.2f}")
amount = input()
print(f"Total: {account:.2f}") |
0d43e1ed49694c74684a16d28c1b835ecf7fe631 | co-leetcode/construct_elephant | /31-40/(34)FindFirstAndLastPositionOfElementInSortedArray/wallaceplayfrog.py | 573 | 3.515625 | 4 | class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
res = []
lo = hi = -1
flag = True
for i in range(len(nums)):
if nums[i] == target:
if fla... |
e62edf5b7d3555fabcebbb52e27136b1650b4b57 | keremkoseoglu/Guitar-Training-Remote | /practice/practice_category.py | 1,303 | 3.546875 | 4 | """ Practice category """
from enum import Enum
class PracticeCategory(Enum):
""" Practice category """
UNDEFINED = 0
RIGHT_HAND = 1
LEFT_HAND = 2
THEORY = 3
DEXTERITY = 4
PERFORMANCE = 5
EDUCATION = 6
SPEED = 7
TIMING = 8
class PracticeCategoryGroup(Enum):
""" Practice cat... |
c0f9add2469a223b4d81be1ed583d4082af6a901 | Sanketwable/pentestools | /code.py | 2,325 | 3.546875 | 4 | """
Brute force password breaker using a dictionary containing
English words.
"""
import sys
import PyPDF2
from pathlib import Path
def get_filename_from_user() -> Path:
"""Asks for a path from the User"""
while True:
filename: str = input("Enter filename in folder of script:")
path: Path = Pa... |
3b4cf9cc95e38ed0a0e73d47843ea217b524fe41 | gormac23/Python | /Projects/Euler/16-power_digit_sum.py | 371 | 3.9375 | 4 | '''
Problem 16
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
'''
def list_of_digits(n,p):
return [int(x) for x in str(n**p)]
def sum_list(l):
return sum(l)
def main():
num = 2
power = 1000
print(sum_list(list_of_digits(num, ... |
9e48eccc70cc68d5ce409960d99b7da3e37fe3a6 | mfarooq28/Python | /ListComprehension.py | 1,821 | 4 | 4 | # I want n for each n in the num
nums = [1,2,3,4,5,6,7,8,9,10]
my_list = []
for n in nums:
my_list.append(n)
print(my_list)
print(" mod % 2")
my_list = []
for n in nums:
if n%2 ==0:
my_list.append(n)
print(my_list)
print("Another method")
my_list=[n for n in nums if n%2 ==0]
print(my_list)
print(... |
a96351d0c90484fefc944e086318a2179068ceb4 | amloyd/Hote_Performance | /Tell_Me_About_The_Data_2.py | 1,163 | 3.546875 | 4 | import csv
from StringIO import StringIO
import pandas as pd
import matplotlib.pyplot as plt
from pandas.tools.plotting import scatter_matrix
PATH = 'data/hotel.csv'
if __name__ == '__main__':
# Read and open the CSV file
with open(PATH, 'r') as f:
data = StringIO() # Create a temporary holder for... |
82d60f07eb49feeb0993c169fb69dcfcf66b0d52 | prastabdkl/machine_learning | /supervised_learning/regression.py | 577 | 3.984375 | 4 | # Example of regression
# Author: Prastab Dhakal
# Chapter:
import matplotlib.pyplot as plt
import numpy as np
x = np.array(range(1, 19))
y = np.array([147026,144272,140020,143801,146233,144539,141273,135389,142500,139452,139722,135300,137289,136511,132884,125683,127255,124275])
#Use np.polyfit to determine the coef... |
2134074789df1b82e956af7f269c2dd29d2637b4 | amayro/g_algorithms | /08_Trees_Hash_function/tasks.py | 2,348 | 3.609375 | 4 | import hashlib
def task_section(task):
print(f'\n{"":-^10} №{task} {"":-^10}')
# №1 ------------------------------------------------------------------------------------
task_section(1)
"""
1. Закодируйте любую строку из трех слов по алгоритму Хаффмана.
"""
string = "beep boop beer!"
print("Исходная строка: " + ... |
373d66947f782782921e550baa62d2045beb8075 | Robinrrr10/python | /src/patterns.py | 321 | 4 | 4 |
print("pattern 1")
for n in range(4):
for i in range(4):
print("#", end = "")
print()
print("pattern 2")
for n in range(4):
for i in range(n + 1):
print("#", end = "")
print()
print("pattern 3")
for n in range(4):
for i in range(4 - n):
print("#", end = "")
print(... |
7ab34acfd00c3f899fcc40a8d2a819751f93e0ac | JaviVinnas/minimizador_automatas_finitos | /main.py | 4,926 | 3.6875 | 4 | #!/usr/bin/env python3
from automata import Automata
import json
def main():
with open('automatas.json') as json_file:
# inicializamos variables de utilidad
automatas = json.load(json_file)
id_automata = {}
letra = 'a'
salir = False
automata = None
opcion_m... |
4e2e17e87f10925dfbe0d72792b2f0c368d07194 | xuhyang/algo-practice | /heap.py | 14,445 | 3.890625 | 4 | from heapq import *
"""
# 堆
# 1 解决动态求最大/小值
# 2 可以解决动态第K大/小问题
# 3 双堆可以解决动态中位数
"""
class Heap:
"""
5. Kth Largest Element
https://www.lintcode.com/problem/kth-largest-element/description
Find K-th largest element in an array. Input: n = 3, nums = [9,3,2,4,8] Output: 4
其他解法:quick_select
"""
def kthLargestElement(self,... |
9b3d54f57af53cc26606fbe8b294ed4cc4e33b07 | git874997967/LeetCode_Python | /hard/leetCode759.py | 939 | 3.609375 | 4 | #759. Employee Free Time
class Interval(object):
def __init__(self, start=None, end=None):
self.start = start
self.end = end
class Solution(object):
def employeeFreeTime( schedule):
"""
:type schedule: [[Interval]]
:rtype: [Interval]
"""
result,arr ... |
51b5d4be2f802d864068967a35a3f94913216aff | jc328/CodeWars-1 | /7kyu_FindThe2ndLargestIntegerInArray.py | 682 | 4.0625 | 4 | // 7kyu - Find the 2nd Largest Integer in Array
// Find the 2nd largest integer in array If the array has no 2nd largest integer then return nil. Reject all non integers elements and then find the 2nd largest integer in array
// find_2nd_largest([1,2,3]) => 2
// find_2nd_largest([1,1,1,1,1]) => nil because all eleme... |
9b78b1adb75653678460baee602a42cb6f1db702 | VitoriaCarvalho/BinaryTrees | /Implementação/rbt.py | 7,222 | 3.65625 | 4 | import sys
class Node:
RED = True
BLACK = False
def __init__(self, key, color = RED):
if not type(color) == bool:
raise TypeError("Bad value for color parameter, expected True/False but given %s" % color)
self.color = color
self.key = key
self.left = self.right = self.parent = NilNode.inst... |
c5a668ca8c9e10b158e31b5a2a7fc55a7ee67704 | joelhoelting/algorithms | /leetcode/iteration/53_maximum_sub_array.py | 997 | 4.0625 | 4 | """
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Example 1:
Input: nums = [-2,1,... |
d57a508b8ea697aabfe145494f3090467748b8b9 | DynamicGravitySystems/LongmanTide | /tidegravity/trajectory_utils.py | 6,670 | 3.765625 | 4 | # -*- coding: utf-8 -*-
from datetime import datetime
import pandas as pd
import numpy as np
def convert_gps_time(gpsweek, gpsweekseconds, format='unix'):
"""
Converts a GPS time format (weeks + seconds since 6 Jan 1980) to a UNIX
timestamp (seconds since 1 Jan 1970) without correcting for UTC leap
s... |
1954c4ab769597192c6d8c70dd0400e2a40e793e | cesarsst/PythonProjects | /PythonExercicios/ex060.py | 361 | 4.125 | 4 | # faça um programa que leia um numero qualquer e mostre o seu fatorial
n = int(input('Digite um numero qualquer: '))
fat = n
while n != 1:
fat *= (n - 1)
n -= 1
print('O fatorial é: {} '.format(fat))
# outra forma
from math import factorial
n = int(input('Digite um numero qualquer: '))
f = factorial(n)
print... |
47ac4a179284227b599b939f3cb3d75684e8aacc | qmnguyenw/python_py4e | /geeksforgeeks/python/easy/24_9.py | 2,189 | 3.53125 | 4 | Python Convert Html to PDF
There are many websites that do not allow to download the content in form of
pdf, they either ask to buy their premium version or don’t have such download
service in form of pdf.
### Conversion in 3 Steps from Webpage/HTML to PDF
**Step1: Download library pdfkit**
... |
c1e3b273ed3455549211aa9d760638e37b4bcf36 | Kaminagiyou123/python_practice | /app.py | 1,214 | 4.25 | 4 | from utils import database
USER_CHOICE="""
Enter:
- 'a' to add a new book
- 'l' to list all books
- 'r' to mark a book as read
- 'd' to delete a book
- 'q' to quit
Your choice : """
def menu():
database.create_book_table()
user_input=input(USER_CHOICE)
while user_input!="q":
if user_input=="l":
print ("... |
75f7d787e2392784d67ba21702204458850950de | puru1909/PythonProjects | /astrologers star(exercise).py | 891 | 3.59375 | 4 | # pattern printing
# input: (ek no input lena h) Interger n(0/1) usko type cast krna h
# ek boolean variable m ar usko set krna h true/false
# True: pattern aesa print hoga
# n=4
# *
# **
# ***
# ****
# False : n=4
# ****
# ***
# **
# *
#
print("please enter a no between 1 to 10")
n = int(input())
print("please ... |
d4bc73451b2fe3691ec74c5dfab7aed6034a5a1d | Schmidty88/ICP1 | /source/project1/project1/file1.py | 207 | 3.625 | 4 | print('Welcome to program 1')
value1 = 200
value2 = 300
value3 = 400
print(value1, 'plus', value2, 'plus', value3, 'equals', value1+value2+value3)
print('This is my code for project 1 question 1')
|
2a3ead9a9be4a31afb170190bf009b488a3aecad | inkri/Machine-Learning | /ML_Python/kmeanP.py | 2,467 | 3.5 | 4 | ##K Means Clustering
#Import Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
#Get the Data
import os
os.getcwd()
os.chdir("C:\\Users\\abhishek.b.jaiswal\\Desktop\\DataScience\\sem 2\\BD 3\\codes")
os.getcwd()
df = pd.read_csv('College_Data',index_col=0)
print("Da... |
2f18c1e3fc2cea08d85b83f3da3bcb6e8bbb7860 | MarcioRSanches/Estudos_Python | /Desafio057.py | 403 | 4.09375 | 4 | sexo = str(input('Digite seu sexo: [M/F] ')).upper()[0].strip() # fatiamento pegando só a primeira letra upper()[0]
while sexo !='M' and sexo !='F': # sexo not in 'MnFn'
print('Sexo inválido!!')
sexo = str(input('Digite novamente seu sexo: [M/F] ')).upper()[0].strip()
if sexo == 'M':
print('O sexo informa... |
258bc29fcf9916aaf6c969330465bb8d8e4f84bf | twarogm/pp1 | /02-ControlStructures/Exercises/02-36.py | 212 | 3.78125 | 4 | x=0
while x>=0:
if x%7==0 and x%2==1 and x%3==1 and x%4==1 and x%5==1 and x%6==1:
print(f"Liczba podzielna przez 7 oraz dająca resztę 1 przy dzieleniu przez 2,3,4,5,6 to {x}")
break
x+=1 |
7fb6bd0fe406a7abecc2641cf45fbab5709e7b06 | szymonczop/UWr-DS-2019-20 | /Machine_learning/SVM/newton_additional.py | 5,896 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 7 21:48:55 2020
@author: czoppson
"""
import numpy as np
import matplotlib.pyplot as plt
def rosenbrock_v(x):
"""Returns the value of Rosenbrock's function at x"""
return (1 - x[0])**2 + 100*(x[1]- x[0]**2)**2
rosenbrock_v([1,1])
def r... |
9909029f7f27114543c1c74533d1e1d86f72dfa5 | gfike19/lc101 | /unit1/playground/mod (2020_02_28 23_49_40 UTC).py | 84 | 3.609375 | 4 | def mod(num1,num2):
result = num1 % num2
return result
print(mod(128, 127)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.