blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
b380ff419257316e675334943842995e14c26db6 | HashiniK/StudentProgressPrediction | /W1790198_Q3.py | 3,827 | 3.890625 | 4 | passes=0
defers=0
fails=0
countProgress=0
countTrailer=0
countRetriever=0
countExclude=0
mainCount=0
progression=0
def verticalHistogram():
global countProgress,countTrailer,countRetriever,countExclude
print("You have quit the program")
print("")
print ("-----VERTICAL HISTOGRAM-----")... |
c4831a400a27fdbdc55c6d19de49cbf7721104bc | Robert-Becker/Python-Project | /Project1Part3.py | 618 | 4.03125 | 4 | print("")
print("")
print("Select Service")
print("")
choice = input("Makeover(M) or HairStyling(H) or Manicure(N) or Permanent Makeup(P): ")
if choice == "M":
cost = 125
elif choice == "H":
cost = 60
elif choice == "N":
cost = 35
elif choice == "P":
cost = 200
print("")
print("Select Disc... |
15be8bceb7e5ff759edd95012a671ef9bad452b0 | Robert-Becker/Python-Project | /Project5-1.py | 1,834 | 3.90625 | 4 | #Original Code Written by Robert Becker
#Date Written - 6/25/2019
#Program was written to calculate end of semester scores for students by using an input file with a single space used as the delimiter between items
inputFile = open("scores.txt", "rt") #Define Input FIle Variable, opens file to read text
fileDat... |
c0b5522a54c4607fd8f088b7824a32a9d44f151c | djstull/COMS127 | /class5/twofunctions.py | 386 | 3.84375 | 4 | def max(num1, num2):
if num1 > num2:
largest = num1
elif num2 > num1:
largest = num2
return largest
print(max(4, 5))
print(max(8, 9))
print(max(-4, -5))
print(max(4000, 6000))
def is_div(divend, divise):
if divend % divise == 0:
return True
else:
return False
#the ... |
c3317d237ba9cfb9a6bdd2f857d09e5f00ad30fc | djstull/COMS127 | /lab6/piggy.py | 721 | 4 | 4 | # converts the words to piggy latin
def convert_word(word):
from vowels import vowelfinder
vowel = vowelfinder(word)
first_letter = word[0]
if first_letter in ["a", "e", "i", "o", "u"]:
return word + "way"
else:
return word[vowel:] + word[:vowel] + "ay"
print(convert_word("google")... |
6aa7e4d251675baf3f0f3af97d70ae2f27dd55e0 | djstull/COMS127 | /ultimatecoinage.py | 1,025 | 4 | 4 | #Write a program to calculate the coinage needed for a given amount of change.
amount = int(input('Please input the total change in cents): '))
hundreds = amount // 10000
amount = amount % 10000
fifties = amount // 5000
amount = amount % 5000
twenties = amount // 2000
amount = amount % 2000
tens = amount // 1000
amoun... |
9a0dc3a6736fe4139f6658b6dde626a9c6bc9bff | djstull/COMS127 | /lab1/coinage.py | 389 | 4.0625 | 4 | #Write a program to calculate the coinage needed for a given amount of change.
amount = int(input('Please input the amount of cents: '))
quarters = amount // 25
amount = amount % 25
dimes = amount // 10
amount = amount % 10
nickels = amount // 5
pennies = amount % 5
print(' ')
print(quarters, "quarters\n")
print(dime... |
142cb67953b8138f718d46206f2ec63b3b4f9cdb | Mychailo02/laboratorna_2_py | /PythonApplication6/PythonApplication6.py | 288 | 3.953125 | 4 | x = float(input("Введіть значення агрументу - "))
A = float(input("Введіть значення константи - "))
if x<0:
y = x
print(y)
elif A>0:
y = A
print(y)
else:
print("Немає розв'язків")
|
2f3913d011987d472f7f8ee29e838275b5109ae0 | IsaacDiaz09/Soluciones-HackerRank-repo | /30 dias de codigo HackerRank/24.) Arbol de busqueda binaria Lvl-Order/solucion.py | 1,450 | 3.859375 | 4 | # https://www.hackerrank.com/challenges/30-binary-trees/problem?isFullScreen=false
import sys
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
... |
3fc0226c6bdb8eeacf35635e21e1b6772e648e63 | IsaacDiaz09/Soluciones-HackerRank-repo | /30 dias de codigo HackerRank/3.) Operadores/solucion.py | 546 | 3.734375 | 4 | # https://www.hackerrank.com/challenges/30-operators/
def mealTotalCost(base,tip,tax):
totalCost = base + (base*(tip/100)) + (base*(tax/100))
# halla el valor total calculando a cuanto equivale cada % y entrega la respuesta en un entero redondeado
return int(round(totalCost))
if __name__ == "__main__":
... |
198fd801462e9e255b22788fa2f79ed1b0220b18 | nneuro/lesson1 | /example.py | 435 | 3.859375 | 4 |
def check(triplets):
if 'ATG' in triplets and 'TAA' in triplets:
if triplets.index('ATG') < triplets.index('TAA'):
return True
else:
return False
x = 0
triplets = ['ATG', 'TAA', 'TAG', 'ATG', 'GGC', 'TAA']
while check(triplets) == True :
print(f'цикл номер {x}, check = {chec... |
d58e2b914284a47fc558b730364ccadce3a4a772 | Muhammadali-gold/python-portfolio | /python-projects/matplot.py | 447 | 3.53125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x = np.array([[0, 0, 255], [255, 255, 0], [0, 255, 0]])
plt.imshow(x, interpolation='nearest')
plt.show()
def addGlider(i, j, grid):
"""adds a glider with top left cell at (i, j)"""
glider = np.array([[0, 0, 255],
... |
e0d1f159e8db74f3dc7d8a3a1a2a6c0f6d448c42 | Muhammadali-gold/python-portfolio | /python 100 days/tip-calculator/src/main.py | 363 | 4 | 4 | if __name__ == '__main__':
print('Welcome to the tip calculator ')
total_bill=float(input('What was the total bill? '))
person_count=int(input('How may people split bill? '))
percent=int(input('What percentage tip would you like to give? 10, 12, or 15? '))
print(f'Each person should pay ${round(tota... |
0cb6cc118fa6988b4e6a8a38e036ef9e8736e451 | markaalvaro/advent-2020 | /day2.py | 710 | 3.9375 | 4 | def count_occurences(password, character):
count = 0
for i in range(0, len(password)):
if password[i] == character:
count += 1
return count
def find_num_valid_passwords():
numValid = 0
for line in open('day2_input.txt'):
fragments = line.split(' ')
expectedRange ... |
8ee6857c5bf0ca2ab86d1f5f1ca6139bdefeaf2b | maleficarium/manga-downloader | /manga-downloader.py | 15,167 | 3.609375 | 4 | ## DESIGN
## This script takes in an url pointing to the main page of a comic/manga/manhwa in Batoto.net
## It then parses the chapter links, goes to each, downloads the images for each chapter and compresses
## them into zip files.
## Alternatively, we may be able to specify a name, and have the script search for it a... |
917d4ff1aca38a81a6c2ec51d13f535109de534e | anaves/CursoPython3-Libertas | /etapa4/ExemploFuncao.py | 162 | 3.640625 | 4 | def soma(a,b):
return a+b
def sm(a,b):
return a+b,a*b
print('início')
r=soma(1,6)
print(r)
x,y=sm(3,6)
print('soma:{}, multiplicação:{}'.format(x,y)) |
22dcbe99009dcb889dc176bc99379c39f97c773f | tenglibai/Data-struct | /1.基本数据结构/栈-进制转换.py | 358 | 3.546875 | 4 | def baseConverter(decNumber, base):
digits = "0123456789ABCDEF"
stack = []
while decNumber > 0:
rem = decNumber % base
stack.append(rem)
decNumber = decNumber // base
newString = ""
while not stack == []:
newString = newString + digits[stack.pop()]
return newString
assert baseConverter(25, 2) == '11001'... |
b27d9d674f57863a994a1f6f98e9711a12d574a3 | Aries5522/daily | /2021届秋招/leetcode/递归回溯分治/添加不同的括号.py | 717 | 3.796875 | 4 | class Sulotion:
def diffWaysToCompute(self, input):
if input.isdigit():
return [int(input)]
res = []
for i, char in enumerate(input):
if char in ["+", "-", "*"]:
left = self.diffWaysToCompute(input[0:i])
right = self.diffWaysToCompute(i... |
a0b187be9d8441ac232d0cd63c65f534f7dfd1f9 | Aries5522/daily | /2021届秋招/leetcode/paixu.py | 2,832 | 3.84375 | 4 | def bubble_sort(numbs):
for i in range (len(numbs)-1):
for j in range (len(numbs)-i-1):
if numbs[j]>numbs[j+1]:
numbs[j],numbs[j+1]=numbs[j+1],numbs[j]
return numbs
# 冒泡排序的思想:就是每次比较相邻的两个书,如果前面的比
# 后面的大,那么交换两个数,关键点在于,一次循环之后,
# 最大值必然放到最后一个去了,那么我men第二次循环的次数就
# 少了一个,如同程序所看。直到循环... |
9238816b49a3cfaf29a77679b877f95ce476d981 | Aries5522/daily | /2021届秋招/leetcode/排序/各种排序.py | 1,144 | 4.09375 | 4 | def merge_sort(list0):
import math
if len(list0)<2:
return list0
mid=math.floor(len(list0)/2)
left,right=list0[0:mid],list0[mid:]
return merge(merge_sort(left),merge_sort(right))
def merge(list1,list2):
list3=[]
while list1!=[] and list2!=[]:
if list1[0]<list2[0]:
... |
b0b07b894931ec3d9caabfd3d7cd3adc194ba972 | Aries5522/daily | /2021届秋招/leetcode/面试真题/美团/美团3.py | 1,016 | 3.5 | 4 | def union_find(nodes, edges):
father = [0] * len(nodes) # 记录父节点
for node in nodes: # 初始化为本身
father[node] = node
for edge in edges: # 标记父节点
head = edge[0]
tail = edge[1]
father[tail] = head
for node in nodes:
while True: # 循环,直到找到根节点
father_of_nod... |
e61ae13b383db473ce0b6bd1603ad374bfdb3eb0 | Aries5522/daily | /2021届秋招/leetcode/二分查找/二分查找.py | 734 | 3.953125 | 4 | """
二分查找模板:
[l, r) 左闭右开
def binary_search(l, r):
while l < r:
m = l + (r - l) // 2
if f(m): # 判断找了没有,optional
return m
if g(m):
r = m # new range [l, m)
else:
l = m + 1 # new range [m+1, r)
return l # or not found
"""
"""
完全平方
"""
cl... |
f93c5949f051aa1e1a8be47e98d1796a97eeb088 | Aries5522/daily | /2021届秋招/leetcode/DFS/字符串排列.py | 1,717 | 3.6875 | 4 | """
一般来说做不出来 感觉
dfs做法
交换两者顺序
确定搜索
判断搜索终止条件
x到倒数第二位就终止
因为最后一位确定了
如果不终止的话就
跳下一位
一直到跳出为止然后开始回溯
"""
# from typing import List
#
#
# class Solution:
# def permutation(self, s: str) -> List[str]:
# res = []
# c = list(s)
#
# def dfs(x):
# if x == len(c) - 1:
# ... |
291516016fdb34d23458247953670fcd2def6a85 | Aries5522/daily | /2021届秋招/leetcode/栈/队列最大值.py | 1,182 | 3.6875 | 4 |
'''
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
'''
##定义一个辅助栈实现,空间换时间,这个辅助栈单调递减.进来一个教大的,那么前面那个小的就都要走.
"""
https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/
"""
class MaxQueue:
def __init__(self):
self.res = []
... |
c86cac8eb810c6d817d150b21d40f8a24d07e81b | Aries5522/daily | /2021届秋招/leetcode/DFS/回溯全排列.py | 978 | 3.828125 | 4 | """
result = []
def backtrack(路径, 选择列表):
if 满足结束条件:
result.add(路径)
return
for 选择 in 选择列表:
做选择
backtrack(路径, 选择列表)
撤销选择
作者:labuladong
链接:https://leetcode-cn.com/problems/permutations/solution/hui-su-suan-fa-xiang-jie-by-labuladong-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得... |
be7db40d0e8a04568fa83556e047f116127dd153 | Aries5522/daily | /CPP/cppworkspace/ieee_test3.py | 299 | 3.5 | 4 | import numpy
import scipy
A=[3,2]
S=[3,1,5]
# A = list(map(int, input().rstrip().split()))
# S = list(map(int, input().rstrip().split()))
S.sort()
for i in range(len(S)):
for j in range(len(A)):
if S[i] < A[j]:
A.insert(j,S[i])
break
for i in A:
print(i) |
7ea27b712e9f3bf4faedd2dbf71d2dd720123209 | Aries5522/daily | /2021届秋招/leetcode/拓扑排序/合并区间.py | 292 | 3.5625 | 4 | data = [[1, 'B'], [1, 'A'], [2, 'A'], [0, 'B'], [0, 'a']]
#利用参数key来规定排序的规则
result = sorted(data,key=lambda x:(x[0]))
print(data) #结果为 [(1, 'B'), (1, 'A'), (2, 'A'), (0, 'B'), (0, 'a')]
print(result) #结果为 [(0, 'a'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A')]
|
e31599e77ca4514f91bccb5f26ad32293fe6dfbb | os-utep-master/python-intro-djr2344 | /w_cc.py | 4,317 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 31 21:23:58 2019
@author: Derek
Sources Cited:
method for removing non-alphanumeric characters (lines 20 -> 22):
<https://stackoverflow.com/questions/1276764/stripping-everything-but-alphanumeric-chars-from-a-string-in-python>
"""
import sys # comman... |
a417c87eb913067a78ed822d16ca440811619258 | PanoStiv/algorithms | /Linked list (Συνδεδεμένη λίστα)/ordered_list_example.py | 1,790 | 3.875 | 4 | from linked_list import LinkedList
from random import randrange
class OrderedList(LinkedList):
def __init__(self):
super().__init__()
def insert(self, data):
if self.empty():
self.insert_start(data)
elif data < self.head.data:
self.insert_start(data)
... |
c2c47a482c392499be6f990faaf3407503edbb73 | PanoStiv/algorithms | /Linked list (Συνδεδεμένη λίστα)/linked_list.py | 1,053 | 3.96875 | 4 | class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def empty(self):
return self.head is None
def insert_start(self, data):
n = Node(data)
n.next = sel... |
9a29246f53a94dd803b6c30cbec5e2837557f3bd | mirceadino/Blackjack | /cards/Deck.py | 2,385 | 3.703125 | 4 | from random import shuffle
from cards.Card import Card
from game.Exceptions import BlackjackException
class Deck():
'''
Class used for handling a deck of cards.
'''
def __init__(self):
'''
Constructor for a Deck.
'''
self.pack = [] # pack = all cards of the deck
... |
5bad2f32074ac303626daaf7d4e2e0f931b31bb1 | LikhithShankarPrithvi/College_codes | /python/problem.py | 259 | 3.59375 | 4 | x=int(input("enter your number"))
a=[]
n=0
temp=x
while x!=0:
x=x//10
n=n+1
print("your number length=",n)
x=temp
while x!=0:
z=x%10
a.append(z)
x=x//10
a.reverse()
for i in range(0,n):
print(a)
a[i]=0
|
86eda09e9afb6230ab6aab95f91a1d740682e69d | LikhithShankarPrithvi/College_codes | /python/problem1.py | 252 | 3.828125 | 4 | x=int(input("enter your number"))
n=0
temp=x
while x!=0:
x=x//10
n=n+1
print("your number length=",n)
x=temp
for i in range(0,n):
for j in range(0,i):
print(end=" ")
print(x)
x=x%(10**(n-i-1))
|
f84916da1481dc054dc0219cb0943f41309e4bf6 | jayse45/alx-higher_level_programming-1 | /0x06-python-classes/1-square.py | 192 | 3.765625 | 4 | #!/usr/bin/python3
"""class square defined by size"""
class Square:
"""private attribute instance size"""
def __init__(self, size):
"""new size"""
self.__size = size
|
1c6393f8a3b3011ac59a5d3d282b6731eadf6fcf | Arsen339/Skillbox-functional-programming | /practice2.py | 1,441 | 3.75 | 4 | ops = {
"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"*": lambda x, y: x * y,
"/": lambda x, y: x / y,
"//": lambda x, y: x // y,
"%": lambda x, y: x % y
}
total = 0
def calc(line):
print(f"Read line {line}", flush=True) # flush-вывод сразу после команды print без буферизации
... |
6e35b4dcb3cf64c0d7a2df0f43bbdaab476f8002 | Aakash-Dogra/Mortality-Rate-Analysis-US | /Mortality_Rate_Analysis.py | 37,269 | 3.984375 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="darkgrid", color_codes=True)
def birth_death_ratio(df, df2):
"""
In this function, we have performed analysis in terms of race or ethnicity of an individual. This analysis is
further don... |
b2a5cdffa4dc2d5a67652a4307ad11facd7bb492 | jindalpankaj/python-sklearn-in-r-shiny | /nlp.py | 2,692 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 4 15:09:53 2020
@author: Pankaj Jindal
"""
# This is a project to begin learning NLP; influenced by a Thinkful webinar.
import pandas as pd
import numpy as np
import sklearn
import re
import matplotlib.pyplot as plt
data = pd.read_csv('https://github.com/Thinkful-Ed/dat... |
c0827d86fc184e95229d96da18e196a24f123aff | edhaz/exercism-projects | /python/raindrops/raindrops.py | 238 | 3.671875 | 4 | def raindrops(number):
answer = ''
factors = {3: 'Pling', 5: 'Plang', 7: 'Plong'}
for i in factors:
if number % i == 0:
answer += factors[i]
if answer == '':
return str(number)
return answer |
07685415a7a84d9daf4330543e2b56a2c6783ac6 | Reisande/ProjectEuler | /Project Euler 9.py | 2,492 | 3.75 | 4 | def triples_generator(input_size_of_terms): # argument of triples_generator is how large the sum of triples can be
def ozanam_generator(term_ozanam): # argument is just how many terms are generated
term_ozanam += 1
numerator = ((4 * term_ozanam) + 3)
denominator = ((4 * term_ozanam) + 4)
... |
10e452d8689027a882425e4c31329c3348599379 | Jithendrachowdary48/Python-Lab | /Lab_5 Linear Search User Inputs.py | 365 | 3.953125 | 4 | #Linear Search by User input
#Inputs
print("Enter an array")
l=list(map(int,input().split()))
find=int(input("Enter a digit to find "))
def linearsearch(a,search):
for i in range(len(a)):
if a[i]==find:
return i
pos=linearsearch(l,find)
if pos==None:
print("Element Not Found")
el... |
edc975992907520af4ccf3318da0470c8eb7a9b0 | Jithendrachowdary48/Python-Lab | /Lab_4 Transpose of Sparse Matrix.py | 976 | 4.03125 | 4 | # Function to represent the Sparse Matrix
def sparse_matrix(arr):
sp = []
r = len(arr)
c = len(arr[0])
for i in range(r):
for j in range(c):
if arr[i][j]!=0:
sp.append([i,j,arr[i][j]])
return sp
def trans(arr):
res = []
for i in arr:
... |
8e2d5d8ae6120354932d2a3874610dfbc88c39ed | Jithendrachowdary48/Python-Lab | /Lab_9 27-10 pop push exit display From Stack.py | 187 | 3.65625 | 4 | #program to implement pop push and exit
stack = [10,20,30]
print(stack)
#push
stack.append(40)
stack.append(50)
print(stack)
#pop
print(stack.pop( ))
print(stack)
exit
|
2d05b1b979779617ce76b15b16f6030b4691cfb9 | baltornat/programming | /python/security/SecLab1/Solutions/Solution5.py | 978 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 15:22:20 2020
@author: marco
Esercizio #5 SecLab1:
-Provide the value of 'i'
"""
import random
import hashlib as h
pool = b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' #Item pool
out = ""
while out[:5] != "00000": ... |
ba539c0e7b1291fafbcad61a647a1b9faade5cf3 | Abrown1211/Python-Practice | /Python-Practice/week-6-review-Abrown1211/random_shapes.py | 2,040 | 3.859375 | 4 | #creates a file with random shape points written to it.
from random import *
from graphics import *
def userFileInput():
fileName = input("Enter the drawing file name to create: ")
shapeCount = int(input("Enter the number of shapes to make: "))
fileName = open(fileName, "w")
return fileName, shapeCoun... |
5fbb53b4895ee1a50a8d49f68dedc40b34d3e237 | Abrown1211/Python-Practice | /Python-Practice/week-7-review-Abrown1211/stock_seller.py | 2,120 | 3.859375 | 4 | class StockHolding:
def __init__( self, symbol, totalShares, initialPrice ):
self.symbol = symbol
self.totalShares = totalShares
self.initialPrice = initialPrice
def getSymbol(self):
return self.symbol
def getNumShares(self):
return self.totalShares... |
18a4c56bcc6207df2464276b34c71246ac3c4d98 | joao-fontenele/NPuzzleSolver | /misc.py | 3,828 | 3.53125 | 4 | #!/usr/bin/env python
#coding: utf-8
from NPuzzle import NPuzzle
from search import a_star
from search import a_star_tree
from search import ida_star
def print_solution(expanded_nodes, steps, path):
print '{} nodes expanded.'.format(expanded_nodes)
print '{} steps to solution.'.format(steps)
for move, st... |
61f7f07a765f2f305f05471e4d6177a7d6707616 | samwelkinuthia/snakey | /samples/jaden.py | 264 | 3.859375 | 4 | def jaden(sentence):
return ' '.join(i.capitalize() for i in sentence.split())
# for user input scenario
# sentence = input("enter a sentence: ")
# print(jaden(sentence))
#test scenario
# print(jaden("Why does round pizza come in a square box?")) |
f83fcdb7cf66fc15b70ce5df0cf93eb25e9074b5 | samwelkinuthia/snakey | /samples/bubble_sort.py | 427 | 3.9375 | 4 | def bubble_sort(n):
swap = False
while not swap:
print('bubble sort: ' + str(n))
swap = True
for j in range(1, len(n)):
if n[j - 1] > n[j]:
swap = False
temp = n[j]
n[j] = n[j - 1]
n[j-1] = temp
test = [2, 16, 1... |
8b0f03d4d4e0db2bb35c8ad1db0c8e0381f56ed4 | samwelkinuthia/snakey | /samples/merge_sort.py | 548 | 3.90625 | 4 | def merge(left, right):
# empty dic to hold data.
result = []
# i and j, two indices, beginning of both right and left list
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.appe... |
bb0bd9dca9195533f9031ce4aee299613ef9b81f | samwelkinuthia/snakey | /samples/largest_no.py | 149 | 3.65625 | 4 | def max(n):
largest = 0
for i in n:
if i > largest:
largest = i
return largest
print(max([11, 2, 14, 5, 0, 19, 21])) |
dd6b6c00d59cb5a26089744badf9ac3e3588e7c7 | davronismoilov/pdp-1-modul | /task 6_2.py | 489 | 4.1875 | 4 | """Standart kiruvchi ma'lumotdagi vergul bilan ajratilgan so'zlar ketma-ketligini teskari tartibda chiqaradigan dastur tuzing
Masalan: Ismlar: john, alice, bob
Natija: bob, alice, john"""
words = input("Vergul bilan ajratib so'zlar kiriting:\n Ismlar: ").split(sep=",")
#First metod sl... |
41fa6d39451fe444bf8d6a9a3753bac587b4d6db | davronismoilov/pdp-1-modul | /10.3task.py | 433 | 3.53125 | 4 | '''
1- va 2- topshiriqda yozgan kodingizni try/except ichida yozib
, ekranga errorni chiqaradigan kod yozing
'''
try :
a = [1, 5, 8, 5, 6, 5, 8, 5]
print(a[9])
except IndexError as e:
print(e)
try:
ab = {'a': 12, "b": 3, 'c': 6}
print(ab[45])
except KeyError :
print('key error i... |
671dd620f6f34e20c4602a264404afdc5a85da1f | davronismoilov/pdp-1-modul | /9.3 task.py | 578 | 3.796875 | 4 | '''
Given an integer n, return a string array answer (1-indexed) where:
answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
answer[i] == "Fizz" if i is divisible by 3.
answer[i] == "Buzz" if i is divisible by 5.
answer[i] == i if non of the above conditions are true.
Input: n = 3
Output: ["1","2","Fizz"]
''... |
284fc596554833c0570f6cb982c752a97dce51e9 | Eleazar-Harold/WeatherDetection | /api_assessment.py | 1,679 | 3.546875 | 4 | import calendar
import datetime
import requests
import json
import urllib
from iso8601 import parse_date
from apixu_client import ApixuClient
from apixu_exception import ApixuException
def iso2unix(timestamp):
# use iso8601.parse_date to convert the timestamp into a datetime object.
parsed = parse_date(timesta... |
3de650934569cf2b5118fc4a8a4fbd4244114589 | rbfarr/Simple-Server | /remotecalc-server-udp.py | 758 | 3.546875 | 4 | #!/usr/bin/env python
# Richard Farr (rfarr6)
# CS 3251
# 9/21/2014
# Project 1
import socket, sys
# Bind to 127.0.0.1 at the specified port
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("127.0.0.1", int(sys.argv[1])))
# Buffer size for received data
buffer_size = 32
while True:
# Receive... |
3c036ccf967bf7c94e288b5b1d371ddd1567e984 | JA4N/lern_python | /Excersise/u_08_kontrollfluss/__init__.py | 976 | 3.875 | 4 | #Aufgabe 2
"""""
liste = ["Hochschule", "der", "TEST", "Medien"]
gesuchtNach = "Medien"
zaehler = 0
gefunden = False
while zaehler < len(liste):
if liste[zaehler] == gesuchtNach:
gefunden = True
break
zaehler += 1
if gefunden == True:
print("Gefunden! Nach dem " + str(zaehler) + " durchgan... |
b8ab12a52930764e694596ad1c4ec4346fb82590 | pankajmore/AI_assignments | /grid.py | 1,243 | 4.15625 | 4 | #!/usr/bin/python
class gridclass(object):
"""Grid class with a width, height"""
def __init__(self, width, height,value=0):
self.width = width
self.height = height
self.value=value
def new_grid(self):
"""Create an empty grid"""
self.grid = []
row_grid = []
... |
7814dec1d1327584bfcc7f7ff8e963a27cc32d06 | tag1234567/assignments | /day1.py | 151 | 3.625 | 4 | p=int(input("Enter principal : "))
r=int(input("Enter rate : "))
t=int(input("Enter time : "))
si=(p*r*t)/100
print("Simple Interest is : ",si)
|
78847ee82c62c876401fef71b5f5f3709fc4ff4d | bertvn/floodtags | /floodtags/datascience/analysis.py | 2,255 | 3.890625 | 4 | """
analyzes the tweets to find which language the dataset is and what keyword is the most frequent
"""
from random import randrange
from collections import Counter
class AnalyzeDataSet(object):
"""
class for analyzing the twitter dataset
"""
def __init__(self):
"""
constr... |
ead67175dbdc6286f97ca1a2b68724ed1ad4ed99 | jakubclark/schnapsen | /schnapsen/api/util.py | 2,501 | 3.859375 | 4 | """
General utility functions
"""
import importlib
import math
import os
import sys
import traceback
from api import Deck
def other(
player_id # type: int
):
# type: () -> int
"""
Returns the index of the opposite player to the one given: ie. 1 if the argument is 2 and 2 if the argument is 1.
... |
58995a5d2fc6bdab5db7267ed206936c2cec69b6 | Medha7979/FloorPlan3D_PY | /2D.py | 4,267 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 24 15:00:00 2019
@author: MEDHA
"""
from turtle import Turtle, Screen
import time
import itertools
a=[1,1]
b=[2,3]
i=0
for x, y in zip(a, b):
if(i<(len(a)-1)):
x=a[i]
y=b[i]
x1=a[i+1]
y1=b[i+1]
if((x1>x)and(y1==y)):
... |
00c5e35f7f5bddc7030403d74b1b75de84bf8c9d | razzaksr/KabilanPython | /basics/LoopMore.py | 891 | 3.875 | 4 | # Another real time example
#for seats in range(1,16):
'''seats=1
while seats<=15:
amt=int(input("Tell us amount to book ticket: "))
if amt>= 190:
print("Ticket Booked @",seats)
seats+=1
else:print("Insufficient amount")'''
'''seats=1
while seats<=30:
if seats%5!=0 and seats%2!=0:
... |
b1c8244326ea335cb4f5a78289b8cb783bdac7ae | razzaksr/KabilanPython | /basics/Member.py | 451 | 3.828125 | 4 | # member operator: in, not in
# list
models=['Redmi9','Realme7','Nokia6.1Plus','Honor9lite']
print(models[2])
#tuple
price=('avenger220','apache200',98700,12,'vikrant',1.2)
print(price[3])
#dict
skills={'java':8000,'python':9000,'dot net':15000,'CCPP':5000,'java':23000,'PHP':8000}
print(skills)
print('Realme5S' in mo... |
18c356c2cfc979d40c09aa0a5ed32bbb62f94834 | tceyhan/python-snippets | /functions.py | 191,904 | 4.1875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author: bm-zi
def f1():
# Chapter 1 - Python Basics
print('''Chapter 1 - Python Basics
. Entering Expressions into the Interactive Shell
. The Integer, Floating-Point, and String Data Types
. String Concatenation and Replication
. Storing Values in ... |
fd393a3fcc2a41c01b037ba61b733490bc2bbf43 | alexrosl/python_automated_testing_udemy | /PythonRefresher/if_statements.py | 690 | 3.921875 | 4 | # should_continue = True
# if should_continue:
# print("hello")
known_people = ["John", "Anna", "Mary"]
person = input("Enter the person you know: ")
if person in known_people:
print("You know the person {}".format(person))
else:
print("you don't know the person {}".format(person))
# Exercise
def who_do_you_kno... |
bcd9aedc8e906802871157763f6046fd67f08aba | obrienadam/APS106 | /midterm/word_count.py | 1,082 | 3.828125 | 4 | def word_count(filename):
with open('article.txt', 'r') as f:
text = f.read().replace('\n', ' ').replace('-', ' ')
# We may want to remove any non-alphabetic characters, eg punctuation
processed_text = ''
for ch in text:
if ch.isalpha() or ch == ' ':
processed_text += ch.low... |
6cd1676e716a609f138136b027cbe6655c7292a4 | obrienadam/APS106 | /week5/palindrome.py | 1,178 | 4.21875 | 4 | def is_palindrome(word):
return word[::-1] == word
if __name__ == '__main__':
word = input('Enter a word: ')
if is_palindrome(word):
print('The word "{}" is a palindrome!'.format(word))
else:
print('The word "{}" is not a palindrome.'.format(word))
phrase = input('What would you li... |
14f61f9325c15fc173f0c5d598525d01481f7098 | obrienadam/APS106 | /week3/recursion.py | 376 | 3.859375 | 4 | from random import randint
def pow(x, y):
if y == 0:
return 1
return x*pow(x, y - 1)
def factorial(x):
if x == 0:
return 1
return x*factorial(x - 1)
if __name__ == '__main__':
x = randint(1, 9)
y = randint(0, 9)
print('{}^{} = {}'.format(x, y, pow(x, y)))
x = randi... |
653627c23040a590d27c862de0db36c6fe46d7b5 | obrienadam/APS106 | /midterm/temperature.py | 699 | 3.859375 | 4 | def to_celsius(temp):
return (temp - 32)*5/9
def avg_temperature(filename):
tmins = []
tmaxs = []
with open('temperature.csv', 'r') as f:
for line in f:
tmin, tmax = map(float, line.split(','))
tmins.append(to_celsius(tmin))
tmaxs.append(to_celsius(tmax))
... |
1ced13face080c2b0b62936a454a1f0b07e604fc | j721/Data-Structures | /binary_search_tree/binary_search_tree.py | 8,650 | 4.28125 | 4 | """
Binary search trees are a data structure that enforce an ordering over
the data they store. That ordering in turn makes it a lot more efficient
at searching for a particular piece of data in the tree.
This part of the project comprises two days:
1. Implement the methods `insert`, `contains`, `get_max`, and `for... |
0aeeed9a00982db0a4991c67e1f9129ec6443ba9 | foxer9developer/test2-tools-repo | /main.py | 387 | 4.0625 | 4 | from add import add
from divide import divide
from multiply import multiply
from subtract import subtract
print("Welcome to Simple Calculator")
print("1. Addition")
print("2. Subtraction ")
print("3. Multliply")
print("4. Divide")
ch = input("Enter Operation: ")
if ch == '1':
add()
elif ch == '2':
subtract()
elif ch ... |
40a2727f0a5fa4b6ccdd7d7026cf4ae7a4b3daa0 | KuzmichevaKsenia/itmo-optimization-labs | /4 - genetics/genetic.py | 815 | 3.546875 | 4 | import random
from .population import Population
from .specimen import Specimen
mutation_probability = 0.01
population_num = 4
generations_num = 3
population = Population(mutation_probability, population_num)
for i in range(population_num):
rand_genome = [j for j in range(1, len(Specimen.paths))]
random.shu... |
560d269361aaf0c285f0380b8c8170a009494cfe | VamsiMohanRamineedi/Python_OOPS | /inheritenceExercis.py | 956 | 3.515625 | 4 | class Character:
def __init__(self, name, hp, level):
self.name = name
if hp >= 1:
self.hp = hp
else:
raise ValueError('hp cannot be less than 1.')
if level >= 1 and level <= 15:
self._level = level
else:
raise ValueError('select levels from 1 to 15.')
def __repr__(self):
return f"My name is... |
b568b7729ed3c9775c6b0798aa9653e61c9e5d96 | Mailhot/sell-bigin | /app.py | 11,312 | 3.8125 | 4 | #!/usr/bin/env python3
import csv
import sys
class Mapper:
"""This instance makes a correspondance between 2 csv files
it takes the column from a first csv and map columns to a second csv"""
def __init__(self, csv_from, csv_to, mapper=None):
self.csv_from = csv_from
self.csv_to = csv_to
... |
b5308acdce732f2c83f423e502758b2e50a68197 | Ellavonn/Hello-Python | /Python Class/Example 3/student.py | 359 | 3.546875 | 4 | class Student:
def __init__(self,first_name,second_name,age):
self.first_name=first_name
self.second_name=second_name
self.age=age
def full_name(self):
name =self.first_name + self.second_name
return name
def year_of_birth(self):
return 2019- self.age
def initials(self):
name=self.first_name... |
818bdca7f0985e823400c463c259dc31c133294c | AnnapooraniKadhiravan/cartoonizer | /main.py | 1,308 | 3.75 | 4 | import cv2 #computer vision to read images
import numpy as np #to perform mathematical operations on arrays
from tkinter.filedialog import * #code causes several widgets like button,frame,label
photo = askopenfilename() #opens internal file to select image
img = cv2.imread(photo) #loads an image from the sp... |
0e48b63dfbfe7beed362b5a51c3b3ff3c36793c7 | vishal-keshav/nn-incremental-learning-project | /dynamic_model.py | 9,800 | 3.546875 | 4 | """Define model architecture here.
The model class must be a torch.nn.Module and should have forward method.
For custome model, they are needed to be treated accordingly in train function.
"""
import torch
import torch.nn as nn
is_cuda = torch.cuda.is_available()
device = torch.device("cuda" if is_cuda else "cpu")
"... |
29e8eb7b6bba6a0ccd18b57b1f9c34c391d43044 | gioliveirass/atividades-pythonParaZumbis | /Lista de Exercicios IV/Ex05.py | 1,153 | 3.796875 | 4 | # Exercicio 05
print('Exercicio 05')
import random
resultado = 0
statement = '''The Python Software Foundation and the global Python community welcome and encourage participation by everyone. Our community is based on mutual respect, tolerance, and encouragement, and we are working to help each other live up to these p... |
0dafc3ecb2533432faf42a7d7c3eca8f280e8f79 | gioliveirass/atividades-pythonParaZumbis | /Lista de Exercicios IV/Ex01.py | 286 | 3.90625 | 4 | # Exercicio 01
print('Exercicio 01')
import random
num = []
min, max = 100, 0
num = random.sample(range(100), 10)
for x in num:
if x >= max:
max = x
if x <= min:
min = x
print(f'Todos os números: {num}')
print(f'Menor valor: {min}')
print(f'Maior valor: {max}') |
9059036f8be7c150514f821de7a3034cd0f3339c | gioliveirass/atividades-pythonParaZumbis | /Lista de Exercicios I/Ex06.py | 304 | 3.734375 | 4 | # Exercicio 06
print('Exercicio 06: Tempo de Viagem de um Carro')
distancia = int(input('Insira a distância a ser percorrida em KM: '))
velocidade = int(input('Insira a velocidade média esperada para a viagem (KM/H): '))
tempo = distancia / velocidade
print(f'O tempo da viagem será de {tempo} horas') |
8f4cb8cbb8f0b0b47c32ae695ff90be71d0ddc32 | gioliveirass/atividades-pythonParaZumbis | /Lista de Exercicios I/Ex01.py | 219 | 3.953125 | 4 | # Exercicio 01
print('Exercicio 01: Calculando a Soma de dois números!')
n1 = int(input('Insira um número: '))
n2 = int(input('Insira outro número: '))
soma = n1 + n2
print(f'A soma dos números inseridos é {soma}') |
ad5a4b4510f4fba1c1439b99a4e4a6167709997c | lbtdne/Coffee-Machine | /coffee_machine.py | 3,078 | 3.984375 | 4 | machine_steps = ["Starting to make a coffee",
"Grinding coffee beans",
"Boiling water",
"Mixing boiled water with crushed coffee beans",
"Pouring coffee into the cup",
"Pouring some milk into the cup",
"Coffee is ready... |
296cc9fc649aec65aa297645babfe674d91232ad | DenVankov/Numerical-Methods | /Lab1/NM_1_1.py | 4,860 | 3.671875 | 4 | from random import randint
class MatrixException(Exception):
pass
def getCofactor(A, tmp, p, q, n): # Function to get cofactor of A[p][q] in tmp[][]
i = 0
j = 0
# Copying into temporary matrix only those element which are not in given row and column
for row in range(n):
for col in range... |
69df0ffef277af6e3466541e8e07265ed79b960e | GGGomer/AoC2020 | /02/02b.py | 1,012 | 3.609375 | 4 | import re
def main():
f = open("./02input", 'r')
line = f.readline()
lowest_indices = []
highest_indices = []
characters = []
passwords = []
# Loop through all lines
while line:
# deconstruct line into elements for lists
decimals = re.findall(r'\d+', line)
lowest_indices.append(int(decima... |
2d120b9d6eb107bbd9404e0a20c88b354f0944cc | aaskorohodov/Learning_Python | /Обучение/Range comprehension.py | 189 | 3.515625 | 4 | list = [eo * 2 for eo in range(10,1,-1) if eo % 2 != 1]
print(list)
words = ["hello", "hey", 'goodbey', "guitar", "piano"]
words2 = [eo + "." for eo in words if len(eo) < 7]
print(words2) |
ab1df5f6495bf2de81da4b47c6f82acf8b9645ae | aaskorohodov/Learning_Python | /Обучение/Set (множество).py | 477 | 4.15625 | 4 | a = set()
print(a)
a = set([1,2,3,4,5,"Hello"])
print(a)
b = {1,2,3,4,5,6,6}
print(b)
a = set()
a.add(1)
print(a)
a.add(2)
a.add(10)
a.add("Hello")
print(a)
a.add(2)
print(a)
a.add("hello")
print(a)
for eo in a:
print(eo)
my_list = [1,2,1,1,5,'hello']
my_set = set()
for el in my_list:
my_set.add(el)
... |
7e39b989796a5177bff5ea327f1566012aeb5a37 | aaskorohodov/Learning_Python | /Обучение/Вывод чисел меньше х.py | 189 | 3.59375 | 4 | a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for elem in a:
if elem < 5:
print(elem)
print([elem for elem in a if elem < 5])
b = 0
while a[b] < 5:
print(a[b])
b += 1 |
32b882820ebdb60f96270d0e908bc0ba2cf559f6 | aaskorohodov/Learning_Python | /Обучение/What do U want to eat.py | 266 | 4 | 4 | print("Введите выше имя, затем нажмите Entr")
name = input()
print(name + ", что вы хотите поесть?")
food = input()
print("")
print(name + ", немедленно идите в магизин и купите " + food + "!") |
f1aae24aa9c84713a937dace34fdbda5d367cb50 | aaskorohodov/Learning_Python | /Обучение/Думать на языке Питон/Is_sorted.py | 292 | 3.640625 | 4 | a = ['a', 'v', 'a']
b = [1, 2, 3, 5, 4]
def is_sorted(lis):
i = 0
for el in lis:
try:
if lis[i] <= lis[i+1]:
i = i + 1
else:
return False
except IndexError:
pass
return True
print(is_sorted(a)) |
f407b77eda6e4ceaf757b664a2cf0d03ec59337d | aaskorohodov/Learning_Python | /Обучение/Думать на языке Питон/Metathesis pair.py | 4,342 | 4.03125 | 4 | '''Ищет пары-метатезисы – такие слова, где перестановка дищь 2х букв дает другое слово'''
file = open('C:\word.txt')
words = ''
for eo in file:
words += eo
'''Превращаем файл в строку, где каждое слово идет с новой строки.'''
def anagrams(all_words):
'''
Ищем анаграмы, собирая их в словарь, где ключ = ... |
ffbda9f72900acc80ed03bf871db381d5ce5fc5e | aaskorohodov/Learning_Python | /Обучение/Думать на языке Питон/Avoids.py | 2,388 | 3.8125 | 4 | avoid_ths = input()
'''Принимает от пользователя набор стоп-букв'''
file = open('C:\word.txt')
'''открывает файл с большим количеством слов'''
words = ''
for eo in file:
words += eo
words = words.replace('\n', ' ')
'''собирает из файла строку со словами через пробел'''
def avoids(list, avoid_ths):
'''приним... |
db236bab002eac619047121dde53949450c3daf6 | aaskorohodov/Learning_Python | /Обучение/Dict counter 2.py | 680 | 3.625 | 4 | text = "привет привет привет пока пока здрасьте"
my_dict2 = {}
for eo in text.split():
my_dict2[eo] = my_dict2.get(eo, 0) + 1 #часть до знака = присваивает словарю ключ, часть справа присваивает значение, при этом...
#...get возвращает значение по ключу eo, чтобы ег... |
c6bfbae89417c7307e7ff93ea916db38b789ac6c | aaskorohodov/Learning_Python | /Обучение/Классы - наследование.py | 857 | 4.03125 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print("Person created")
def say_hello(self):
print(f"{self.name} say hello!")
class Student(Person):
def __init__(self, name, age, average_grade):
#Person.__init__(self, name, age)
... |
9beefaee0cd2529075f223c1e2fb39871d45f24c | bjlovejoy/workoutPi | /challenge.py | 5,594 | 3.515625 | 4 | import os
import datetime
from time import time, sleep
from gpiozero import Button, RGBLED, Buzzer
from colorzero import Color
from oled import OLED
'''
Creates or appends to file in logs directory with below date format
Each line contains the time of entry, followed by a tab, the entry text and a newline
'''
def lo... |
aed5cd14882ef0a82e36f8b3bed9cf81748bd3ae | LeaderRushi/PythonForKids | /basic data.py | 455 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 25 11:54:29 2020
@author: giris
"""
subject_list = ['math', "science", "LASS", "PE"]
subject_list.append("music")
print (subject_list)
subject_list.remove("PE")
print (subject_list)
subject_list.sort()
print (subject_list)
teacher_list = ['Harder','Drake', ... |
1ce5004cdc178694f616e2ea4eabe0f73c3581b2 | riterdba/magicbox | /cl9.py | 337 | 3.984375 | 4 | #!/usr/bin/python3
class Horse():
def __init__(self, name, color, rider):
self.name = name
self.color = color
self.rider = rider
class Rider():
def __init__(self, name):
self.name = name
riderr = Rider('Миша')
horsee = Horse('Гроза', 'черная', riderr)
print(horsee.rider.name) ... |
9de3f927d4cd56dc1f3b0d3397cebad9b61f67a8 | riterdba/magicbox | /4.py | 426 | 3.6875 | 4 | #!/usr/bin/python3
#Определение високосного года.
x=input('Введите год:')
y=len(x)
x=int(x)
if (y==4):
if((x%4==0) and (x%100!=0)):
print('Год високосный')
elif((x%100==0) and (x%400==0)):
print('Год високосный')
else:
print('Год не високосный')
else:
print('Вы ввели неправильный... |
e0dd4c5a6ead7cd585d9d4cf387e6d4c8849accb | riterdba/magicbox | /cl11.py | 283 | 4.125 | 4 | #!/usr/bin/python3
class Square():
def __init__(self, a):
self.a = a
def __repr__(self):
return ('''{} на {} на {} на {}'''.format(self.a, self.a, self.a, self.a))
sq1 = Square(10)
sq2 = Square(23)
sq3 = Square(77)
print(sq1)
print(sq2)
print(sq3)
|
cf0e08f57baf9bb7b3e9a2f27acce377fdf33c1d | mayIlearnloopsbrother/Python | /chapters/chapter_7/ch7b.py | 400 | 3.890625 | 4 | #!/usr/bin/python3
#7-8 deli
sandwich_orders = ['ham', 'chicken', 'brocoli']
finished_sandwiches = []
while sandwich_orders:
sandwich = sandwich_orders.pop()
print("making you a " + sandwich.title() + " sandwich")
finished_sandwiches.append(sandwich)
print("\n")
print("following sandwiches have been made")
for ... |
9f3e5247a1c58d8c2e625138306b8422bc430afc | mayIlearnloopsbrother/Python | /chapters/chapter_6/ch6a.py | 300 | 4.15625 | 4 | #!/usr/bin/python3
#6-5 Rivers
rivers = {
'nile': 'egypt',
'mile': 'fgypt',
'oile': 'ggypt',
}
for river, country in rivers.items():
print(river + " runs through " + country)
print("\n")
for river in rivers.keys():
print(river)
print("\n")
for country in rivers.values():
print(country)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.