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 |
|---|---|---|---|---|---|---|
47f111e1242d64f5655027c836ebfa25b802f312 | dheerajsharma25/python | /assignment10/ass10_4.py | 646 | 4.15625 | 4 | #Q.4- Create a class Shape.Initialize it with length and breadth Create the method Area.
class shape:
def __init__(self,length,breadth):
self.length=length
self.breadth=breadth
def area(self):
self.result=self.length*self.breadth
class rectangle(shape):
def arearect(self):
print("area of re... |
67a7ad3ff6a0614dc38f40b3230daae5f16ed1d5 | dheerajsharma25/python | /assignment5/ques5_5.py | 355 | 4.03125 | 4 | #Q.5- A shop will give discount of 10% if the cost of purchased quantity is more than 1000.Ask user for quantity Suppose, one unit will cost 100. Judge and print total cost for user.
q=int(input("enter the units "))
q1=q*100
if(q1>1000):
dis=((q/10)*100)
q1=q1-dis
print("total cost is %d"%(q1))
else:
print("no di... |
3c9681b39dc9cbd0f7fe5abb883d88f7f5a90215 | aswathi9/PESU-IO-SUMMER | /prog3.py | 453 | 3.921875 | 4 | def search(a,beg,end,ele):
while beg<=end:
mid=(beg+end)//2
if a[mid]==ele:
return mid
elif a[mid]<ele:
beg=mid+1
elif a[mid]>ele:
end=mid-1
return -1
n=int(input("Enter no. of elements"))
a=[]
for i in range(n):
e=int(input("Enter no."))
a.append(e)
ele=int(input("Enter el... |
8950bfeacfd4b68cb47e7c851357dcdd06fc6669 | Percell44/python_-demo | /hello.py | 115 | 3.84375 | 4 | firstName = input('What is your first name? ')
print('Hello ' + firstName)
print(firstName, ' is learning Python') |
4aead30a35fe3d4312cd6788087a278bbc1a56e1 | andrew15818/108 | /spring/pattern_recognition/homework/HW3/0616110_HW3.py | 18,975 | 3.890625 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## HW3: Decision Tree and Random Forest
# In hw3, you need to implement decision tree and random forest by using only numpy, then train your implemented model by the provided dataset and test the performance with testing data
#
# Please note that only **NUMPY** can be used to i... |
91f7ad7519c86fe6fb8c42af2659ec893bb97e76 | SeongHyeonShin/ndb_algorithm | /2_Bubble_Sort.py | 505 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 14:50:29 2020
@author: SHIN
"""
import numpy as np
# Bubble sort
# 옆에 있는 값과 비교해서 더 작은 값을 앞으로 보낸다
# O(N ^ 2)
if __name__ == '__main__':
# arr = [1, 10, 5, 8, 7, 6, 4, 3, 2, 9]
arr = np.random.randint(0, 100, size=50)
for i in range(len(arr) - 1):
... |
78f48d4425a141c9f5a36e1e78c2d78d4068d517 | SeongHyeonShin/ndb_algorithm | /3_Insertion_Sort.py | 480 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 14:50:29 2020
@author: SHIN
"""
import numpy as np
# Insertion sort
# 각 숫자를 적절한 위치에 삽입한다!
# O(N ^ 2)
if __name__ == '__main__':
# arr = [1, 10, 5, 8, 7, 6, 4, 3, 2, 9]
arr = np.random.randint(0, 100, size=50)
for i in range(len(arr) - 1):
j = i
... |
0455ad1f56d24e5f4a1d2340fa19a7a809d2f7d4 | juliachaloupka/CryptographyMidterm | /Cryptography_Midterm/aes/tests.py | 4,828 | 3.5 | 4 | import unittest
from aes import AES
class TestBlock(unittest.TestCase):
"""
Tests raw AES-128 block operations.
"""
def setUp(self):
self.aes = AES(b'\00' * 16)
def test_success(self):
""" Should be able to encrypt and decrypt block messages. """
message = b'\01' * 16
... |
f01448ca4c4c36675bb0d9a9f4011d2475ee5ff3 | sv1996/PythonPractice | /set.py | 404 | 4.0625 | 4 | s ={1,2,3} #sets of integers
print(s)
print(type(s))
# set don't allow duplicates
s= {1,2,3,1,4}
print(s) #prints only single value not duplicates
s=set([1,2,3,4,1])
print(s)
#initialize a set with set() method
s =set()
print(type(s))
# add element to a set
s={1,2}
s.add(3)
print(s)
#add multiple elements to a s... |
56cdff9e47c16d2b3f672b2f0b56ee542ab28dee | sv1996/PythonPractice | /input.py | 47 | 3.640625 | 4 | num= int(input("enter a number"))
print(num%10) |
6463c599070a9448ce87d30b591cc7aab2b754e7 | sv1996/PythonPractice | /lambda.py | 107 | 3.5 | 4 | double = lambda x: x*2
print(double(5))
#lambda added
def double(x):
return x*2
print(double(5)) |
c0c4d692956d733993d63a42fdfdcf609c9b7eba | sv1996/PythonPractice | /sortList.py | 509 | 4.28125 | 4 | number =[3,1,5,12,8,0]
sorted_list =sorted(number)
print("Sorted list is " , sorted_list)
#original lst remain unhanged
print("Original list is " , number)
# print list in reverse order
print("Reverse soretd list is " , sorted(number , reverse =True))
#original list remain unchanged
print("Original list is " , number)... |
b972c01d2b22e14fed024ddaee819f44d11dea86 | chasezimmy/playbill | /helpers/connection.py | 467 | 3.625 | 4 | import sqlite3
import env
class DB(object):
""" connection class to database """
def __init__(self):
"""
Args:
conn (object): db connection
cur (object): db cursor
"""
self.conn = sqlite3.connect(env.SQLITE_FILE)
self.cur = self.conn.cursor()
... |
c653254fa319e6e5712fcef35bf5e3e63146a164 | Python-clique/Area-and-perimeter | /area and perimeter program.py | 1,046 | 4 | 4 | from tkinter import *
root = Tk()
root.configure(bg = 'light blue')
n1 = IntVar()
n2 = IntVar()
def multiplication():
m1 = n1.get()
m2 = n2.get()
m3 = m2 * m2
label1 = Label(root , text = "Area is = %d" %m3 , bg = "light blue").place(relx = 0.3 , rely = 0.75 )
def perimeter():
m1 = n1.get()
m2 ... |
d9e4dfaf7b8ed0c4ffa7bc0c91636a791295fd96 | vpc20/leetcode-may-2020 | /SingleElementInSortedArray.py | 1,700 | 3.71875 | 4 | # You are given a sorted array consisting of only integers where every element appears exactly twice, except for one
# element which appears exactly once.Find this single element that appears only once.
#
# Example 1:
#
# Input: [1, 1, 2, 3, 3, 4, 4, 8, 8]
# Output: 2
#
# Example 2:
#
# Input: [3, 3, 7, 7, 10, 11, 11]
... |
d6506a86b8213130606bbbd6d0b175d65e068d2a | vpc20/leetcode-may-2020 | /RemoveKDigits.py | 2,845 | 3.546875 | 4 | # Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is
# the smallest possible.
#
# Note:
# The length of num is less than 10002 and will be ≥ k.
# The given num does not contain any leading zero.
#
# Example 1:
# Input: num = "1432219", k = 3
# Out... |
a2710e67ef6324697b55bd7f635db562e9683844 | vpc20/leetcode-may-2020 | /JewelsAndStones.py | 1,084 | 4 | 4 | # You're given strings J representing the types of stones that are jewels, and S representing the stones you have.
# Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
#
# The letters in J are guaranteed distinct, and all characters in J and S are letters... |
9ff37bbfd7fe12c8e942b06ecf9a7e58f773e88e | vpc20/leetcode-may-2020 | /MaxSumCircularSubarray.py | 2,910 | 3.703125 | 4 | # Given a circular array C of integers represented by A, find the maximum possible sum of a non - empty subarray of C.
#
# Here, a circular array means the end of the array connects to the beginning of the array.(Formally, C[i] = A[i]
# when 0 <= i < A.length, and C[i + A.length] = C[i] when i >= 0.)
#
# Also, a subarr... |
49d9b6ad1d24c298de9261bddfe37c8494789ce3 | Shogo-Nakasaki/Study-Python | /210519/210519_1.py | 763 | 3.640625 | 4 | # 英語のテストを作るためにExcelに表入力するプログラム
import openpyxl as px
from openpyxl import Workbook
import openpyxl
wb = openpyxl.Workbook()
wb.save("System英単語.xlsx")
ws = wb.active
num = 0
print("終了するには3を入力してください\n\n")
while(True):
# テスト内容の入力
text1 = input(f"英単語>>")
if text1 == '3':
print("作成を終了します")
break... |
a528ae279f5773160001dd56b9ffb7df47714a86 | viditvora11/GK-quiz | /Python assements/v2 (Instructions and welcome)/v2a_instructions_and_welcome.py | 707 | 4.4375 | 4 | #Asking if they want to know the quiz rules.
rule = input("\nDo you want to read the rules or continue without the rules? \npress y to learn the rules or x to continue without knowing the rules : ")#Asking for the input
if rule == "y" or rule == "yes": #Use if function
print("\nThe basic rules are as follows \n ... |
9aba44312fb51d4ee4989b80a2428fa5ac94675a | djfish1/Tools | /Python/StringUtils.py | 640 | 3.640625 | 4 | import re
def str2bool(s):
b = None
if s.lower() in ('y', 'yes', 'true', 't', '1'):
b = True
elif s.lower() in ('n', 'no', 'false', 'f', '0'):
b = False
else:
raise ValueError('Unable to interpret "' + s + '" as bool.')
return b
def alnum_sort(l):
# iterables sort eleme... |
e307dae65dcc6c710950e7bbc8ff029b2664fdef | PimW/experiments | /bdd2aig/bdd2aig.py | 10,390 | 3.625 | 4 | import re
import os
def extract_constraints():
pass
def write_constraints_as_sat():
pass
def extract_bdd_nodes(filename: str) -> [set, list]:
"""
The file contains all nodes of the bdd in the format:
::
[
node(node_id, var, low, high),
node(node_id, var, low, ... |
be209cd682fa1bd58c55821629668e03575ec2a6 | Evelyn2017/compiler | /pyCalc/calc1.py | 3,219 | 3.796875 | 4 | # Token types
#
INTEGER, PLUS, MINUS, EOF = 'INTEGER', 'PLUS', 'MINUS', 'EOF'
class Token(object):
def __init__(self, type, value):
self.type = type
self.value = value
def __str__(self):
return "Token <{type}, {value}>".format(type=self.type,
... |
91e0252060d3c81a69eab0180d352b50c4bd2054 | jonathanj/compose | /compose.py | 438 | 3.84375 | 4 | from functools import reduce
def compose(*fs):
"""
Create a function composition.
:type *fs: ``iterable`` of 1-argument ``callable``s
:param *fs: Iterable of 1-argument functions to compose, functions will be
applied from last to first, in other words ``compose(f, g)(x) ==
f(g(x))``.
... |
2a69fac76973f6e2f27721264926a3ae99c07cb8 | sushil-2803/30-days-of-code-challenge | /Day 20/solution.py | 373 | 3.5 | 4 | #!/bin/python3
import sys
n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
swap=0
# Write Your Code Here
for i in range(len(a)-1):
for j in range(0,n-i-1):
if(a[j]>a[j+1]):
a[j],a[j+1]=a[j+1],a[j]
swap+=1
print(f"Array is sorted in {swap} swaps.")
print(f"Fi... |
39a9ecbb37d8f9b22edd4bde41370ff1c2b01563 | well-balanced/hackerrank-python | /problem_6.py | 420 | 3.53125 | 4 | if __name__ == '__main__':
score_list = []
marksheet = []
n = int(input())
for _ in range(0,n):
name = input()
score = float(input())
marksheet.append([name,score])
score_list.append(score)
score_list = sorted(list(set(score_list)))
second_score = score_list[1]
... |
796585db36d1a65691e1371af6fb71a36d2e466d | hemel-cse/NewsCrawler | /NewsCrawler/Helpers/date_helper.py | 1,146 | 3.59375 | 4 | import datetime
# Datetime Format
# Example: '26-11-2016 12:36 AM'
DATETIME_FORMAT = "%d-%m-%Y %I:%M %p"
def increase_day_by_one(d):
d += datetime.timedelta(days=1)
return d
def get_formatted_datetime(d, frmat=DATETIME_FORMAT):
return datetime.datetime.strftime(d, frmat)
def date_to_string(d, frmat = ... |
86cc9ef2db7a97c84d45776d9fbdd8ec2744949e | JamazaMal/PlayArea | /eu030.py | 617 | 3.5 | 4 | dc = 6 # Max number of digits
pw = 5 # Which power to use
pows = [i**pw for i in range(0, 10)]
digits = [1] + [0] * (dc-1)
def nextDigit(n):
global digits
r = True
if n == dc:
return False
if digits[n] == 9:
r = nextDigit(n+1)
if r:
digits[n] = 0
else:
... |
562a5f56228e1fc5010a199ff4d2f29246760c97 | JamazaMal/PlayArea | /eu058.py | 354 | 3.515625 | 4 | def is_prime(n):
return all(n % i for i in range(2, int(n**.5)+1))
def main():
i = 1
t = 0
c = 0
while True:
s = i * i
t = t + 4
for j in range(1,4):
if is_prime(s + ((i+1)*j)):
c = c + 1
if c/t < 0.1:
print(i, t, c, c/t)
... |
7f349e7791dff882d39db583f3689acff7041072 | mythilidivya98/Divya | /stockspan.py | 496 | 3.59375 | 4 | def calculateSpan(price, S):
n = len(price)
st = []
st.append(0)
S[0] = 1
for i in range(1, n):
while( len(st) > 0 and price[st[-1]] <= price[i]):
st.pop()
S[i] = i + 1 if len(st) <= 0 else (i - st[-1])
st.append(i)
def printArray(arr, n):
for ... |
c2de02602f41f9e759d17716206a00630864d7a5 | nirmalshah20519/GTU_PRACTICALS | /ADA/PRACTICAL_6/matrix_chain_mul.py | 796 | 3.828125 | 4 | # Implementation of Chain Matrix Multiplication using Dynamic Programming
import sys
sol_matrix = [[-1 for _ in range(50)] for _ in range(50)]
def find_min(p, i, j):
if(i == j):
return 0
if(sol_matrix[i][j] != -1):
return sol_matrix[i][j]
sol_matrix[i][j] = sys.maxsize
... |
7659e0b19f0401dd1948c081fd7b6b5e0b557b85 | nirmalshah20519/GTU_PRACTICALS | /PDS/SET_1/Prog-10.py | 170 | 3.921875 | 4 | # Count occurrences of an element in a list
L1= [15, 6, 7, 10, 12, 20, 10, 28, 10]
print(L1)
x=int(input("Enter a number to check its occurence : "))
print(L1.count(x))
|
35d3d5427943e9d102a4a524f3d1b9b12a9d1dc6 | nirmalshah20519/GTU_PRACTICALS | /PDS/SET_1/Prog-9.py | 246 | 4.03125 | 4 | # Program to print duplicates from a list of integers
L1 = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20]
print(L1)
res=[]
for i in L1:
if L1.count(i)>1:
res.append(i)
print("duplicates found in list are :")
print(set(res))
|
4d48dda6e0e27a3f0099f9ee141c30f2f9428035 | ShramanJain/Computer-Society | /Basic/Display Factors of A Number/SolutionByShraman.py | 203 | 3.59375 | 4 | def factor(n):
l = []
for i in range(1, n + 1):
if n % i == 0:
l.append(i)
l = str(l)
return l
print("N = ", end="")
n = int(input())
print(f"Output = {factor(n)}")
|
c85ec3454523b121fd44b351892ed1f5e0499a40 | mohitsudhakar/coding | /Intervals/max_interval_overlap.py | 2,422 | 3.765625 | 4 | """
Consider a big party where a log register for guest’s entry and exit times is maintained.
Find the time at which there are maximum guests in the party.
1. Brute force is to find, min and max time and count number of guests for each time
This is O(N*(max-min)) time O(max-min) space
2. Sort start and end, and trave... |
9661ee24cfe802e39afaec7136a387580eeef68e | mohitsudhakar/coding | /classic_array/2sum.py | 315 | 3.8125 | 4 | # Return indices of 2 numbers in give array that sum to s
def two_sum(arr, s):
dic = {}
for i, a in enumerate(arr):
if s-a in dic:
return dic[s - a], i
dic[a] = i
return None
if __name__ == '__main__':
sum_ = 10
array = [1,2,3,4,5,7]
print(two_sum(array, sum_)) |
d71d3394457bccd14cebc21e1f640bcd658c6d76 | mohitsudhakar/coding | /string/add 2 Large numbers.py | 501 | 3.890625 | 4 | def addLarge(num1, num2) -> int:
res = ''
num1 = num1[::-1]
num2 = num2[::-1]
l = len(num1) if len(num1) > len(num2) else len(num2)
carry = 0
for i in range(l):
n1 = int(num1[i]) if i < len(num1) else 0
n2 = int(num2[i]) if i < len(num2) else 0
r = (n1 + n2 + carry) % 10
... |
09e52d08db87046a6556b71ed22e534266cb0bd8 | mohitsudhakar/coding | /Intervals/merge_overlapping_intervals.py | 602 | 3.765625 | 4 |
def merge_overlapping_intervals(intervals):
print('Sort by start')
intervals.sort() # sort by start
# intervals.sort(key=lambda i: i[1]) # sort by end
stack = []
for interval in intervals:
if stack and interval[0] < stack[-1][1]:
top = stack.pop()
stack.append... |
b23c10dc7244c7e58802033bd665213a93e8c43f | mohitsudhakar/coding | /coding_rounds/drw3.py | 1,071 | 3.5625 | 4 |
def shortestRunLengthEncoding(s: str, k: int) -> int:
leftLength, rightLength = [0], [0]
lastCount = 1
for i in range(1, len(s)):
leftLength.append(lastCount)
if s[i] == s[i-1]:
if lastCount in [1,9,99,999,9999,99999]:
lastCount += 1
else:
... |
a7f745e89d04fb9079a06819c82473e51d1ae503 | mohitsudhakar/coding | /daily_coding_problem/101_prime_sum.py | 961 | 4.0625 | 4 | """
This problem was asked by Alibaba.
Given an even number (greater than 2), return two prime numbers whose sum will be equal to the given number.
A solution will always exist. See Goldbach’s conjecture.
Example:
Input: 4
Output: 2 + 2 = 4
"""
def isPrime(num, primes):
if num in primes:
return True
... |
e4f8f175e4293a01ac1679f28667ba9e762d7d43 | yk-hts/AtCoder | /b_71.py | 181 | 3.5 | 4 | S = list(input())
alphabet = []
for i in range(26):
alphabet.append(chr(i+97))
x = set(S)
for i in alphabet:
if i not in x:
print(i)
exit()
print('None') |
597fc9639668109d8715a5be729cf285845c268c | yk-hts/AtCoder | /b_fizzbuzz_sum.py | 310 | 3.515625 | 4 | n = int(input())
array = list([x+1 for x in range(n)] if (x+1)%15!=0 and )
sum = 0
for i in range(len(array)):
if array[i]%15==0:
array[i] = 'fizzbuzz'
elif array[i]%3==0:
array[i] = 'fizz'
elif array[i]%5==0:
array[i] = 'buzz'
else:
sum += array[i]
print(sum) |
b5f02bafae1491c3410a450c29e56f42f870f580 | brelsford/topology | /Barriers_example.py | 2,058 | 3.609375 | 4 | from matplotlib import pyplot as plt
import my_graph_helpers as mgh
import math
"""
This shows a short snippet of code to (manually) define barriers for the
epworth block, build the barriers through the function "build_barriers", and
plot the results before and after construction of new roads.
"""
de... |
79079abcdc8c54f73fe397e37e86f08a38114f68 | FernandoGarciafg/m02_boot_0 | /mapFilterReduce.py | 1,429 | 3.625 | 4 | from functools import reduce
def doble(numero):
return numero * 2
def pares(numero):
# otra opcion seria simplemente poner return x % 2 == 0
if numero % 2 == 0:
return numero
else:
return None
lista = [1,3,-1,15,9,2,8]
listaDobles = map(lambda x:x * 2, lista) # map aplica en este cas... |
2ca1a0ce4909965a4b4d0bcf2080d406bb9a5732 | FernandoGarciafg/m02_boot_0 | /recursividad.py | 1,503 | 4.1875 | 4 | # la recursividad es una funcion que para repetirse se invoca a si misma, una funcion es recursiva si para definirse se necesita
# solo a si misma y se llama a si misma, la recursividad tiene que tener una condicion de parada
def retroContador(numero):
print("{}\n".format(numero), end = "")
if numero > 0:
... |
33af79a047b149381359661361e731545b51f6c0 | DoomsdayDevice/calculator | /calc.py | 8,026 | 3.8125 | 4 | from tkinter import *
class Calculator (Frame):
"""creates a frame inside the window"""
def __init__(self, window):
Frame.__init__(self, window)
# self.width = 275
# self.height = 500
# window.geometry("%sx%s" % (self.width, self.height))
window.title("SkyNet v1.1")
... |
aab70625a101ba567de900dc6592a34f3c70558e | mk-99/p4ne | /Sem2.2/deco.py | 307 | 3.71875 | 4 | print("Start")
def modify_cubic(old_func):
def new_cubic(arg):
print("Вычисляем куб от ", arg)
return old_func(arg)
return new_cubic
@modify_cubic
def cubic(arg):
return arg * arg * arg
# cubic = modify_cubic(cubic)
for i in range (0, 10):
print(cubic(i))
|
d1259971da85320de4f9478cf816b892ce7ca125 | Shwetasouravtiwari/python-course | /theDouble.py | 152 | 3.671875 | 4 | def doubleChar(doubleit):
doubled = []
for letter in doubleit:
doubled.append(letter * 2)
print("".join(doubled))
doubleChar('the') |
1cd6266da30f919c850b283513f24b7cffe1a4c0 | raphaelshirley/ull_python_classes | /codingstyle/solutions/collection.py | 107 | 3.796875 | 4 | colors = ['red', 'green', 'blue', 'yellow']
for i, color in enumerate(colors):
print(i, '--->', color) |
0c3e993ce07bdeb5dd7608c94896ffc2d71af138 | raphaelshirley/ull_python_classes | /machinelearning/mls/plot.py | 6,522 | 3.703125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import sklearn.metrics
import seaborn as sns
from matplotlib.collections import EllipseCollection
def draw_ellipses(w, mu, C, nsigmas=2, color='lightgray', axis=None):
"""Draw a collection of ellipses.
Uses the low-level EllipseCollection to efficiently draw... |
50b0f8d421d6e7a907499602003a46b61dd8f4d3 | GustavoJatene/practice | /070.py | 682 | 3.515625 | 4 | total = contP = 0
nPdt = ''
contPb = 0
mPrcb = 0
print('-' * 30)
print('LOJA LOJA')
print('-' * 30)
while True:
pdt = str(input('Nome do produto: '))
prc = float(input('Preço: R$'))
total += prc
if prc >= 1000:
contP += 1
if contPb == 0:
mPrcb = prc
if prc <= mPrcb and nPdt == ''... |
c79a2d047cebb01c74781e83375ef7f657293105 | GustavoJatene/practice | /061.py | 212 | 3.75 | 4 | n1 = int(input("Informe o primeiro termo: "))
n2 = int(input("Razão da PA: "))
cont = 0
while cont < 10:
print("{}".format(n1), end="-")
n1 = n1+n2
cont = cont + 1
if cont == 10:
print(end="FIM") |
275d7aa8960d304505cbf99873b7facae85ba278 | GustavoJatene/practice | /034.py | 275 | 3.75 | 4 | sal = float(input("Informe o salário: "))
if sal >= 1250:
aum = sal + ((sal*10)/100)
print("Seu salário terá acréscimo de 10% e será: R${}".format(aum))
else:
aum = sal +((sal*15)/100)
print("Seu salário terá acréscimo de 15% e será: {}".format(aum)) |
2270978b351d4d8002d2a9b034a5b2b61a994cc2 | GustavoJatene/practice | /037.py | 465 | 4 | 4 | num = int(input("Informe um numero inteiro: "))
print("Digite [1] para BINÁRIO\nDigite [2] para OCTAL\nDigite [3] para HEXADECIMAL")
nbin = bin(num)
noct = oct(num)
nhex = hex(num)
esc = int(input("Tecle a opção: "))
if esc == 1:
print("{} convertido para BINÁRIO é: {}".format(num, nbin[2:]))
elif esc == 2:
pri... |
572907a3cc69925f9489c9aed322e8ca41086556 | GustavoJatene/practice | /015b.py | 307 | 4.09375 | 4 | import math
num = int(input("Digite um numero: "))
raiz = math.sqrt(num)
print("A raiz de {} é igual a {:.2f}".format(num,raiz))
print("A raiz de {}, arredondando para cima é igual a {}".format(num,math.ceil(raiz)))
print("A raiz de {}, arredondando para baixo é igual a {}".format(num,math.floor(raiz))) |
b113065082c3c498de5edd65292d5acb187b2d49 | GustavoJatene/practice | /007.py | 310 | 3.953125 | 4 | n = int(input("Digite um número: "))
# n2 = n*2 <- (Caso precise usar esses valores posteriormente, é preciso que crie as variáveis)
# n3 = n*3
# raiz = pow(n, 1/2) ou n**1/2
print('O dobro do numero {} é = {} \nO triplo é = {} \nA raiz quadrada é = {:.2f}'.format(n, (n * 2), (n * 3), (pow(n, 1 / 2))))
|
1295ef13438f16dde50717364555a6cd899b089d | GustavoJatene/practice | /015.py | 213 | 3.515625 | 4 | km = int(input("Insira a quantidade de Km rodado: "))
dias = int(input("Informe a quantidade de dias usado: "))
val_fin = (60 * dias) + (0.15 * km)
print("O valor total a ser pago é de: R${:.2f}".format(val_fin)) |
8ac2df2e1534e649af60b4fc3f9bec3065fe9ae1 | GustavoJatene/practice | /031.py | 223 | 3.515625 | 4 | dist = float(input("Informe a distancia em km, da sua viagem: "))
if dist <= 200:
print("O preço a ser pago será de: R${:.2f}".format(dist*0.50))
else:
print("O preço a ser pago será de: R${}".format(dist*0.45)) |
aea4de55e129fae6d4b69b047cff768914e73e8d | RationalLearningAgent/Artificial-Teaching-Assistant | /Code/Image Processing/Text_Colour_RGB.py | 1,250 | 3.578125 | 4 | import cv2
import numpy as np
import Tkinter
import tkFileDialog
Tkinter.Tk().withdraw() # Close the root window
in_path = tkFileDialog.askopenfilename()
#RGB Image
img = cv2.imread(in_path)
print "RGB Image Shape is :",img.shape
while(1):
cv2.imshow('RGB Image',img)
c = cv2.waitKey(1)
if c == 27:
cv... |
f7c62ac2153382ef2d4b9c28a0c336493f2ab0fa | krasotinpa/Stepic | /Python/Basics/task1-4-1.py | 671 | 3.515625 | 4 | def add(name, var):
global NameSpace
NameSpace[name]['vars'].add(var)
def create(name, parent):
global NameSpace
NameSpace[name] = {'parent': parent, 'vars': set()}
def get(name, var):
global NameSpace
# print('=>'+name)
if var in NameSpace[name]['vars']:
print(name)
return
if name == 'glob... |
67959a5d4312c4f8c036aa9f147f7874014a67ab | jcampillay8/Python-Ciclo-For-B-sico-II | /ejecircico07.py | 410 | 4.09375 | 4 | # Máximo : crea una función que toma una lista y devuelve el valor máximo en la matriz. Si la lista está vacía, haga que la función devuelva False.
# Ejemplo: máximo ([37,2,1, -9]) debería devolver 37
# Ejemplo: máximo ([]) debería devolver False
def mínimo (lista):
if len(lista)<=0:
return False
else:
... |
54f1d42f62ab625278a416fdf7f3cdfb81758a57 | Edgardo899/examen_python | /examen_python.py | 1,548 | 3.90625 | 4 | import csv
def nombreDelArchivo():
nombre_archivo = input("Ingresar nombre del archivo: ")
return nombre_archivo
#Fin del método nombreDelArchivo().
def verificacionExistenciaArchivo(nombre_ingresado):
# Variables para determinar si se crea el archivo o no.
archivo_existe = True
#Variable con el ... |
ba8ab6155ae6a2d8f426f5bc66f56e2c5ca230ec | claywong/ud120-projects | /naive_bayes/nb_author_id.py | 1,712 | 3.53125 | 4 | #!/usr/bin/python
"""
This is the code to accompany the Lesson 1 (Naive Bayes) mini-project.
Use a Naive Bayes Classifier to identify emails by their authors
authors and labels:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email... |
4162112e9a564f6e8c2bd3d21e929a1831e3357f | hakcsim/Tutorials-Repo | /database.py | 2,775 | 3.75 | 4 | import sqlite3
class Employee:
# class variable - shared between instances
raise_amount = 1.04
num_of_emps = 0
def __init__(self, first, last, pay):
# instance variables - unique to each instance
self.first = first
self.last = last
self.pay = pay
Employee.n... |
d4d658965d544dc7fa8d19046eca852db1af6e61 | hakcsim/Tutorials-Repo | /itertools_module.py | 5,093 | 3.625 | 4 | import itertools
counter = itertools.count()
for num in counter:
if num < 20:
print(num)
else:
break
print(next(counter))
print(next(counter))
print(next(counter))
print(next(counter))
data = [100,200,300,400]
daily_data = list(zip(itertools.count(), data))
print(daily_data)
counter = iter... |
ab5ca4877bcbd0db93d5c2891a6dead1da07c1c6 | hakcsim/Tutorials-Repo | /decorators.py | 4,612 | 4.125 | 4 | def outer_function(msg):
message = msg
def inner_function():
print(message)
return inner_function
hi_func = outer_function('Hi')
bye_func = outer_function('Bye')
hi_func()
bye_func()
# same as above
def outer_function_2(msg):
def inner_function():
print(msg)
return inner_func... |
3875da480ae72ca4cbf6043270c49c201347a23f | Kri-lab/YoutubeVideos | /Programmieren in Python/11_Dictionarys.py | 408 | 3.5625 | 4 | # Dictionarys in Python {key: value}
tagebuch = {'montag': 'Doofer Tag', 'dienstag': 'War schon besser'}
tagebuch = {'montag': ['Schule doof', 'alles doof'],
'dienstag': ['Schule doof', 'ich bin aber cool']}
tagebuch = {'montag': {'morgens': 'dooof', 'mittags': 'doooooof', 'abends': 'okay'},
... |
92f92739189d62eedfa1c769ed2c483bd139fdef | Kri-lab/YoutubeVideos | /Programmieren in Python/07_Listen.py | 646 | 3.953125 | 4 | # Listen in Python
# a = a + b oder a += b?
# extend oder append?
# insert, pop, count, iterieren?
einkaufs_liste = ['milch', 'salz', 'eier', 'äpfel']
zusatz_liste = ['backpulver', 'motoröl', 'milch']
zusatz_liste2 = 'brot'
# a = a + b <=> a += b
# einkaufs_liste = einkaufs_liste + zusatz_liste
# einkaufs_liste +=... |
d4a9d06e3f2c6b332daa09d13ea27819bcae57ca | rushabhshah2002/bookLibrarySystem | /bookratingsearch.py | 1,972 | 3.515625 | 4 | import time
import csv
def rating():
mainList = []
f = open("Stock.txt", "rt")
f1 = csv.reader(f)
for i in f1:
if i != []:
mainList.append(i)
rate = []
book = []
stock = []
edition = []
price = []
author = []
count = 0
for i in range(len(mainList)):
... |
aa65dba074bfd7e24ed9468d09181c3150cc44d4 | Iskanderkys/pythoncurce-_- | /5.py | 131 | 3.953125 | 4 |
for i in range(3):
# for k in range(i+1):
# print(f"k={k}, i={i}")
# # print(f"i+{i}") |
ff421ac14ab2d0c1917ac3e2f1e561fca515e134 | Iskanderkys/pythoncurce-_- | /venv/2092019.py | 123 | 3.765625 | 4 | max_i = int(input("NUM>>"))
item = 0
s = "abc"
while item < max_i:
print(item, end=", ")
item += 1
print("...") |
6f013967c7998c120b1a1f8ca681add61a969ae3 | preciousakura/Atividades-Python | /listas.py | 278 | 4.1875 | 4 | num = []
num.append(0)
num.append(9)
num.append(8)
num.append(2)
for x, cont in enumerate(num):
print(f"Na posição {x} encontrei o valor {cont}!")
print("Cheguei ao fim da lista")
x = ('apple', 'banana', 'cherry')
y = enumerate(x)
print(list(y))
|
4a79d928f2489ca57e99281fe9f515542cbcf49e | preciousakura/Atividades-Python | /dicionario/exercicio2.py | 467 | 3.5 | 4 | from random import randint
from operator import itemgetter
jogo = {
'jogador1': randint(1, 6),
'jogador2': randint(1, 6),
'jogador3': randint(1, 6),
'jogador4': randint(1, 6),
}
ordem = []
print("Valores sorteados: ")
for k, v in jogo.items():
print(f'O {k} tirou {v}.')
ordem = sorted(jogo.items(),... |
c57799bb1ea76d52ec15085c90ede41dc76ea625 | Punkrockechidna/PythonCourse | /advanced_python/functional_programming/map.py | 294 | 4.125 | 4 | # MAP
# previous version
# def multiply_by_2(li):
# new_list = []
# for item in li:
# new_list.append(items * 2)
# return new_list
# using map
def multiply_by_2(item):
return item * 2
print(list(map(multiply_by_2, [1, 2, 3]))) #not calling function, just running it
|
77d027f188b923b6c0cc1f5466c7ae8392682771 | Punkrockechidna/PythonCourse | /python_basics/logic/exercise_duplicates.py | 621 | 4.0625 | 4 | # print duplicates
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
unique_list = set(some_list)
for item in some_list:
if item in unique_list:
unique_list.remove(item)
else:
print(item)
# Without sets
some_list.sort()
print(some_list)
for number in range(len(some_list)):
if some_lis... |
9702ac1a5b90658c71f18640d9f11aa1f76bbed0 | Punkrockechidna/PythonCourse | /exercise_guessing_game/random_guess.py | 315 | 3.828125 | 4 | import random
import sys
number = random.randrange(1,10)
guesses = 0
win = False
while not win:
input("Guess a number from 1 to 10")
guesses += 1
current_guess = sys.argv[1]
if current_guess == number:
print(f'You got it, the number was {number}, with {guesses} tries!')
win = True
|
31633675909d7bd06ebbe76665b6cb726667ad53 | Punkrockechidna/PythonCourse | /python_basics/logic/while.py | 678 | 3.84375 | 4 | i = 0
while i < 50:
print(i)
i += 1
else:
print('Done with all the work!')
# for loop vs while
# simpler
my_list = [1, 2, 3]
for item in my_list:
print(item)
# more flexible and powerful
i = 0
while i < len(my_list):
print(my_list[i])
i += 1
# breaking
while True:
response = input('say s... |
1dcb8478600e6e21f49e109cb5a2f27bf5b80257 | Punkrockechidna/PythonCourse | /python_basics/logic/loops.py | 388 | 4.03125 | 4 | # Iterables - list, dictionary, yuple, set, string. One by one check each item in collection
user = {
'name': "golem",
"age": 5006,
'can_swim': False
}
for item in user.items():
print(item)
# or use this way
for key, value in user.items():
# can use k and v
print(key, value)
for item in user.... |
f4639ccaef61f4ec683eb2a42a180bfda13e537f | Punkrockechidna/PythonCourse | /python_basics/functions/scope.py | 633 | 3.625 | 4 | #What variables do I have access to?
# A new function is kind of like creating a new world for scope
# 1 - Start with local
# 2 - Parent local scope
# 3 - Global
# 4 - built in python functions
# global keyword uses the global variable
# dependency injection is better (parameters needed)
# nonlocal keyword
# Scope ... |
effd59472d0cfb5e83fdd79d53c989dbc88eac22 | soccer155/-RPSgame | /RPSgame.py | 1,267 | 4.09375 | 4 | import random
def game(user):
count_win = 0
count_loss = 0
count_tie = 0
game_in_progress = True
t = ['rock', 'paper', 'scissors']
while game_in_progress == True:
user_choice = input("Enter Rock, Paper, or Scissors: ")
user_choice_lower = user_choice.lower()
if user_choic... |
0fd424756e6dd3e286253c67e5a6e51d27062234 | Carlo-Carandang/DNA-Code-to-Binary-to-ASCII | /decoder.py | 1,781 | 3.5625 | 4 | """You are working with a team of genetics researchers. You're told the exciting and confusing news that there may be a message from God hidden in our DNA! Through science and prayer your team has been able to work out the following:
* The message is hidden somewhere in the attached sequence of ~120,000 base pairs
* ... |
947f37fca0d63f02ec4af7a6c063496765ce4f06 | brandon-vargas24/PythonCode | /Python/merge_sort.py | 1,245 | 4.21875 | 4 | #Extra Credit Homework Assignment, Merge Sort
#VARGAS, BRANDON
#April 24, 2017
#Iterative:
def merge_sort_iterative(l, m):
result = []
i = j = 0
total = len(l) + len(m)
while len(result) != total:
if len(l) == i:
result = result + m[j:]
break
elif len(m) == j:
... |
5a80ae4f8e4f64e5b167d6a2dcf869f703772d84 | dkokelley/hashking | /hashking - incremental.py | 889 | 3.671875 | 4 | #Hashking#
# Required:
# # Python 3.2 (32 bit)
# # Skein module (Currently only works with 32 bit version of Python 3.2)
import skein
import random
bestguess = ""
bestscore = 1024 # Replace with current best score before running so that only better scores are printed
target = "5b4da95f5fa08280fc9879df44f418c8f9f12ba... |
b7dc216aadba0d01c3ec3559073e80b7259564d6 | Philigrim/luminor_hw | /Scripts/iban_algorithms.py | 2,948 | 3.921875 | 4 | #
# Data cleansing
# This is used to remove all non-alphanumeric characters.
#
# Returns string new_iban, which contains IBAN without non-alphanumeric characters.
#
def data_cleansing(iban):
new_iban = ''
for char in iban:
if(char.isalnum()): new_iban += char
return new_iban
#
# Iban check... |
517db206920ba9c71d60669bbbaf0ebf073e6d4a | kaspersky43/python_turtle_practice | /red_hexagon.py | 249 | 3.5625 | 4 | '''
앞으로 이돟: fd
뒤: bk
왼쪽: lt
오른쪽: rt
'''
import turtle as t
n = 6 #6각형
t.shape('turtle')
t.color('red')
t.begin_fill() #색 영역 시작
for i in range(n):
t.fd(100)
t.right(360/n)
t.end_fill() #색 영역 끝
|
9a49302aaea4162ee9516a50177a136e611ff3a9 | gourik/Machine-Learning- | /k_nearest_neighbour.py | 3,732 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 7 15:04:06 2021
@author: t
"""
#A classified dataset from a company is considered,in which feature(column) names are hidden but data and target classes are given
#Using KNN algorithm, a model will be created which directly predicts a class for new data point.
... |
9dc41e4b416f9d91040906fc67de0dd2e4eab5ce | gourik/Machine-Learning- | /exceptional_handling.py | 4,670 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 31 15:20:58 2021
@author: Gouri
"""
#Exceptional handling in Python:
try:
#code block where exception can occur
a=b
except:
print('Some problem might have occured')
try:
#code block where exception can occur
a=b
except Exception ... |
b7016456fb373975209286077222c6423f25f572 | gabrielibagon/TensorBlur | /tensorblur/blur.py | 2,801 | 3.90625 | 4 | import tensorflow as tf
class Blur:
"""
Base class for Blur objects.
"""
def __init__(self, size=1):
"""
Initialize a Blur object with a specified kernel size.
https://en.wikipedia.org/wiki/Kernel_(image_processing)
Note: blurring is most efficient when size is odd.
... |
6d3ef737751193c05f7a6791ca698a94c6cc77b7 | ChuqiaoW/Sandbo | /prac_05/hex_colours.py | 572 | 4.3125 | 4 | COLORS = {"aliceblue": "#f0f8ff", "antiquewhite": " #faebd7", "brown": "#a52a2a", "burlywood": "#deb887",
"cadetblue": "#5f9ea0", "coral": "#ff7f50", "chocolate": "#d2691e", "cornflowerblue": "#6495ed",
"darkgoldenrod": "#b8860b", "darkorange": "#ff8c00"}
color_chose = input("Pls enter color name... |
dc3081a5ae99ff552a0949113862134282476995 | ChuqiaoW/Sandbo | /prac_04/list_exercises.py | 595 | 4.03125 | 4 | def main():
numbers = []
for number in range(1, 6):
write_in = int(input("Number:"))
numbers.append(write_in)
data = analyze_numbers(numbers)
print(f"The first number is {data[0]}\nThe last number is {data[1]}\nThe smallest number is {data[2]}\n"
f"The largest number is {data[3... |
aa0889b1c7e030acce744954f71709d7589e3aa4 | BetaProjectGroup/INF6050GroupProject | /project mockup.py | 3,280 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 14 20:14:07 2018
@author: MoLeigh
"""
# TO DO
#1. collect the demographic info from the user. --> input() store in
# variables/lists/dictionaries
#2. define daily recommended calorie intake based on the data they gave you
#and information from the web --> ma... |
668231c1df74597af290b1375842b57c27f69e32 | MLoopz/HackerRank | /freqQuery.py | 608 | 3.734375 | 4 | def freqQuery(queries):
answers = []
dic = {}
for t, n in queries:
if t == 1:
#insert
dic[n] = dic.get(n, 0) + 1
elif t == 2:
#delete
if n in dic and dic[n] > 0:
dic[n] = dic.get(n, 0) - 1
elif t == 3:
#check... |
6b9a1fb77a47d7ab8202a8d6b3aae6176045973d | MLoopz/HackerRank | /minToursPacks.py | 778 | 3.53125 | 4 | def getMinTours(N, A, k):
# Iterating through each possible
# value of minimum Items
for i in range(1, max(A)+1):
tours = 0
for j in range(0, len(A)):
if(A[j]% i == 0):# Perfectly Divisible
tours += A[j]/i
else:
# Not Perfectly Divi... |
cfa4cbdf3d0ab1fb004fa74a1bd113818a4eb85e | MLoopz/HackerRank | /twoStrings.py | 214 | 3.640625 | 4 | def twoStrings(s1, s2):
lst_sbstring = []
substring = ""
answer = "NO"
for l in s1:
if l in s2:
answer = "YES"
break
return answer
print(twoStrings("and","art")) |
7c61b9cc81d4ae45d91866e38ec0051b045cdc00 | khatriajay/pythonprograms | /in_out_list_.py | 418 | 4.4375 | 4 | #! /usr/bin/env python3
#Python3 program for checking if you have a pet with name entered.
petname= ['rosie', 'jack', 'roxy', 'blossom'] #Define a list with pet names
print (' Enter your pet name')
name = input()
if name not in petname: #Check if name exists in list
print ('You dont hav... |
a240619cb6a2944bffeb7826844656df68b5db9f | khatriajay/pythonprograms | /exit_program.py | 420 | 4 | 4 | #! /usr/bin/env python3
# Python3 program to make user type exit to exit the program
import sys # Import module
while True: #always true by default
print ('Type exit to exit:')
response=input()
if response == 'exit': # Condition ch... |
429a147c3291e507964ef1015390d144f77e71f4 | shaoqiming/PythonLesson | /day11/ClassTest.py | 1,962 | 4.0625 | 4 | # coding:UTF-8
# 表示是从object继承
class Student(object):
pass
bart=Student()
# 后面是内存地址
print bart
# 可以在类上面绑定属性
bart.name='shaoqi'
print bart.name
class Student1(object):
# 在类中定义的方法的第一个参数是self 表示实例的本身。
def __init__(self,name,score):
self.name=name
self.score=score
def print_score(self... |
286b5e824827971610c7fbb587bd873b72748d6b | amolsmarathe/Casino-Black-Jack-Game-Python-Capstone-Project | /main.py | 7,683 | 4.125 | 4 | """
"Casino Blackjack Game"
This is a simple text-based BlackJack game with following features:
- Multiple players versus an automated dealer
- Players can play STAND or HIT or DOUBLE DOWN
- Players have 4 colored chips: White, Green, Red and Black chips
- Players can pick their betting amount
- Ea... |
c7b05b89c047a48548e04c157b7ef9f1568c8f63 | omaskery/human-resource-machine | /hrminterp/value.py | 1,323 | 3.796875 | 4 | import string
class Value(object):
def __init__(self, value):
self._value = value
def __str__(self):
return str(self.value)
@property
def value(self):
return self._value
@staticmethod
def parse(value):
value = value.strip()
if all([c in string.digits ... |
67d85303d11ee6889ea6a41632259a73a3d81bbf | anilktechie/database-playground | /sqlite_ex5.py | 1,329 | 3.515625 | 4 | """SQLite Exercise 5
Parse a file containing SQL statements for the SQLite dialect and execute them.
"""
import os
import logging
import sqlparse
import sqlalchemy as sa
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("sqlalchemy.engine.base")
logger.setLevel(logging.DEBUG)
def main():
file_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.