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 |
|---|---|---|---|---|---|---|
49e7bd2e40d7626cbe108b07d166043c281b497b | ntapacTest/Algorithms | /MergeSorting.py | 638 | 3.671875 | 4 | def sort(a,a1,an):
if(an!=a1+1):
q=((an-a1)//2)+a1
sort(a,a1,q)
sort(a,q,an)
merge(a,a1,an,q)
def merge(a,a1,an,q):
l=[x for x in a[a1:q]]
r=[x for x in a[q:an]]
i=0
j=0
for k in range(a1,an):
if(i>=len(l)):
... |
905e1378407ea11a854aa20efcff31ba9d0ae392 | nail82/bpnn | /data_table.py | 10,558 | 3.65625 | 4 | """
Ted Satcher
CS 640
Fall 2012
Assignment 3
File: data_table.py
This module implements the data table for the neural net.
"""
from __future__ import print_function
import numpy as np
import os
class DataTable(object):
"""
This class is the data repository for the neural network.
It contains all the we... |
cc431e299e2e2ff62c0feb9d6e793ad72a16bbca | WOM89757/tf12test | /2.mnisttest.py | 2,157 | 3.59375 | 4 | from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
def imshow(img):
plt.imshow(np.reshape(img, [28,28]))
plt.show()
mnist = input_data.read_data_sets("./MNIST_data/", one_hot=True)
for index in range(10)... |
f233b45a71a1514c7e27ce4c98b429a229e8bcdc | Runmore/AnythingWeWant | /HW1/morepractice.py | 567 | 3.53125 | 4 | complement = { 'A':'T', 'C':'G', 'G':'C', 'T':'A' }
queue=[]
def gen_codon(c):
queue.append(c)
return queue[-3:]
s = "ATCTGTATAACGAATATATACATTATC"
rcs = ''.join( map( lambda c: complement[c] , reversed(s) ) )
codon= map(gen_codon,s)
print rcs
print codon
codonf = filter( lambda c: len(c)==3 ,codon)
print codo... |
664f6d6da2ad2587b4546729751eef690f3011ec | chen1932390299/leetcode-java-python | /python-leetcode/day16_advanced_functions.py | 626 | 3.90625 | 4 |
def foo(iteral):
return iteral[0]
# todo sample own define map
a=[[1,"a"],[2,"b"]]
res= list(map(foo,a)) # <<=====>> res=list(map lambda x:x[0],a) :--> lambda func:expression
print(res) # [1, 2]
# todo sample2 about map
result=list(map(str,a)) # change all elements to string type
# todo sample filter own defin... |
335aff27ab2aacd342c611bc6c1919f21093af13 | chen1932390299/leetcode-java-python | /python-leetcode/day24_mro_super.py | 905 | 3.921875 | 4 | #
# class A:
#
# def foo(self):
# print("---->A.foo")
#
# class B(A):
#
# def foo(self):
# print("B.foo----->")
# A().foo()
#
# class C(A):
#
# def foo(self):
# print("C.foo----->")
# A().foo()
#
#
# class D(B,C):
# def foo(self):
# print("D.foo---->")
# ... |
95abb9a2f079f3980d638786db669624d0407995 | chen1932390299/leetcode-java-python | /python-leetcode/day21_magic.py | 1,285 | 3.640625 | 4 |
# todo :魔法函数与普通函数区别,就是魔法函数会自动执行调用,而普通需要对象去手动调用
class Dog:
"""__del__ 在引用计数为0时触发垃圾回收"""
def __init__(self):
self.name="tom"
def __call__(self, *args, **kwargs):
print("----->call------>")
def __str__(self):
"""need return str type ,else TypeError: __str__ returned non-string (t... |
2b6570837e6da9d1cf0458010f1fde4373628104 | swtnk/AcadView | /prog1.py | 266 | 3.84375 | 4 | def error_detection(num):
if num < num + 1:
try:
num = num / (num - num)
return num
except ZeroDivisionError as error:
return error
def main():
print(error_detection(3))
if __name__ == '__main__':
main()
#OUTPUT: division by zero |
09f75de95ac1f64a6ffd3b73e803b32ed8a209a8 | rakeshsukla53/interview-preparation | /Rakesh/python-basics/call_by_reference_in_python.py | 1,081 | 4.28125 | 4 |
def foo(x):
x = 'another value' # here x is another name bind which points to string variable 'another value'
print x
bar = 'some value'
foo(bar)
print bar # bar is named variable and is pointing to a string object
# string objects are immutable, the value cannot be modified
# you can not pass a simple p... |
2b07a1da75d655ff808d94a18e6d1c9f5abedf3f | rakeshsukla53/interview-preparation | /Rakesh/Common-interview-problems/counter_challenge.py | 509 | 3.515625 | 4 | __author__ = 'rakesh'
def solution(N, A):
'''
:param N: Maximum value
:param A: List of Numbers
:return: List of numbers
'''
maxValue = 0
counters = [0] * N
for i in A:
if (i >= 1) and (i <= N):
counters[i - 1] += 1
maxValue = counters[i - 1]
elif... |
4394e39ded93a4134ed32f1c96db38a710e7946f | rakeshsukla53/interview-preparation | /Rakesh/python-basics/call a function until a sentinel value.py | 322 | 3.5625 | 4 |
# method 1
block = [1, 2, 3, 4, 5, 6, 7, 8]
i = 0
result = []
while i <= len(block):
if block[i] == 5:
break
result.append(block[i])
i += 1
print result
# here if the block is callable then it will work otherwise not.
result = []
for value in iter(block, 5):
result.append(value)
print resul... |
067491bdd79ddeddea6146513a74457649d0d68e | rakeshsukla53/interview-preparation | /Rakesh/Common-interview-problems/candyProblem.py | 995 | 3.5 | 4 | __author__ = 'rakesh'
#we will move two ways one is right and other is left and then take the max of it
#candy problem
class Solution(object):
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
tempA = [1] * len(ratings)
for i in range(len(ratin... |
1d5566306ef92e7f652e863ce90ee9e8b98a1a25 | rakeshsukla53/interview-preparation | /Rakesh/Google-interview/differentation.py | 673 | 3.5 | 4 | __author__ = 'rakesh'
from collections import Counter
#2x^2 + 5x + 10
def polynomial(equation):
coefficent = []
power = []
for line in equation.split():
try:
try:
if line[1] == 'x':
coefficent.append(line[0])
if line[-1] ==... |
de4fc062a33d209172ed71d02074dda15ebbe5d4 | rakeshsukla53/interview-preparation | /Rakesh/trees/Symmetric_Tree_optimized.py | 888 | 4.28125 | 4 |
# for this method I am going to use the reverse binary tree method to check for symmetric tree
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def __init__(self):
self.... |
28cd26a23942d826b699cd6cddfc23248ad67dda | rakeshsukla53/interview-preparation | /Rakesh/Natural Language Processing/coverting_words_to_feature.py | 1,829 | 3.5 | 4 | __author__ = 'rakesh'
import nltk
import random
from nltk.corpus import movie_reviews
documents = [(list(movie_reviews.words(fileid)), category)
for category in movie_reviews.categories()
for fileid in movie_reviews.fileids(category)]
random.shuffle(documents)
all_words = []
for w in movi... |
255621d0bc01e2b2192d2a5731af1621c50cf69f | rakeshsukla53/interview-preparation | /Rakesh/Math/sqrt function optimized.py | 463 | 3.828125 | 4 |
# This is newton method way to solving the problem
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
X = 1
while True:
fx = X*X - x
dx = 2*X
y = X
X = X - float(fx)/dx
if str(y... |
0d4e7b50613b4459159c16a2773248967fe45a60 | rakeshsukla53/interview-preparation | /Rakesh/Common-interview-problems/meeting_rooms.py | 879 | 3.5625 | 4 | __author__ = 'rakesh'
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def minMeetingRooms(self, intervals):
"""
:type intervals: List[Interval]
:rtype: int
"""
... |
dc53ce7c76f9b149441aeda751214149d8933c17 | rakeshsukla53/interview-preparation | /Rakesh/python-iterators/remove_while_iteration.py | 636 | 4.125 | 4 | __author__ = 'rakesh'
somelist = range(10)
for x in somelist:
somelist.remove(x) #so here you are modifying the main list which you should not be doing
print somelist
somelist = range(10)
for x in somelist[:]: #Because the second one iterates over a copy of the list. So when you modify the original list, you do... |
83bc96dc64096e151cd76f943ca8254bc635753e | rakeshsukla53/interview-preparation | /Rakesh/python-functionals/Validating Email Addresses With a Filter.py | 380 | 3.859375 | 4 | __author__ = 'rakesh'
import re
def filterEmailAddress(email):
m = re.match(r'\b[a-zA-Z-_0-9]+@[a-zA-Z\d]+[.][a-zA-Z]{1,3}\b', email)
if m:
if m.group() == email:
return email
emailID = []
N = input()
for i in range(N):
emailID.append(raw_input())
print sorted(list(filter(filte... |
8f1c6e18c4efc25efdb21fd9c05ed13de574486e | rakeshsukla53/interview-preparation | /Rakesh/matrix_arithmetic/matrix_rotation_reverse_awesomness.py | 162 | 4.0625 | 4 | A = [
[1, 2, 3],
[8, 9, 4],
[7, 6, 5]
]
# print A[::-1] # reverses the whole matrix
matrix = zip(*A[::-1]) # rotates the whole matrix clockwise 90 degree
|
d9d3972659395307fb5353071b3615a0ad82c1bc | rakeshsukla53/interview-preparation | /Rakesh/Google-interview/breeding_like_rabbits_optimized_method.py | 2,970 | 4.5 | 4 | __author__ = 'rakesh'
#here we have to know about memoization
#Idea 1 - To sabe the result in some variables ---but it is not feasible. Fibonacci can be done since only two variables
#are required. Also in the memoization part there is only recursion process not all.
#Idea 2 - Use some kind of hash table here, but i... |
0edd9ec75e7acff7f4f3f784a71553f3ccb71acf | rakeshsukla53/interview-preparation | /Rakesh/python-basics/list_comprehension.py | 645 | 4.0625 | 4 |
l = [1, 2, 3, 4, 5, 6, 7]
# filter means what all values you want to use
print filter(lambda x: x if x % 2 == 0 else 0, l)
print filter(lambda x: x if x % 2 == 0 else 0, l)
print [i if i % 2 == 0 else 0 for i in l]
# create a matrix in python using list comprehension
print [[i if i == 2 else 0 for i in range(3)] ... |
eb55353311c8e6a84e43e1d0184b2d193d0e6b01 | rakeshsukla53/interview-preparation | /Rakesh/trees/find_number_of_binary_tree.py | 870 | 3.84375 | 4 | __author__ = 'rakesh'
class Solution(object):
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
#Check the image for optimized solution and check how we have started with the problem
#Writing code is the most trivial thing you can imagine
binarySearch... |
1b1e945ef82db250c50dd635c5da0a86a8ec32fc | rakeshsukla53/interview-preparation | /Rakesh/Common-interview-problems/product of array except self.py | 912 | 4.15625 | 4 |
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
Logic :
You will use two loops one going from left to right, and other from right to left
for example if a = [1, 2, 3, 4]
Going from left -> a = [1, 1, 2, ... |
d76b4fb7698514de4c2bf3d22af7d915efe37719 | rakeshsukla53/interview-preparation | /Rakesh/search-algorithm/binary_search.py | 545 | 3.796875 | 4 | __author__ = 'rakesh'
def binarySearch(alist, item):
#for binary search I am assuming that the list is increasing order
mid = len(alist) / 2
if item == alist[mid]:
return 'Item Found'
if mid == 0:
return 'Item not Found'
if item > alist[mid]:
return binarySearch(alist... |
23ca1215a474d6a40ac0c93df2446b5475adce9a | rakeshsukla53/interview-preparation | /Rakesh/Common-interview-problems/Ordered_Dict.py | 1,795 | 4.21875 | 4 | __author__ = 'rakesh'
#What is orderedDict
#An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.
from collections import OrderedDict... |
02180358325e6d765af190e73ecf82df0dcbdfa9 | rakeshsukla53/interview-preparation | /Rakesh/matrix_arithmetic/filling matrix using spiral matrix way.py | 596 | 3.703125 | 4 |
1) Create a matrix to store the coordinates
(0,0) (0,1) (0,2)
(1,0) (1,1) (1,2)
(2,0) (2,1) (2,2)
(2) Read it out using the trick of "Spiral Matrix I"
(0,0) (0,1) (0,2) (1,2) (2,2) ...
(3) Put 1, 2, 3, ... n**2 at these coordinates sequentially. Done.
def generateMatrix(self, n):
result = ... |
c65f358380f0189717032666991f396bde4c06ec | rakeshsukla53/interview-preparation | /Rakesh/matrix_arithmetic/rotate in place algorithm.py | 515 | 3.765625 | 4 |
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
matrix[::] = zip(*matrix[::-1])
class Solution:
def rotate(self, A):
n = len(A)
for i in range(n/... |
dcb5dc0d8b77109893f6c8f0446daf75e4cf57f8 | rakeshsukla53/interview-preparation | /Rakesh/Natural Language Processing/word_tokenize.py | 750 | 4.1875 | 4 | __author__ = 'rakesh'
#http://pythonprogramming.net/tokenizing-words-sentences-nltk-tutorial/
from nltk.tokenize import sent_tokenize, word_tokenize
EXAMPLE_TEXT = "Hello Mr. Smith, how are you doing today? The weather is great, and Python is awesome. The sky is pinkish-blue. You shouldn't eat cardboard."
print(sent... |
5aeedd6c95fbd300cc1991564cefd9b29619da2f | MohitKumar21/Forsk2019 | /Day2/pattern.py | 220 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 8 11:03:21 2019
@author: User
"""
star=int(input("enter the no. : "))
for star in range(0,star):
print("* "*star)
for i in range(0,star+1):
print("* "*(star-i+1)) |
fb46d0cfdade35b2c7d61a68d3b4e5b7f2e362ac | MohitKumar21/Forsk2019 | /Day1/format2.py | 156 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 7 12:15:50 2019
@author: Hitesh
"""
str1 = input("Enter String ")
str1 = str1.replace(' ','*')
print(str1) |
5f842066cab566242edb124461fd76a00ebbc0b5 | nishantpratap/docker-pythonscript | /nis.py | 500 | 3.78125 | 4 | import glob
list = []
list = glob.glob('*.txt')
print(list)
#it returns all the files in a list ending with .txt extension
#sir i do want to know exactly what you want
#please mention me
#on the basis of my evaluation these are the things:
#case1
#You want to read subdirectries also(in a present working direct... |
697468fd2e8acd3d3fe32e3257ac97e8f318b50f | pythondred/--6 | /6.4.py | 2,922 | 3.890625 | 4 | class Car:
def __init__(self, speed, color, name, is_police):
self.speed = speed
self.color = color
self.name = name
self.is_police = is_police
def go(self):
return f'{self.name} едет'
def stop(self):
return f'{self.name} останавливается'
def turn_right(se... |
f1b37196503a28b024a68f01fd19d6214c4699ae | lahusiak/python_DungeonGame | /dungeon.py | 3,000 | 3.65625 | 4 | import random
import sys
import os
# CELLS = [(0,0), (0,1), (0,2),
# (1,0), (1,1), (1,2),
# (2,0), (2,1), (2,2)]
def clear():
"""Clear the screen"""
os.system('cls' if os.name == 'not' else 'clear')
def build_cells(width, height):
"""Create and return a width x heigh grid of two-tuples
... |
c57d58734d211092b66c4bc2974b973ba020bc5f | jgoman99/British-Bengal-Weekly-Crop-Reports | /Python Code/read_json.py | 356 | 3.515625 | 4 | def read_json():
import json
# Opening JSON file
f = open('data.json', )
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
for i in data['symbol']:
print(i)
# Closing file
f.close()
if __name__... |
82392919ed18941685a84bd6a3305b6650fcae6c | kyw5205/kyw_osp_repo | /py_lab2/my_pkg/do_set.py | 196 | 3.640625 | 4 | #!/usr/bin/python3
def pr_un_in(a,b):
unlist =list(a|b)
inlist = list(a&b)
u = sorted(unlist)
i = sorted(inlist)
print("=> union ", u)
print("=> intersection ", i)
|
7709915b3e161aed6e09e187111e1fffd89fcde4 | phenix502/python | /cat.py | 401 | 3.90625 | 4 | import sys
import codecs
def Cat(filename):
f = codecs.open(filename, 'r','utf-8')
for line in f:
print(line)
f.close()
# Define a main() function that prints a little greeting.
def Hello(name):
name = name + "!!!!!!!"
print('Hello',name)
def main():
#Cat(sys.argv[1])
Hello(sys.argv[1])
# This is the standa... |
f83ddcd18f163645378d2c65958cc0606a2d2d2b | gnbbgys/code_repo | /myrepo/decode_str.py | 1,449 | 3.84375 | 4 | #is mirror binary tree
"""
G
A A
B B
"""
class Node:
def __init__(self, name: str):
self.left = None
self.right = None
self.name = name
def __str__(self):
return self.name
def __eq__(self, other):
print("XXX==eq==XX")
... |
3b39e47c0ef211d7c89f9637afc39186bddb4962 | conglb/Leetcode-practice | /game-of-life.py | 1,204 | 3.53125 | 4 | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
m = len(board)
if m == 0:
return
n = len(board[0])
# check if cell on board
def check(x, y):
... |
249cb7c20135e16a03655294197cdd16a15f5f3d | geekonion/mytools | /evaluate.py | 399 | 3.90625 | 4 | import pdb
choose=input("buy or sell? default [1]\n1.buy\n2.sell\n:>")
high=float(input("please input high price:\n"))
low=float(input("please input low price:\n"))
if choose=='1':
buy=float(input("please input your buy price:\n"))
score=(high-buy)/(high-low)
elif choose=='2':
sell=float(input("please input... |
b209df1b3a82e165e2f42f8d33d7f2428eaa3578 | NurTasin/nhspc-2021-mock-1 | /i.py | 759 | 3.546875 | 4 | def listify(string):
lstring=[]
for i in range(len(string)):
lstring.append(string[i])
return lstring
t=int(input())
strings=[]
args=[]
for i in range(t):
strings.append(str(input()))
args.append(str(input()))
for i in range(t):
string=strings[i]
blanks=string.count("?")
argc... |
9b246f10cb7185b2a9d8b1b8be43b88786cc8b1e | MarcBouchonville/pythonPrograms | /exam/seconds/Parfait002.py | 1,665 | 3.59375 | 4 | # ex 2. Parfait.py
'''
1) FONCTIONS
'''
# determiner la liste des diviseurs d'un nb
def listing(nb):
liste = []
for i in range(1, nb):
if nb%i == 0:
#print (i, " / ", n)
liste.append(i)
#print ("liste : ", liste)
return liste
# determiner si... |
4cb1d47ff68e598d595dd5b78e6d937b959f7400 | MarcBouchonville/pythonPrograms | /lesson05/prog048.py | 1,099 | 3.78125 | 4 | # resolution d'equations - methode CRAMER
def det(a1, b1, c1, a2, b2, c2):
x = {}
y = {}
diviseur = ((a1 * b2) - (a2 * b1))
if diviseur != 0 :
x = ((c1 * b2) - (c2 * b1)) / diviseur
y = ((a1 * c2) - (a2 * c1)) / diviseur
else :
x = "division par zero"
y = ... |
51d09a5317420e3eb48cd6805a2859a40a48fb9b | MarcBouchonville/pythonPrograms | /lesson05/prog045c.py | 477 | 3.546875 | 4 | def fct(mots):
retour = ''
retour = '* '
let=0
for i in range (0, (len(mots)*2)) :
if i%2 == 0 or i == 0 :
#print (mots[let])
retour = retour + mots[let]
let+=1
else :
retour = retour + ' '
retour = retour + ' *'
r... |
eedf0ea8a3939b8efe7a6eac6dbd8b194bbc6214 | MarcBouchonville/pythonPrograms | /lesson02/prog003.py | 581 | 3.875 | 4 | print ("programme 2.3 - lecture de 4 nb entiers")
a = int ( input ("premier nombre : " ))
b = int ( input ("deuxieme nombre : " ))
c = int ( input ("troisieme nombre : " ))
d = int ( input ("quatrieme nombre : " ))
grand = 0
petit = 0
if a > b :
grand = a
petit = b
else :
grand = b
petit... |
8f7daf7ca1ab065d9e63a5e90a8fe40246ec3ffa | MarcBouchonville/pythonPrograms | /lesson03/prog033.py | 340 | 3.859375 | 4 | # 3.3 affichage en sapin
x = int(input("nombre de lignes d'étoiles : "))
d = x
for i in range(0, x+1):
y=0
i+=1
#print("")
print('-' * d, end="")
if (i%2 == 0):
print("")
else
d-=1
while y < i:
y+=1
print("*", end="")
print("")
... |
f5d91547216963a40053c15afb81e0d181151e19 | manuck/myAlgo | /개념/05 Stack2/04.QuickSort(2).py | 494 | 3.75 | 4 |
def quickSort(arr, lo, hi):
if lo < hi:
i, j = lo, hi
while i < j:
while i <= hi and arr[i] <= arr[lo]:
i += 1
while arr[j] > arr[lo]:
j -= 1
if i >= j: break
arr[i], arr[j] = arr[j], arr[i]
arr[lo], arr[j]... |
38b16736852d759f81e2409d6ffffebfdcb67ab1 | manuck/myAlgo | /개념/05 Stack2/04.QuickSort(1).py | 628 | 3.59375 | 4 |
def partition(a ,begin, end):
pivot = (begin + end) // 2
L = begin
R = end
while L < R:
while a[L] < a[pivot] and L < R:
L += 1
while a[R] >= a[pivot] and L < R:
R -= 1
if L < R:
if L == pivot:
pivot = R
a[L], a[R]... |
b990af411e19ad79dbae787dcb476d57823c44df | manuck/myAlgo | /개념/13 백트래킹/02.배낭문제(4)_재귀_메모.py | 862 | 3.6875 | 4 | # n번째 물건 부터 배낭을 담을지 결정한다.
w = [0, 5, 4, 6, 3]
v = [0, 10, 40, 30, 50]
N = 4
maxW = 10
def knapsack(k, W):
if W == 0 or k == 0: return 0
if memo[k][W] != -1: return memo[k][W]
case1 = case2 = 0
if W >= w[k]: # k번째 물건을 담는 경우
case1 = knapsack(k - 1, W - w[k]) + v[k]
case2... |
eeba2590990e53f2eb755b1b8fb2ddf054b59c4e | smiletoeveryone/python | /input_01.py | 304 | 4.03125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
name = input("What is your name?\n")
print("Nice to meet you, " + name)
age =int(input("How old are you?\n")) # you shoud make a type transform when you ask information what about numbers
age2 = age + 1
print("So next year you will be %d years old!" % age2)
|
0d62ca3cef75a668777133869a61130a27656766 | usmanzakari/assigment | /formula for pressure.py | 103 | 3.578125 | 4 | f=int(input("Enter the force:"))
a=int(input("Enter the area:"))
p=f/a
print("pressur: {}".format(p))
|
f95d064dc22e8312189b125c9771894733c61cf4 | usmanzakari/assigment | /formula for density.py | 88 | 3.734375 | 4 | m=int(input("Enter m:"))
v=int(input("Enter v:"))
p=m/v
print("density: {}".format(p))
|
bd4c50b8b27c8bce38494827db23870360601e88 | Slimgin/getting-started | /subnet.py | 474 | 3.84375 | 4 | #! /usr/bin/env python
input_ip = raw_input("Please input an IP address: ")
octet = input_ip.split(".")
if int(octet[0]) == 10:
print ("This is a Class A Private Network")
elif int(octet[0]) == 172 and 16 <= int(octet[1]) <= 31:
print ("This is a Class B Private Network")
elif int(octet[0]) == 192 and in... |
c842f1a23b98511f4e3ac0029ef0f4f1e1b5d855 | mateuskienzle/training-python | /ex-082-dividindo-valores-em-varias-listas.py | 443 | 3.765625 | 4 | valores = list()
pares = list()
impares = list()
while True:
n = (int(input('Digite um valor: ')))
valores.append(n)
if n% 2 == 0:
pares.append(n)
else:
impares.append(n)
pergunta = str(input('Quer continuar [S/N]? ')).upper()[0]
if pergunta == 'N':
break
print('=-' *30)
... |
51b18fb9210b639f7bc5632802642b899963962b | mateuskienzle/training-python | /ex-048-soma-impares-multiplos-de-tres.py | 354 | 3.890625 | 4 | soma = 0
contador = 0
for c in range(3, 501, 2):
if (c%3 == 0):
soma = soma + c
contador = contador + 1
print('A soma de todos os {} valores solicitados é: {}' .format(contador, soma))
''' Uma forma de abreviar "soma = soma + c" seria colocando apenas "soma += c". O mesmo vale pro caso do
"contador... |
82614dafd03622c7f20690306594a3f606b0ff1d | mateuskienzle/training-python | /ex-087-mais-sobre-matriz-em-python.py | 891 | 3.75 | 4 | matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
pares = maior_valor = soma_colunas = 0
for linha in range (0, 3):
for coluna in range (0, 3):
matriz[linha][coluna]= int(input(f'Digite um valor para a posição [{linha}, {coluna}]: '))
if matriz[linha][coluna]%2 == 0 :
pares += matriz[linha][col... |
216ddf788d4019fd83f1385fc29b1a17535f2e07 | mateuskienzle/training-python | /ex-050-soma-dos-pares.py | 495 | 3.78125 | 4 | soma = 0
cont = 0
for c in range(1, 7):
n = int(input('Digite o {}º número: ' .format(c)))
if (n%2==0):
soma = soma + n
cont = cont + 1
if soma == 0:
print('Você não informou nenhum número par, portanto a soma é igual a zero.')
else:
if cont == 1:
print('Como você só digitou {} ... |
3685a6a052243f986d8428ffbb602aa2c545b3eb | mateuskienzle/training-python | /ex-034-aumentos-multiplos.py | 464 | 4.03125 | 4 | valor_casa = float(input('Valor da casa: R$'))
salario = float(input('Salário do comprador: R$'))
anos_financiamento = int(input('Quantos anos de financiamento?'))
prestacao = valor_casa/(anos_financiamento*12)
print('Para pagar uma casa de R${:.2f} em {:.2f} anos, a prestação será de R$ {:.2f}' .format(valor_casa, ano... |
a7a31fb4115efcd978192b7fdf6bcf40afd0b468 | mateuskienzle/training-python | /ex-096-funcao-que-calcula-area.py | 233 | 3.515625 | 4 | def area(larg, alt):
a = larg * alt
print(f'A área de um terreno de {larg} x {alt} é de {a}m²')
print('Controle de terrenos')
print('-' *20)
l = float(input('largura (m): '))
h = float(input('altura (m): '))
area(l, h) |
58f022b1931595c56fd3d9d40054d1f906fec258 | mateuskienzle/training-python | /ex-029-radar-eletronico.py | 333 | 3.65625 | 4 | velocidade = int(input('Qual é a velocidade atual do carro? '))
multa = (velocidade - 80) * 7
if velocidade > 80:
print('\033[0:34:44m MULTADO! Você excedeu o limite de velocidade permitido que é de 80km/h!')
print('Você deve pagar uma multa de R${:.2f}' .format (multa))
print('Tenha um bom dia! Dirija com segu... |
85669c3bd54d8c2b84eb4b2682d414806322cb92 | mateuskienzle/training-python | /ex-039-alistamento-militar.py | 1,063 | 4.0625 | 4 | from datetime import date
nascimento = int(input('Ano de nascimento: '))
ano_atual = date.today().year
idade = (ano_atual-nascimento)
print('Quem nasceu em {} tem {} anos em {}.' .format(nascimento, idade, ano_atual))
if idade > 18:
data_alistamento = (idade-18)
ano_alistamento = (nascimento+18)
if data_ali... |
dfdc48c3cc68c316dd4f21725016f669f365d0b2 | WillDavid/Python-Exercises | /BuscaPython/algoritmoBusca02.py | 267 | 4.1875 | 4 | numeros = []
x = int(input("Informe a quantidade de numeros: "))
for i in range(x):
numero = float(input("Informe um número real: "))
numeros.append(numero)
lista = []
for i in numeros:
if i not in lista:
lista.append(i)
print("Lista Ordenada: ", lista)
|
6d3aba17b75e3eff3b706bc6ec4bdf1b583dc0a8 | katiemharding/ProgrammingForBiologyCourse2019 | /problemsets/PythonProblemSets/positiveOrNegative.py | 996 | 4.59375 | 5 | #!/usr/bin/env python3
import sys
# for testing assign a number to a value
unknown_number = int(sys.argv[1])
# first test if it is positive
if unknown_number>0:
print(unknown_number, "is positive")
if unknown_number > 50:
# modulo (%) returns the remainder. allows testing if divisible by
if unknown_number%3 == 0:
... |
636617754fecc41116144a0b257756b771a858bf | sainihimanshu1999/Data-Structures | /June2021/BackTrack/AllthePathFromSource.py | 311 | 3.671875 | 4 | '''Basic dfs backtracking'''
def paths(graph):
result = []
def dfs(node,path):
if node == n-1:
path.append(node)
result.append(node)
return result
for child in graph[node]:
dfs(child,path+[node])
dfs(0,[])
return result |
98e50d2ab89fdd30b9d4bc31249ae8340bddff8d | sainihimanshu1999/Data-Structures | /June2021/Graph/ReconstructInternary.py | 596 | 3.65625 | 4 | '''
using basic stack and and graph
'''
from collections import defaultdict
def iternary(tickets):
graph = defaultdict(list)
for u,v in tickets:
graph[u].append(v)
for u in graph.keys():
graph[u].sort(reverse= True)
stack = ['JFK']
result = []
while stack:
i = stack... |
56458708ccd5b285e54e956e5a7281d611afd93f | sainihimanshu1999/Data-Structures | /June2021/Graph/CourseSchedule2.py | 579 | 3.59375 | 4 | '''
we have to return the list of courses arranges in how they should be studied
'''
def courseSchedule(numCourses,prerequest):
source = [set() for _ in range(numCourses)]
destination = [set() for _ in range(numCourses)]
for d,s in prerequest:
source[d].add(s)
destination[s].add(d)
r... |
3436748155ebc6b899603964eba21b707190f509 | sainihimanshu1999/Data-Structures | /Practice Ds - Prev/stk_balanced.py | 760 | 3.96875 | 4 | from stack import Stack
def is_match(p1, p2):
if p1 == "(" and p2 == ")":
return True
elif p1 == "{" and p2 == "}":
return True
elif p1 == "[" and p2 == "]":
return True
else:
return False
def is_balanced(string):
s = Stack()
bal = True
index = 0
while ... |
69b6d9859a71997e59f3a029d774f6f4e33ad1aa | sainihimanshu1999/Data-Structures | /June2021/DP/MCTTree.py | 641 | 3.65625 | 4 | '''
we have to find minimum cost tree where we have to return the sum of non leaf nodes, where there is an inorder
traversal and through that inorder traversal the non leaf values are product of max from a slicing
'''
def mctTree(arr):
memo = {}
def dfs(i,j):
if i+1==j: return 0
if (i,j) in me... |
10214c5082580b191ba08b696a68cc03b4a4ada5 | sainihimanshu1999/Data-Structures | /Practice Ds - Prev/stackarray.py | 1,277 | 3.953125 | 4 | class EmptyStackError(Exception):
pass
class StackFullError(Exception):
pass
class Stack:
def __init__(self, max_size=10):
self.items = [None] * max_size
self.count = 0
def is_empty(self):
return self.count == 0
def is_full(self):
return self.count == len(self.i... |
df53b01e665db255e342ec59df0e42bca4ec0dc3 | sainihimanshu1999/Data-Structures | /Practice Ds - Prev/selectionsort.py | 315 | 3.6875 | 4 | def selection_sort(a):
for i in range(len(a)-1):
minIndex = i
for j in range(i+1, len(a)):
if(a[j] < a[minIndex]):
minIndex = j
if i != minIndex:
a[i], a[minIndex] = a[minIndex], a[i]
x = [89, 65, 98, 32, 51, 11, 19]
selection_sort(x)
print(x)
|
ce6f7020e54f6fffb38bb9b2e0e14345c21956d3 | sainihimanshu1999/Data-Structures | /Medium/CountingBits.py | 230 | 3.8125 | 4 | '''This is an easy question but we have to use basic logic or we can say it is hit and trial'''
def countBits(num):
result = [0]
while len(result)<=num:
result += [i+1 for i in result]
return result[:num+1]
|
aa1a936a0230518c6a2cacf11566f164db084f00 | sainihimanshu1999/Data-Structures | /Practice - DS-New/reversesdoublylinkedlist.py | 366 | 3.9375 | 4 | def reverseDLL(head):
#return head after reversing
t = None
curr = head
while curr:
#flipping the orientation of next and previous links
t = curr.prev
curr.prev = curr.next
curr.next = t
curr = curr.prev
if t:
#setting the head to the last element of t... |
2526483ff2d28aefa82bcc9e6dc35c6f9ed8fa69 | sainihimanshu1999/Data-Structures | /Practice Ds - Prev/evenoddthreading.py | 628 | 4.03125 | 4 | # this program is made using the threadings in python
# the concept of threading is bascially running two threads simultaneously
# one thread wait while otner one is completed
import threading as th
import time
even_event = th.Event()
odd_event = th.Event()
def even_function():
for i in range(0, 30, 2):
... |
a14518cacf584823ab1f4aca70b5f37283b5bf59 | sainihimanshu1999/Data-Structures | /Practice Ds - Prev/stacklinked.py | 1,315 | 3.75 | 4 | class EmptyStackError(Exception):
pass
class Node:
def __init__(self, value):
self.info = value
self.link = None
class Stack:
def __init__(self):
self.top = None
def is_empty(self):
return self.top == None
def size(self):
if self.is_empty():
... |
e245fe8941056308e8c94c2da52436fe76b05c00 | sainihimanshu1999/Data-Structures | /June2021/Heaps/MaximumProductOfTwoElements.py | 305 | 3.8125 | 4 | '''
baic tracking of two largest number in the array and then finding thier product according to our need
'''
def maxProd(nums):
a=b=-1
for num in nums:
if num>a:
a,b = num,a
elif num>b:
b=num
return (a-1)*(b-1)
nums = [1,5,4,5]
print(maxProd(nums)) |
24e046bed5e4ed18ffa91bb9d82af34e736199d3 | sainihimanshu1999/Data-Structures | /Medium/CombinationSum4.py | 883 | 3.515625 | 4 | '''There are various method to do this, i would do this my dp memoization'''
from typing import NewType
def combinationSum(nums,target):
count =0
memo = {}
def dp(nums,target,memo):
if target in memo:
return memo[target]
else:
count = 0
... |
37c477142ce0557fdf27aba4bfe5b4c3779c4845 | sainihimanshu1999/Data-Structures | /June2021/DP/MartixBlockSum.py | 1,088 | 3.671875 | 4 | '''
In this question we will use prefix matrix by adding both rows and columns and then finding the answer
'''
def matrixBlockSum(matrix,k):
m = len(matrix)
n = len(matrix[0])
prefix = [[0]*n for _ in range(m)]
#row prefix
for i in range(m):
prefix[i][0] = matrix[i][0]
for j in r... |
1f2497fcc321c503e90ea8156c6094c39a6a60ab | sainihimanshu1999/Data-Structures | /Practice-DS-march2021/checkiftwomatrixareindentical.py | 382 | 3.703125 | 4 | '''
Program to check that the two matrix that are given are identical or not
'''
'''
for two matrix to be equal, the number of rown and columns should be equal as well as there elemnts
should be equal too
'''
def aresame(A,B):
n = 4 #4*4 matrix
for i in range(n):
for j in range(n):
if (A[... |
4c0c609675021b37297a9a1e68b3f984ff7a0cec | math-yew/my-python-scripts | /run.py | 804 | 3.5625 | 4 | import webbrowser
def run(action):
print("\n")
if action == "name":
name()
elif action == "web":
web()
elif action == "mult":
mult()
else:
other()
myName = "buddy"
def name():
fname = input("What is your name? ")
print("Hello there, " + fname)
global myName
myName = fname
restart()
def web():... |
c97df9692c0d772e8cef6a60bdb23a59ba803ccd | sxd7/p_ython | /python.py | 413 | 4.21875 | 4 | Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import math
>>> radius=float(input("enter the radius of the circle:"))
enter the radius of the circle:5
>>> area=math.pi*radius*radius;
>>> pr... |
d9e6d12add4432e9fe05c6923fbada99673438e1 | YohanCS/FilteringArrays | /RangeFilter.py | 1,020 | 3.84375 | 4 | # constants for range min and range max of values
range_min = 0.03
range_max = 50.0
# Implement update of an array and filter range values of an array
class RangeFilter:
# Crops all values below range_min (resp above range_max)
# and replaces them with the range_min value (resp above range max)
#... |
6ac8be51130acd90ee46b97418fda5abd6febeeb | NAVEEN2530/GUVI | /task/natruralseq.py | 105 | 3.515625 | 4 | def seqence(n):
for i in range(1,n+1,1):
print(i)
n=int(input("enter range: "))
seqence(n) |
fcdcc8dba5118e27a5e9c4559a406dca259f2a66 | NAVEEN2530/GUVI | /task/while3.py | 757 | 3.78125 | 4 | def dist():
c=abs(b-a)
return c
def tab(c):
print("1.micro(10 rs/km)")
print("2.prime(20rs/km)")
print("3.mini(50rs/km)")
print("4.suv(80rs/km)")
t=int(input("enter the type of cab"))
if(t==1):
fare = 10*c
elif(t==2):
fare=20*c
elif(t==3):
fare=50*c
elif(t==4):
... |
5af099c2243b3bea059dcd1370523ead724dc9fa | ilsur-hunter00/KNITU-KAI-projects | /1st semestr/Python/LAB2.py | 161 | 3.875 | 4 | import math
R1 = int(input("R1: "))
R2 = int(input("R2: "))
R1 > R2
S1 = math.pi*R1**2
S2 = math.pi*R2**2
S3 = S1 - S2
print(S1, S2, S3)
|
041a9f165d025e3b905c8b2c1393d3da8b3660fe | batra98/mariogame | /20171114_Assign1/ending.py | 629 | 3.5625 | 4 | class End():
def __init__(self,map_mario):
self.map_mario=map_mario
self.stair_right=["## ","#### ","#### ","###### ","###### ","#########","#########"]
self.stair_left=[" ##"," ####"," ####"," ######"," ######","#########","#########"]
self.castle=[]
def draw_left(self,x,... |
67585f2cf71511458d9a0d9bcc5c2f00a7895aa4 | DiamondHusky/CrawlerDemo | /03CrawlerAdvanced/thread_demo/demo4.py | 1,482 | 3.625 | 4 |
# Lock版生产者和消费者模式
import threading
import random
import time
gMonney = 1000
gLock = threading.Lock() # 全局锁
gTotalTime = 10
gTimes = 0
class Producer(threading.Thread):
def run(self):
global gMonney
global gTimes
while True:
money = random.randint(100,1000)
gLock.... |
201b0e4e5e6e6057deb0427cd0d4d66694e78dfe | PradeepNingaiah/python-assginments | /hemanth kumar python assginment/3.loops.py | 3,194 | 4.28125 | 4 |
#1.Write a program to print “Bright IT Career” ten times using for loop
x=[1,2,3,4,5,6,7,8,9,10]
for p in x:
print("Bright IT Career")
#-----------------------------------------------------------------------------
#2. Write a python program to print 1 to 20 numbers using the while loop.
x=0
whi... |
222f287965120511ecb52663994e286d2752d363 | PradeepNingaiah/python-assginments | /hemanth kumar python assginment/14.exception.py | 1,734 | 4.5625 | 5 |
#1. Write a program to generate Arithmetic Exception without exception handling
try:
a = 10/0
print (a)
except ArithmeticError:
print ("This statement is raising an arithmetic exception.")
else:
print ("Success.")
#--------------------------------------------------------------------------... |
985eb5db25353cedb541452a999e79411cad3704 | TristinHillebrand/prac5 | /part3.py | 326 | 4.09375 | 4 | number = []
for i in range(0,5,1):
num= int(input("please enter a number"))
number.append(num)
print("the first number is", number[0])
print("the last number is", number[4])
print("the smallest number is", min(number))
print("the largest number is", max(number))
print("the average number is", sum(number)/len(nu... |
46af81b2b25757dedbc7c40c571dfca74c60fb69 | christianns/Curso-Python | /08_Programación_orientada_a_objetos/03_Atributos_y_métodos.py | 4,056 | 4.375 | 4 | '''
Atributos y métodos
Si hay algo que ilustre el potencial de la POO esa es la capacidad de definir
variables y funciones dentro de las clases, aunque aquí se conocen como atributos
y métodos respectivamente.
'''
# Atributos
# A efectos prácticos los atributos no son muy distintos de las variables,
# la diferencia... |
5c805c9c2964f9a1ee57fc8549e2dae20c2aa693 | christianns/Curso-Python | /05_Entradas_y_salidas/06_Ejercicio_3.py | 909 | 4.3125 | 4 | '''
Ejercicio 3
Crea un script llamado descomposicion.py que realice las siguientes tareas:
Debe tomar 1 argumento que será un número entero positivo.
En caso de no recibir un argumento, debe mostrar información acerca de cómo
utilizar el script.
El objetivo del script es descomponer el número en unidades,
decenas, ce... |
1a544cb42c9ad4753c9759abcf5df19547c09897 | christianns/Curso-Python | /03_Control_de_flujo/20_Ejercicio_15.py | 2,301 | 4.28125 | 4 | # Problema 15: Realiza un sistema para controlar el ingreso a un cine, donde ofrezca
# películas de terror, acción y aventuras. En cada opción tenga restricción por edad.
# Categorías $ Edad (%)
# Terror 18 - 55
# Acción 10 a mas
# Aventura 4 a mas
# Análisis: Para la solución de es... |
f891132a02dfab65990f796af71695f2d362fd90 | christianns/Curso-Python | /02_Operadores y expresiones/04_Expresiones_anidadas.py | 299 | 3.796875 | 4 | # Estas expresiones permiten juntar dos o mas cadenas de datos
a = "Hola "
b = "y "
c = "Adios"
abc = a + b + c
print ("Saludos", abc)
# tambien se puede multiplicar las cadenas
amor = 2 * (a+b+c)
print ("El amor multiplicado es", abc)
# tambien se pueden comparar
print (a == c)
print (a != c)
|
d114c4ca0205f54dd4f3c90e48cd1d7440fb1184 | christianns/Curso-Python | /07_Errores_y_excepciones/08_Ejercicio_4.py | 958 | 4.25 | 4 | '''
Ejercicio 4
Realiza una función llamada agregar_una_vez(lista, el) que reciba una lista y un elemento.
La función debe añadir el elemento al final de la lista con la condición de no
repetir ningún elemento. Además si este elemento ya se encuentra en la lista
se debe invocar un error de tipo ValueError que debes cap... |
dd44d58ab9c771cfbeb0a0c0099d12170ab62839 | christianns/Curso-Python | /04_Coleccion_de_datos/05_Diccionarios.py | 2,425 | 4.375 | 4 | # Diccionarios.
# Son junto a las listas las colecciones más utilizadas y se basan en una
# estructura mapeada donde cada elemento de la colección se encuentra
# identificado con una clave única, por lo que no puede haber dos claves iguales.
# En otros lenguajes se conocen como arreglos asociativos.
# Los diccionarios... |
c9a753fc4a85c8874a49112449b6c924397339ab | christianns/Curso-Python | /06_Programacion_de_funciones/09_Ejercicio_1.py | 541 | 4.21875 | 4 | '''
Ejercicio 1 Realiza una función llamada area_rectangulo(base, altura) que devuelva
el área del rectangulo a partir de una base y una altura.
Calcula el área de un rectángulo: su base y altura ingrese por teclado.
Nota: El área de un rectángulo se obtiene al multiplicar la base por la altura.
'''
base = int(input(... |
5c8ce54a695bc87fa2e214eed81bea061134739e | christianns/Curso-Python | /04_Coleccion_de_datos/06_Pilas.py | 1,090 | 4.53125 | 5 | '''
Pilas
Son colecciones de elementos ordenados que únicamente permiten dos acciones:
- Añadir un elemento a la pila.
- Sacar un elemento de la pila.
La peculiaridad es que el último elemento en entrar es el primero en salir.
En inglés se conocen como estructuras LIFO (Last In First Out).
Las podemos crear c... |
93bc34d26b8b86617893b8a10bb30adf8bf36244 | christianns/Curso-Python | /04_Coleccion_de_datos/12_Ejercicio5.py | 515 | 3.90625 | 4 | # Ejercicio 6
# Al realizar una consulta en un registro hemos obtenido una cadena de texto corrupta al revés.
# Al parecer contiene el nombre de un alumno y la nota de un exámen.
# ¿Cómo podríamos formatear la cadena y conseguir una estructura como la siguiente?
print ('<nombre apellido> ha sacado un Nota de <nota>.'... |
dac0c4fbd04f7c8d193cc2dd8bb3a0cb42948202 | christianns/Curso-Python | /06_Programacion_de_funciones/07_Funciones_recurcivas.py | 1,154 | 4.65625 | 5 | '''
Funciones recursivas
Se trata de funciones que se llaman a sí mismas durante su propia ejecución.
Funcionan de forma similar a las iteraciones, pero debemos encargarnos de
planificar el momento en que dejan de llamarse a sí mismas o tendremos una función rescursiva infinita.
Suele utilizarse para dividir una tare... |
5f6f2db26ecd905182fa447cf6abad7601576570 | christianns/Curso-Python | /01_Tipos_de_datos/04_Booleanos.py | 264 | 3.75 | 4 | # Este es un ejemplo de numericos del tipo booleanos
# Este entrega dos valores False o True
a = True
b = False
# Este print indica el tipo de dato
print (type(a))
print (type(b))
# Este print devulve el valor numerio del booleanos
print (int(a))
print (int(b))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.