blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
25c667d6d414f5dca0b03231086151c86134c04d | nnim99/Introduction-to-Programming-Python- | /Lab8/Task 2.py | 541 | 4 | 4 | def main():
number = int(input("Enter number of enteries: "))
list01 = []
for var in range(0,number):
number01 = int(input("Enter a number: "))
list01.append(number01)
length = len(list01)
index = 0
if list01[index] < list01[index+1]:
smallestNumber = list01[index]
else:
smallestNumber =list01[index+... |
7ed570a75ceb5034a461ea83141458dd424b04c8 | RiverStormWinds/flaskPra | /prac_code/yield_prac.py | 2,993 | 3.640625 | 4 | # coding:utf-8
'''
def consumer():
r = ''
while True:
n = yield r
if not n:
return
print('[CONSUMER] Consuming %s...' % n)
r = '200 OK'
def produce(c):
# c.send(None) # c.send(None)启动生成器
c.__next__() # 由此可见,c.send(None)和c.__next__()是一样的作用
n = 0
whil... |
905f5eded12f932615a3c3a4b096da1d0a67359f | Sirrie/112work | /homework1/test1.py | 879 | 3.515625 | 4 | # Enter these expressions and statements into the interpreter.
# Predict the results of each line before advancing to the next line.
# Be precise.
print 3*3/4, 3/4*3, 3**3/4
x = 1000*1000*1000*1000 # one trillion
x
print x
type(x)
x /= 1000*1000*1000 # divide by one billion
x
x/1000
x
x = 123
x.bit_length()
import... |
66d55b0da82671ccf12836947f8c63e0165496ff | kburchfiel/cbs_course_review_analysis | /course_ratings_scraper.py | 9,074 | 3.609375 | 4 | # Course Ratings Scraper
# This Python program scrapes ratings information for recent Columbia Business School courses from cbscoursereview.com, stores them in a DataFrame, adds difficulty percentile information, then stores them in a CSV file for further analysis.
# By Kenneth Burchfiel (first uploaded to GitHub on 2/... |
78d9d09b166fc1d38170f119fb337659bc5dbecd | modal/tktoolbox | /tktoolbox/examples/canvas/bitmap.py | 494 | 3.546875 | 4 | from tkinter import *
canvas_width = 300
canvas_height = 80
master = Tk()
canvas = Canvas(master,
width=canvas_width,
height=canvas_height)
canvas.pack()
bitmaps = ["error", "gray75", "gray50", "gray25", "gray12", "hourglass", "info",
"questhead", "question", "warning"]
nst... |
0fd42dcb8c7913275e78635506f1edec569b2ba5 | TahaKhan8899/Coding-Practice | /TwitterChallenge2020/isPossible.py | 1,010 | 3.625 | 4 | #
# Complete the 'isPossible' function below.
#
# The function is expected to return a BOOLEAN.
# The function accepts following parameters:
# 1. INTEGER_ARRAY calCounts
# 2. INTEGER requiredCals
#
def isPossible(calCounts, requiredCals):
calCounts.sort()
for i in range(0, len(calCounts)-1):
# Fin... |
cef9233d5ea6ceb0168ec5959f4aa2ad17db88e9 | samantaavijit/Python_Tutorial | /Function.py | 399 | 4.0625 | 4 | def add(a, b):
print(a + b)
def addition():
a = int(input("Enter a "))
b = int(input("Enter b "))
print(a + b)
def fun1(a, b):
"""This is a function which calculate addition of two number and return the result"""
return a + b
add(int(input("Enter a ")), int(input("Enter b ")))
addition()
p... |
26412fc8084349ecfe6e4be3a5f8636ebabd1e6d | jalondono/holbertonschool-higher_level_programming | /0x03-python-data_structures/7-add_tuple.py | 485 | 3.765625 | 4 | #!/usr/bin/python3
def add_tuple(tuple_a=(), tuple_b=()):
t = (0, 0)
sizea = len(tuple_a)
sizeb = len(tuple_b)
if sizea == 1:
a = tuple_a[0]
c = 0
elif sizea == 0:
a = 0
c = 0
else:
a = tuple_a[0]
c = tuple_a[1]
if sizeb == 1:
b = tuple... |
b4a9a0ef58ad66bd7ee2aa24ffa473e6b6171a1a | suryavipin42/PythonProjects | /LanguageFundamentals/identifiers.py | 330 | 3.765625 | 4 | # variable name= value
# variable represents the memory location
#start with character, no length limit,but use max upto 4
# identifier = name of class,function ,variable,method
# no= 2
# print(no,"is the value in no.")
brand = "Apple"
exchangeRate = 1.235235245
message = "The price of this %s laptop is" % brand
print... |
ff51f23adba85bf19dbdc2fa0f58c44c471d18c3 | ktny/atcoder | /ABC105/c.py | 502 | 3.515625 | 4 | N = int(input())
if N == 0:
print(0)
exit()
# 1桁目から見ていって奇数なら1があるはずなので1桁目は1とやっていく
ans = []
i = 1
while N:
if N % 2 == 0:
ans.append('0')
else:
ans.append('1')
if i % 2 == 0:
N += 1
else:
N -= 1
N //= 2
i += 1
zero = True
for b in reversed... |
8e7b16355aaa20085a40ddd5caa3a04e983032fb | Hriman-Mahanta/PythonPrograms | /ArraySum.py | 117 | 3.921875 | 4 | # 8.Program to find the sum of array elements.
A=[1,2,3,4,5]
sum=0
for i in range(0,len(A)):
sum+=A[i]
print(sum) |
bf3eb756fe7bcfca6c84f65ea59bc48dab1085b3 | ychaiu/calculator-2 | /calculator.py | 1,496 | 4.1875 | 4 | """A prefix-notation calculator.
Using the arithmetic.py file from Calculator Part 1, create the
calculator program yourself in this file.
"""
from arithmetic import *
from functools import reduce
def my_reduce(function, input_list):
init = input_list[0]
#init = None
for item in input_list[1:]:
init = function(... |
7f2f2d2f725edc9e5b4a28858a221cbc2057d508 | philips-ni/ecfs | /leetcode/091_decode_ways/python/decode_ways.py | 2,565 | 3.921875 | 4 | """
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (... |
bda89fc0bd4cc4f7acd4118fb562ffbaea80cdf4 | Anh-Quan-07/CAUTRUCDULIEUVAGIAITHUAT | /CTDLGT_Python/BT13. Cài đặt đồ thị có hướng.py | 1,167 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 14 21:30:32 2021
@author: quann
"""
# libraries
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# Build a dataframe with your connections
# This time a pair can appear 2 times, in one side or in the other!
df =... |
b08dfb7293f608344ff54d1c8a8d8307d8d58b99 | dharmesh-coder/Full-Coding | /Codevita/Round 2/C.py | 325 | 3.625 | 4 | def countWays(n) :
res = [0] * (n + 2)
res[0] = 1
res[1] = 1
res[2] = 2
for i in range(3, n + 1) :
res[i] = res[i - 1] + res[i - 2] + res[i - 3]
return res[n]
t=int(input())
ans=[]
for i in range(t):
x=int(input())
ans.append(countWays(x+1))
for i in ans:
print(i,end=... |
1535a9d70692cc626dd44cd46b51245b8cc84306 | ting-python/Python0709 | /d08/Lambda4.py | 546 | 3.796875 | 4 | def calc(score):
if score >=90:
print("A")
if 90>=score>=80:
print("B")
if 80>=score>=70:
print("C")
if 70>=score>=60:
print("D")
if 60>=score>=50:
print("E")
if score<50:
print("E")
dict = {'level':lambda cin: calc(cin)}
if __name__ == '__main__... |
6d153ce6956483be57823353f23e6873e21833cf | LFYG/leetcode-acm-euler-other | /project-euler/problem 6.py | 233 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
(1+2+...+n)^2 =((1+n)^2 * n^2)/4
1^2 + 2^2 + ... + n^2 = n*(n+1)*(2n+1)/6
'''
def pep6(n):
return (3*(n**4)+2*(n**3)-3*(n**2)-2*n)/12
if __name__ == '__main__':
print pep6(100) |
c84b8c759631ab6189bc0c7cc7766a8dc1d7e3f5 | AidenLong/python | /base/lesson_02/lesson_02_condition_loop.py | 529 | 3.734375 | 4 | # -*- coding: utf-8 -*-
# if判断
a = 100
b = 200
c = 300
if c == a:
print(a)
elif c == b:
print(b)
else:
print(c)
# None的判断
x = None
if x is None:
print('x is None')
if not x:
print('x is None')
# for循环
s = 0
for i in range(0, 101):
s += i
print(s)
# while循环
s = 0
i = 0
while i <= 100:
s +... |
41f9b3675518a083dca22d8af61b19072f500722 | DaviMarinho/PythonCEV | /ex055.py | 438 | 3.890625 | 4 | #Exercício Python 055: Faça um programa que leia o peso de cinco pessoas. No final, mostre qual foi o maior e o menor peso lidos.
maior = float(0)
menor = float(9999)
for i in range(0,5):
peso = float(input(f'Escreva o peso da {i+1}ª pessoa:\n'))
if peso > maior:
maior = peso
elif peso < menor:
... |
ac35618edd53d70fea53a8fa0ea38d9a6a591988 | Riadhoq/DSA | /algorithms/searching/binary-search-recursive.py | 1,724 | 4.125 | 4 | """
Binary Search Recursive
"""
# This was the first try
# this does not remember the actual index
#
# def binary_search_first(list, item_to_find):
# if len(list) == 0:
# return -1
# mid = len(list) // 2
# # print(list)
# if list[mid] == item_to_find:
# # print(mid)
# return mid
# elif list[mid] ... |
92e154f615e7a3320338d294b995bada9027b77a | Linuzs/Pythonwork | /baskteball.py | 2,673 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author:Linuz
"""
team_a_list=[]
team_b_list=[]
team_a = input("初始化球队1名称:")
team_b = input("初始化球队2名称:")
team = ""
score_a = 0
score_b = 0
while team != 'game over':
if team_a.strip() != team_b.strip() and team_a.strip() != "game over" and team_b.strip() != "game ... |
e03b05f8b981a1f6d404d441afa6f8effab13a92 | KatherineCG/TargetOffer | /37-两个链表的第一个公共结点.py | 1,368 | 3.640625 | 4 | # -*- coding:utf-8 -*-
import re
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
if pHead1 == None or pHead2 == None:
return
p1 = pHead1
p... |
11e0543fb6906dab233301502612f789fa2e5293 | Hezel254/python_projects | /list.py | 104 | 3.90625 | 4 | numbers=[2,4,18,1,9]
max=numbers[0]
for number in numbers:
if number > max:
max = number
print(max)
|
2502b81b581ed7a5106c73475caed8b957a663a6 | kashyapa/interview-prep | /revise-daily/educative.io/depth-first-search/7_path_with_maximum_sum.py | 1,642 | 4.125 | 4 | # Find the path with the maximum sum in a given binary tree. Write a function that returns the maximum sum.
#
# A path can be defined as a sequence of nodes between any two nodes and doesn’t necessarily pass through the root.
# The path must contain at least one node.
import math
class TreeNode:
def __init__(se... |
881d5f87a7550b4e2858aed9fdead6de1c6af5fc | elit-altum/Python-Basics | /range.py | 132 | 4 | 4 | # works with the built-in range() fn.
for i in range(0, 10, 2):
print(i)
# reversing range
for i in range(10, 0, -1):
print(i) |
be67f5d67911b65f88c7393e42ecad82ca8a946e | nsiicm0/project_euler | /8/primality_test.py | 523 | 4.03125 | 4 | import math
def is_prime(n:int) -> bool:
if n == 1: return False
if n < 4: return True # 2 and 3 are prime
if n % 2 == 0: return False # there are no even primes at this point
if n < 9: return True # 4, 6 and 8 have already been excluded
if n % 3 == 0: return False
r = math.floor(math.sqrt(n)) #... |
f4f82ffd34c0d2c12352e78bc7e72981c8c70402 | Haraboo0814/AtCoder | /Manabi/union_find.py | 1,860 | 3.875 | 4 | class UnionFind():
'''
グループ分けを木構造で管理するデータ構造
以下の二点を高速で行うことができるのがメリット.
・要素xと要素yが同じグループに属するかどうかを判定したい
→ 要素xの根と要素yの根が同じならば同じグループ,
要素xの根と要素yの根が同じでないならば異なるグループ
にあることが分かる.
・要素xと要素yが別のグループに属する場合,
要素xの属するグループと要素yの属するグループを併合する.
'''
def __init__(self, n):
se... |
6019e1447da545ca8e7b1389e929f390b5020b83 | aktech/pydsa | /pydsa/queue.py | 786 | 4 | 4 | class queue(object):
"""
A queue is a container of objects (a linear collection)
that are inserted and removed according to the
first-in first-out (FIFO) principle.
>>> from pydsa import queue
>>> q = queue()
>>> q.enqueue(5)
>>> q.enqueue(8)
>>> q.enqueue(19)
>>> q.dequeue()
... |
859a332bb24a36941d9228f28713aaf586c94cd6 | wanderleibittencourt/Python_banco_dados | /Modulo-2/Aula2-2-Classes/aula5.py | 1,334 | 3.65625 | 4 | from time import sleep
class Escritor:
#METODO CONSTRUTOR
def __init__(self,nome,livros) -> None:
self.__nome = nome
self.__titulos = livros
#Getter
def get_nome(self):
return self.__nome
#Getter
def get_titulos(self):
for livros in self.__titulos: #["livro1","l... |
12fc0bae7ae1f3a8bd377f2d598e269dd92dca8f | hsm207/2018-dsb | /src/utils/layers.py | 7,984 | 3.53125 | 4 | import tensorflow as tf
from tensorflow.python.keras.activations import sigmoid, softmax
from tensorflow.python.keras.layers import Conv2D, BatchNormalization, LeakyReLU, MaxPooling2D, GlobalAveragePooling2D
class ConvBlock:
def __init__(self, filters, kernel_size, data_format='channels_first', padding='same', st... |
6ef67a38cd7ed0e8244d77b34e92017119cb872a | wurka/molvi | /editor/mentab.py | 445 | 3.953125 | 4 | import sys
elements = {
'H': 0,
'h': 0,
'He': 1,
'he': 1,
'Li': 2,
'li': 2,
'Be': 3,
'be': 3,
'B': 4,
'b': 4,
'c': 5,
'C': 5
}
if __name__ == "__main__":
if len(sys.argv) < 2:
print("say element name, e.g. <python mentab.py H> for hydrogenius")
else:
if not sys.argv[1] in elements:
print("no suc... |
d2a91e4194dbc893a4b044b242e2a568cb324768 | zryne/languages | /python/main.py | 1,082 | 4.03125 | 4 | from circle import Circle
from sphere import Sphere
from ball import Ball
def main():
c = Circle()
c.set_radius(5)
print('Circle:')
print(' Radius = ' + str(c.get_radius()))
print(' Diameter = ' + str(c.get_diameter()))
print(' Circumference = ' + str(c.get_circumference()))
print(' ... |
171f926906bf71f24bd92540a99c28561e0267e4 | Marmoth85/ExercicesCodinGame | /easy/Python3/defibrillators.py | 662 | 3.53125 | 4 | import sys
import math
lon = input()
lat = input()
n = int(input())
lon_rad, lat_rad = math.radians(float(".".join(lon.split(",")))), math.radians(float(".".join(lat.split(","))))
dist = 10 ** 10
name_defib = ""
for i in range(n):
defib = input()
defib_id, name, address, num, longit, latit = defib.split(";"... |
47603f47c07c76049ededb70428b7d081138365d | Amnesia-f/Code-base | /Python/冒泡排序.py | 352 | 4.03125 | 4 | def bubble_sort(lists):
for i in range(len(lists) - 1):
for j in range(len(lists) - i - 1):
if lists[j] > lists[j + 1]:
lists[j], lists[j + 1] = lists[j + 1], lists[j]
return lists
lists = [98, 90, 82, 95, 88]
print("要排序的列表:", lists)
print("冒泡排序结果:", bubble_sort(lists... |
59e2fe7ffcbb8f0d84179be6fdc93115d9db271f | Girin7716/KNU-Algorithm-Study | /src/kimkihyun/week_13/BOJ_1990/1990.py | 1,102 | 3.5625 | 4 | # 소수인팰린드롬
import math
a,b = map(int,input().split())
def check(num):
if num == num[::-1]:
return True
return False
def isPrime(num):
if num <= 1:
return False
if num % 2 == 0:
return False
for i in range(3,int(math.sqrt(num)),2):
if num % i == 0:
retur... |
147480fe64f59452e7a64fe06a521cbc7f91ad85 | hpplayer/LeetCode | /src/p230_sol5.py | 748 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @param {integer} k
# @return {integer}
def kthSmallest(self, root, k):
stack = []
... |
a8abc94bf5381b30400918c548040d515fe4c7aa | cmajorsolo/Python_Algorithms | /DirectedGraph.py | 1,101 | 3.796875 | 4 | from collections import defaultdict
graph = defaultdict(list)
def addEdge(graph, u, v):
graph[u].append(v)
def generate_edges(graph):
edges = []
for node in graph:
for neigbours in graph[node]:
edges.append((node, neigbours))
return edges
addEdge(graph,'1','2')
addEdge(graph,'1'... |
6e651ec8942e63597234e922fbc3c573beb1fcbf | santhosh2sai/python4me | /containsxo.py | 785 | 3.875 | 4 | #Check to see if a string has the same amount of 'x's and 'o's. The method must
#return a boolean and be case insensitive. The string can contain any char.
#XO("ooxx") => true
#XO("xooxx") => false
#XO("ooxXm") => true
#XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true
#XO("zzoo") => false
#P... |
1777d9b1df83dddd3b5707b765a818584964aca8 | jedzej/tietopythontraining-basic | /students/swietczak_monika/lesson_01_basics/sum_of_three_numbers.py | 190 | 4.1875 | 4 | # This program reads two numbers and prints their sum:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
print(a + b + c)
|
0e016e34e46435270dc0bba650016e7ba56a2ced | akshaali/Competitive-Programming- | /Hackerrank/gridChallenge.py | 2,281 | 4.15625 | 4 | """
Given a square grid of characters in the range ascii[a-z], rearrange elements of each row alphabetically, ascending. Determine if the columns are also in ascending alphabetical order, top to bottom. Return YES if they are or NO if they are not.
For example, given:
a b c
a d e
e f g
The rows are already in alphabe... |
9ab0d2938d5e334a3a1060059a2a4b48cea53946 | cosmicRover/algoGrind | /tries/TriesImplementation.py | 3,060 | 4.25 | 4 | #leetcode trie insert and search
# An example of Trie implementation
# It takes into account the english alphabets as input
class TrieNode:
def __init__(self):
#init 26 children as none
self.children = [None] * 26
#a bool representing if it's an end of the word
# it gets set to Tr... |
e8d30b4e4b6f63a328e69796ffa62a96d400f8ca | harrietty/python-katas | /katas/persistence.py | 589 | 3.84375 | 4 | # Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
from functools import reduce
def persistence(num):
if num < 10: return 0
def multiply(arr):
re... |
8e7bfe127c7488c89391d4fb056f26008701c10f | Katzeminze/A2L_Parser | /Parser_a2l.py | 5,898 | 3.59375 | 4 | import os
import re
class FileA2L:
def __init__(self, path):
self.path = path
self.current_position = 0
self.obligatory_lines_number = 5
if not os.path.exists(self.path):
print("File does not exist")
def write(self, content):
with open(self.path, 'w') as f... |
9c41c48b4c9fb941aef4038ef859593c3e3032ad | gsrr/leetcode | /hackerrank/Moody_Analytics_Women_in_Engineering_Hackathon/01_strong_correlation.py | 610 | 3.515625 | 4 | #!/bin/python
import sys
def minus(val):
if val == 0:
return "equal"
elif val > 0:
return "big"
else:
return "small"
def solve(n, p, d):
# Complete this function
parr = [ minus(p[i] - p[i - 1]) for i in xrange(1, len(p))]
darr = [ minus(d[i] - d[i - 1]) for i in xrang... |
4b7a7d4453b23c6715278f6ab7472f3bc72b36ec | techadddict/Python-programmingRG | /user_input & conditional programming/getUserInput6.py | 1,256 | 4.71875 | 5 | #A string Str1 is a *prefix* of a string Str2 if Str2 can be obtained by adding symbols
#to the right of Str1. For instance the string `abbc' is a prefix of the string `abbcadd' and not a prefix
#of the string `abbdab'. Symmetrically, Str1 is a *suffix* of a string Str2 if Str2 can be obtained by adding
#symbols to th... |
c6c5c2f16e29ac025415e698fe78791330be7f93 | Ankit-Developer143/Programming-Python | /Regular Expression/demo2.py | 630 | 3.796875 | 4 | """ These methods include group which returns the string matched,
start and end which return the start and ending positions of the first match,
span which returns the start and end positions of the first match as a tuple.
"""
import re
pattern = r"pam"
match = re.search(pattern, "eggspamsausage")
if match:
p... |
4615ba7bf8e4e3b7766414cb2ec0c4578d465622 | Florins13/How-to-Think-Like-a-Computer-Scientist | /namespace_test.py | 661 | 3.875 | 4 | import mymodule1
import mymodule2
print((mymodule2.myage - mymodule1.myage) ==
(mymodule2.year - mymodule1.year))
print("My name is", __name__)
mymodule1.main()
# Ex 5
# So, this print __name__ actually prints the name of the module. If you are
# printing the current module (the one you are in) you will... |
44446f249d37b061f0ed4af0be9644b1c4546365 | john-okey/testrepo | /test_file03.py | 489 | 3.734375 | 4 | import sys
print{" "}
for i in range(1,int((sys.argv[1]))):
if i == 1:
print("Deze nummer is de {}st keer ik 'jij ben geweldig' moet schrijven".format(i))
elif i == 2:
print("Deze nummer is de {}nd keer ik 'jij ben geweldig' moet schrijven".format(i))
elif i == 3:
print("Deze numme... |
f6d3678d91d680bcc692d3d305d5475f1c68c1e4 | thelabdc/OVSJG-SUSO-public | /src/suso/ab_test.py | 4,314 | 3.6875 | 4 | """
This file contains tools for doing A/B Testing.
@author Kevin H. Wilson <kevin.wilson@dc.gov>
"""
import numpy as np
from scipy import special
from scipy.stats import binom
def degree_of_certainty(successes_a, failures_a, successes_b, failures_b):
"""
Compute the "degree of certainty" that the B side of a... |
db5e38551af864be9c48f2d1befe3c53253ccddd | seanchen513/leetcode | /design/0146_lru_cache.py | 9,629 | 3.96875 | 4 | """
146. LRU Cache
Medium
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if... |
2ef8a2626ce197fd6e23790494fdaf1c42b90ea8 | zkuser2002/Library_Application_Form_With_Tkinter | /frountend.py | 3,091 | 3.8125 | 4 | from tkinter import *
import backend
def clear_list():
list1.delete(0,END)
def fill_list(books):
for book in books:
list1.insert(END,book)
window=Tk()
window.title('Book Store')
#=================Labels=================
lbl1=Label(window,text='Title')
lbl1.grid(row=0,column=0)
lbl2=L... |
0b1c59f9280ebb164202708f11dc7827d2de26c7 | Sanich11/QAP-6 | /PycharmProjects/Mod18/Task18_2_3.py | 590 | 3.546875 | 4 | """
Напишите программу, которая отправляет запрос на генерацию случайных текстов (используйте этот сервис -
https://baconipsum.com/api/). Выведите первый из сгенерированных текстов.
"""
import requests
import json
r = requests.get('https://baconipsum.com/api/?type=meat-and-filler')
r = json.loads(r.content... |
ac8d9e7836f84a6dec72bb0d808649aabe9f408c | devanshbhatia26/Library | /Trees/SegementTrees.py | 846 | 3.53125 | 4 | def build(node, start, end):
if start==end:
tree[node] = A[start]
else:
mid = (start+end)/2
build(2*node, start, mid)
build(2*node, mid+1, end)
tree[node] = tree[2*node]+tree[2*node+1]
def update(node, start, end, idx, val):
if start==end:
tree[node] += ... |
7d6341cbbf098898504065360e3035f8291b3e8e | dorrabbkhan/sideprojects | /Alien Invasion/button.py | 1,392 | 3.6875 | 4 | """
Class file for button in Alien Invasion game
"""
import pygame.font
class Button:
"""
Class for button in Alien Invasion game
"""
def __init__(self, ai_game, msg):
self.screen = ai_game.screen
self.screen_rect = ai_game.screen.get_rect()
# initialize screen
self.... |
f0dffdf4255710bdcd1dd23d93f7b55d404b6ffb | TdotA/Python_for_CS1 | /MyScripts/functions.py | 1,445 | 3.75 | 4 | import math
def area(n,a):
area = (a**2 * n )/4* math.tan(math.pi/n)
return area
#print(str(area(4,2)))
#print(str(area(3,2)))
#print(str(area(6,2)))
def is_leap_year (y):
if (y % 4) == 0 :
if (y % 100) == 0 :
if (y % 400) == 0 :
return True
else :
... |
5a9f334f6f08aff691d55c38ba97a7b5eed3a78d | dominiquecuevas/hackbright-markov-chains | /markov.py | 3,390 | 4.125 | 4 | """Generate Markov text from text files."""
from random import choice
def open_and_read_file(file_path):
"""Take file path as string; return text as string.
Takes a string that is a file path, opens the file, and turns
the file's contents as one string of text.
"""
# your code goes ... |
1b9d86514ac35b10e889d86c824fa366d019fa18 | novneetnov/Principles-Of-Computing---I | /week1/merge.py | 719 | 3.5625 | 4 | # url : http://www.codeskulptor.org/#user39_MMUT83KjKI_8.py
"""
Merge function for 2048 game.
"""
import test_merge
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
return_line = [0]
merge_flag = False
for elem in line:
if elem != 0:
if retur... |
2faa13bcdf4fab5f3a7d03844666ba0d3a42464a | raquelmcoelho/object-oriented-programming | /Atividade02/Fila.py | 507 | 4.1875 | 4 | #Fila - FIFO(first in first out)
fila = []
n = int(input("quantos elementos terá sua fila? "))
#adicionar no tail
while len(fila) < n:
elemento = input("adicione o elemento: ")
fila.append(elemento)
print("sua fila agora está assim:")
[print(x) for x in fila]
#retirar na head
n1 = int(input("quantos element... |
c5e4d0d68866a0114c78fabe23c3cce599e9d229 | KimNgan96/Fossil_Test | /question_3.py | 644 | 3.640625 | 4 | import threading
lock = threading.Lock()
class Car(threading.Thread):
def __init__(self, max_speed, door=4,wheel=5, seat=4):
threading.Thread.__init__(self)
self.door = door
self.wheel = wheel
self.seat = seat
self.max_speed = max_speed
def run(self):
lock.acqui... |
765b2e06f4c24d2619341977ef3a6d837f45f5a3 | sunminky/algorythmStudy | /알고리즘 스터디/개인공부/heap/Fueling.py | 765 | 3.625 | 4 | # https://www.acmicpc.net/problem/1826
import sys
import heapq
if __name__ == '__main__':
n_gasstation = int(sys.stdin.readline())
gasstations = sorted([tuple(map(int, sys.stdin.readline().split())) for _ in range(n_gasstation)],
key=lambda x: x[0])
destination, cur_fuel = map(int,... |
a7e390f55bb316c22ff6202c886090ba16bd3981 | rwieckowski/project-euler-python | /euler364.py | 802 | 3.625 | 4 | """
There are <var>N</var> seats in a row <var>N</var> people come after
each other to fill the seats according to the following rules
<ol type="1"><li>If there is any seat whose adjacent seats are not
occupied take such a seat</li><li>If there is no such seat and there
is any seat for which only one adjacent seat i... |
150d4e2d01df92118756aeadc72e28b21b4a6faa | Bollegala/bollegala.github.io | /lect/dm/python_basics.py | 1,024 | 3.53125 | 4 | import math
def get_vector(s):
words = s.split()
v = {}
for w in words:
v[w] = v.get(w, 0) + 1
return v
def cos(x, y):
total = 0
for word in x:
total += x[word] ** 2
x_norm = math.sqrt(total)
total = 0
for word in y:
total += y[word] ** 2
y_norm = math... |
b08cbd85c5a36a21b63ed25b5da6c6f34fc0dcdc | etangreal/compiler | /test/tests/05class/6496-test_class-object_006.py | 383 | 3.5 | 4 | class A(object):
def __init__( self ):
self.attr=776
def func( self ):
print self.attr
class B(object):
def __init__( self ):
self.attr=777
def func( self ):
print self.attr
class C(object):
def __init__( self ):
self.attr=778
def func( self ):
... |
383e5708995d4e0486e661e2fe365677533ff6b6 | zhangda7/leetcode | /solution/_100_same_tree.py | 2,985 | 3.84375 | 4 | #-*- coding:utf-8 -*-
'''
Created on 2015/8/24
@author: dazhang
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
#easy but ugly solution
'''
class TreeNode:
def __init__(self, ... |
7007162486b50ef838a5e69bae26c319f9436782 | yagnyasridhar/Python | /Training/1.py | 1,714 | 4.25 | 4 | '''
print("Hello, World!")
'''
#comment
#print("Hello, World!")
#indentation
'''
i = 12
if type(i) == type(1):
print("wow")
'''
#variable
'''
i = "sample"
y = 10
print(y+i)
'''
'''
i = "awesome"
def func():
global i
i = "value"
print(i)
func()
print(i)
'''
#pass
'''
def ... |
9e1c37b5c05cb2cc6e018ff4a25e6075796cd32a | sacsachin/programing | /repeat_and_missing_num.py | 470 | 3.546875 | 4 | # !/usr/bin/python3
"""
https://www.interviewbit.com/problems/repeat-and-missing-number-array/
Repeat and Missing Number Array
"""
def solve(A):
n = len(A)
for i in range(n):
if A[abs(A[i])-1] > 0:
A[abs(A[i])-1] = -A[abs(A[i])-1]
else:
missing = abs(A[i])
print(A)
... |
a882ec79859cfb4030881e1e6dbcdb9cdc9b8a3b | ayazhemani/interview_prep | /minesweeper/minesweeper.py | 5,338 | 3.546875 | 4 | """Solution for Minesweeper Game
"""
from random import randint
import os
class Minesweeper:
def __init__(self, width, height):
self.difficulty = 0.05
self.height = height
self.width = width
self.board = [[None] * width for x in xrange(height)]
self.unhidden_board = [[None] ... |
a21a4a5504f7796b4525c73cab8d797ebd2d53b9 | yakobie/homework | /exercise 10/tenth.py | 337 | 3.890625 | 4 | import random
user = raw_input("Guess a number between 1 and 20, type exit to exit: ")
while user != "exit":
a = random.randint(1, 5)
user = raw_input("Guess a number between 1 and 20, type exit to exit: ")
if user == a:
print('You win! :)')
a = random.randint(1, 5)
else:
print('Nope...')
a = random.ra... |
ec69309fb64895e8b857f5cea9882c7b950e0978 | garciaha/DE_daily_challenges | /2020-07-20/num_char.py | 1,435 | 4.15625 | 4 | """Numbers First, Letters Second
Write a function that sorts list while keeping the list structure. Numbers should be first then letters both in ascending order.
Examples
num_then_char([
[1, 2, 4, 3, "a", "b"],
[6, "c", 5], [7, "d"],
["f", "e", 8]
]) -> [
[1, 2, 3, 4, 5, 6],
[7, 8, "a"],
["b", "c"], ["d", ... |
21a3503024d4dc3c7411ee15ee37bb34b5b5471e | peterhchen/runBookAuto | /code/example/13_ListGen/04_Comprehen.py | 159 | 3.796875 | 4 | #!/usr/bin/python3
'''
Generate a lis of 10 values
Multiple them by 2
Return multiples of 8
'''
print ([x for x in [i * 2 for i in range(10)] if x % 8 == 0])
|
5c1ca2069230bac5ac6bdd32d782d9d798d52c2b | soumasish/leetcodely | /python/paint_house.py | 1,628 | 3.765625 | 4 | """Created by sgoswami on 7/29/17."""
"""There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. The cost of
painting each house with a certain color is different. You have to paint all the houses such that no two adjacent
houses have the same color.
The cost of paint... |
7249beac71d56639fd3ef819f0a58f94698dfe58 | GuilhermeFA00/WeatherDTS_project | /main.py | 1,567 | 4.03125 | 4 | #Reading csv file
import pandas as pd
data = pd.read_csv(r"C:\Users\Usuario\Desktop\I.A. lrn_path\DataScy_Learning\WeatherDTS_project\WeatherDataM.csv")
#Pre-processing
from sklearn import preprocessing
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import train_test_split
weather_... |
d3adc7c557b18c69b8abde7be34ae9e11b1ada5b | k4u5h4L/algorithms | /leetcode/Word_Search.py | 1,515 | 3.875 | 4 | '''
Word Search
Medium
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
E... |
ce6d705fec6ff297d36bb190ce5f8d1f5e58a049 | lxh0019/AID2003 | /day1/fork.py | 505 | 3.703125 | 4 | """
创建二级子进程处理僵尸
"""
from os import *
from time import *
def f1():
for i in range(3):
sleep(2)
print("写代码")
def f2():
for i in range(2):
sleep(4)
print("测代码")
pid = fork()
if pid < 0:
print("Create process failed")
elif pid == 0:
p = fork() # 创建二级子进程
if p == 0:... |
5bd2273d3b638db81170098428bbf7766db8af52 | benkadiayi/HWW2D3 | /md.py | 390 | 4.125 | 4 | class area():
def __init__(self,length,width):
self.length = length
self.width = width
self.area = length * width
print (f"Your area is {self.area}square foot")
class circumference():
def __init__ (self,radius):
self.radius = radius
self.circ = 2 * radius * 3.14
... |
1a5363884a7ff5674fa59ec74fc144e9f4e6c0f9 | bcheney21/git_practice_2 | /general-assembly/unit4/w1/d3/solution.py | 312 | 4.1875 | 4 | greeting_dictionary = {
'english': 'Hello!',
'spanish': 'Hola!',
'french': 'Bonjour!'
}
user_input = input('please enter a language: english, spanish, or french\n').lower()
for key, value in greeting_dictionary.items():
if key == user_input:
print_greeting = value
print(print_greeting) |
90a9a4e4eee2cbecc9660adfae3ab72b9c1535b4 | debryc/LPTHW | /ex15.4.py | 402 | 3.75 | 4 | from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your %r file: " % filename
print txt.read()
# Why doesn't the script stop and ask me for another argument?
print "Write the file name in the command line again."
from sys import argv
script, filename_again = argv
txt_again = open(file... |
8556169f2bae7bbde9b88ef3486023d881d7e202 | tonycmooz/git-practice | /test.py | 1,218 | 3.59375 | 4 | import csv
import json
class TestClass(object):
def __init__(self, foo, bar, baz):
self.foo = foo
self.bar = bar
self.baz = baz
def fizz_buzz(self, digit_1, digit_2):
for i in range(1, 100):
if i % digit_1 == 0:
if i % digit_2 == 0:
... |
e1baeac08ad198a1fd322eb280ac487c7770878d | mike03052000/python | /Training/HackRank/mike/while-1.py | 342 | 4 | 4 | numbers = [11, 22, 33, 44, ]
print('before: %s' % (numbers,))
def test_while():
idx = 0
while idx < len(numbers):
numbers[idx] *= 2
idx += 1
print('after: %s' % (numbers))
test_while()
def enumerate1(x):
v=[]
for idx,val in enumerate(x):
v.append(idx+val)
print('v=',v)... |
fd2c7b79022b8a8fc94c4ee12b94222684261fe9 | quarkgluant/boot-camp-python | /day03/ex03/ColorFilter.py | 7,275 | 3.703125 | 4 | #!/usr/bin/env python3
# -*-coding:utf-8 -*
import numpy as np
class ColorFilter:
"""a tool that can apply a variety of color filters on images.
For this exercise, the authorized functions and operators are specified for each methods. You
are not allowed to use anything else."""
def _dtype_to... |
e996cb3a023c6c7c2ff1e8ecb9e2f9a1913b6760 | carloswm85/2021-cs111-programming-with-functions | /w10-handling-exceptions/prove-handling-exceptions/receipt.py | 3,065 | 3.875 | 4 | import csv
from datetime import datetime
def main():
products_file = "E:/GitHub/2021-cs111-programming-with-functions/w10-handling-exceptions/prove-handling-exceptions/products.csv"
products = read_products(products_file)
print('>>> Inkom Emporium <<<')
# print('Products:')
# for number, product... |
1fa4edf8f99ef1ac2473221e91c4a47ed37ee860 | 13424010187/python | /源码/【11】循环圣诞树-课程资料/11.py | 1,659 | 4.1875 | 4 | ''''''
'''
*在不同数据类型下的使用:在字符串:倍数 在数字类型:乘号
遍历:逐个访问
序列:一组数据
遍历序列:逐个访问一组数据的每个元素
for循环:已知循环次数的循环,常用来遍历
while循环:未知循环次数的循环,符合条件就行,很少用来遍历
for循环:for 变量 in 序列:
range()方法:start:默认为0 stop:不包括stop本身 step:步长,默认为1
'''
'''while循环实现圣诞树'''
# number=int(input('please input a number :'))
# i=1
# while i<=number:
# print(' '*... |
dc4f1bc96ae3f24670b289cfe52626df67206b70 | Alexanderklau/hackerRank_test | /test_project.py | 870 | 3.984375 | 4 | # -*-coding:utf-8 -*-
__author__ = 'Yemilice_lau'
# def print_formatted(number):
# width = len("{0:b}".format(number))
# for i in range(1, n + 1):
# # print("{0:{width}d}".format(i,width=width))
# print("{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}".format(i, width=width))
#
# # your... |
60a60eb4b62884547b8ccf65709a8a263cabb7f7 | sarck1/RoadPython | /chapter010/chapter_01004.py | 1,527 | 4.28125 | 4 | # 类的继承
class BaseClass:
"""基类"""
# 成员变量
def __init__(self, age, name, job): # 特殊函数:双下划线开始+双下划线结束,系统定义的特殊函数,不能在类外部访问
self.age = age # 公有成员: 对所有人公开,可以在类的外部直接访问
self._name = name # 保护成员:不能够通过 "from module import *" 的方式导入
self.__job = job # 私有成员:双下划线开始,无双下划线结束;类的外... |
e64ec18bc9e744298a5b7041fad45dedf48b260e | tangdoufeitang/leetcode | /Python/29.divide-two-integers.py | 1,482 | 4.09375 | 4 | from __future__ import print_function
# 29. Divide Two Integers
# Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
# Return the quotient after dividing dividend by divisor.
# The integer division should truncate toward zero.
# Example 1:
# Input... |
275652e0b654a516f0433e58c023b160863e264a | YancyWei/YancyWorld | /循环队列/循环队列.py | 2,997 | 4.21875 | 4 | """
设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”。
循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。
你的实现应该支持如下操作:
MyCircularQueue(k): 构造器,设置队列长度为 k 。
Front: 从队首获取元素。如果队列为空,返回 -1 。
Rear: 获取队尾元素。如果队列为空,返回 -1 。
enQueue(value): 向循环队列插入一个元素。... |
627bdd2b9b779002274765f3925b9d1cbc143bd8 | ricardoBpinheiro/PythonExercises | /Desafios/desafio066.py | 197 | 3.765625 | 4 | n = 0
cont = 0
soma = 0
while True:
n = int(input('Digite um numero (999 para sair): '))
if n == 999:
break
soma += n
cont += 1
print(f'A soma dos {cont} valores é {soma}') |
ed26ac19ec3096e369a83bb327861f3baf19ee01 | MCaldwell-42/classes | /classes.py | 1,066 | 3.984375 | 4 | class Pizza:
def __init__(self):
# Establish the properties of each pizza
# with a default value
self.size = ""
self.style = ""
self.crust = ""
self.toppings = []
def add_topping(self, topping):
self.toppings.append(topping)
print(f"added {toppin... |
8e1b298679ba890b6ebea48a266b68f25d2e1354 | mahimadubey/leetcode-python | /different_ways_to_add_parentheses/solution.py | 1,395 | 4.25 | 4 | """
Given a string of numbers and operators, return all possible results from
computing all the different possible ways to group numbers and operators. The
valid operators are +, - and *.
Example 1
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]
Example 2
Input: "2*3-4*5"
(2*(3-(4*5))) = -34
((2*3)-(4*... |
3d466a1d1b683fff57ef69a54274344ce7bd5a21 | skinan/Competative-Programming-Problems-Solutions-Using-Python | /1154A.py | 598 | 3.75 | 4 | # Codeforces
# 1154A - Restoring Three Numbers.
def main():
temp = input().split(" ") # Get the inputs in a temporary list.
num = []
# Convert all the list elements to integer type, and append it to a new list.
for i in range(len(temp)):
num.append(int(temp[i]))
# Sort the l... |
de8fbf0346deac21df683dfb177dfef3cf90570d | jclopezp/retos-py | /ej-02.py | 172 | 3.53125 | 4 | # isinstance(3, int) -> True
# isinstance(3, str) -> False
# x es un elemento del rango
def multiplos(a, b):
lista = [a * x for x in range(1, b + 1)]
return lista
|
25e777491b72b0f9535734f46ce339afc8b909b0 | peterJbates/euler | /027/quadratic_primes.py | 837 | 3.796875 | 4 | from time import time
import math
start = time()
# checks if a number is prime
def isPrime(n):
if n < 2:
return False
elif n == 2:
return True
elif not n & 1: # if n is even (and not 2)
return False
for x in range(3, int(math.sqrt(n))+1, 2):
if n % x == 0:
re... |
3a40256b0e3b4d3dff2196591ab75ff59900dce1 | razvanilie/UniWork | /AF/Finished/DFS/DFS.py | 885 | 3.78125 | 4 | #http://www.cs.yale.edu/homes/aspnes/pinewiki/DepthFirstSearch.html
from collections import defaultdict
def addEdge(u, v):
graph[u].append(v)
graph[v].append(u) # it depends if it s a directed or undirected graph
#DFS starting with node x
def DFS(x):
visitedArray[x] = True
print(x)
for y in graph[... |
9ab3890b27d2bab9674fb68db3c59acd635441dd | VictorVaquero/sentimentAnalysis | /src/preprocesado.py | 2,897 | 3.609375 | 4 | import csv
from collections import Counter
DIR = "../JavaPreprocesamiento/"
TEXT = "market.csv"
FINAL = "market.txt"
IRREGULAR = "IrregularVerbs.csv"
COLS = 10 # Numero de columnas de el archivo de texto
VOCABULARY = 200 # Numero de palabras a mantener
DEBUG = True
# Simbolos o palabras que no se van a considerar
SI... |
ec029b7a58fa3d665a45949ebe7f04b928795b72 | uvae/BojSolution | /14XXX/boj_14624.py | 163 | 3.796875 | 4 | n = int(input())
if not(n%2): print('I LOVE CBNU')
else:
print('*'*n)
for i in range(n//2+1):
print('{}*{}'.format(' '*(n//2-i), ' '*(i*2-1)+'*' if i else '')) |
b894fa69ad4ca9ccd810d66d6d314f1c537ee3f2 | DarkAlexWang/leetcode | /laioffer/search-in-sorted-matrix.py | 1,315 | 3.703125 | 4 | class Solution:
def search_in_sorted_matrix(self, matrix, target):
if len(matrix) == 0 or len(matrix[0]) == 0:
return [-1, -1]
res = [-1, -1]
m = len(matrix)
n = len(matrix[0])
row = self.find_row(matrix, 0, m - 1, target)
if row == -1:
retur... |
7aa05cab25aabea9b1c2674e51ebd3933f205ddb | dragosbratuflorian19/Skills | /SQL_notes.py | 1,208 | 4.03125 | 4 | ###################################################
# SQLITE3
import sqlite3
the_connection = sqlite3.connect(':memory:') # Connection to a datebase (file or memory)
the_cursor = the_connection.cursor()
the_cursor.execute("""
CREATE TABLE employees (
first text,
last text,
p... |
87e846986fe2555c9b3d5e876ef6f1c6737e05ea | raysomnath/Python-Basics | /Python_MySQL/Select_With_WildcardCharacters.py | 564 | 3.53125 | 4 | # You can also select the records that starts, includes, or ends with a given letter or phrase.
# Use the % to represent wildcard characters:
import sys
import mysql.connector
# Try connecting to database "mydatabase"
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="Somshona$1",
... |
f5dc7d5389e5d26a2d68152e6d9e7b0a58b6b308 | Qinpeng96/leetcode | /206. 反转链表.py | 1,695 | 4.375 | 4 | """
[206. 反转链表](https://leetcode-cn.com/problems/reverse-linked-list/)
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
***
反转一个链表有两种方法:
迭代法和递归法。
迭代法就是每次提出一个左边元数,插入到之前的一个链表中去。
#
[1,2,3,4,5,None]
[1,None] [2,3,4,5,None]
[2,1,None] [3,4,5,None]
[3,2,1, None] [4,5... |
0dbdbd57d3f4af853170eeed6af6ec0d4533fead | yosifnandrov/func_exercise | /funny_funcs.py | 1,731 | 3.640625 | 4 | def numJewelsInStones(jewels, stones):
final = 0
for jewel in list(jewels):
final += stones.count(jewel)
return final
#print(numJewelsInStones("aA","aAAbbbb"))
def find_smaller(arr):
final = []
for i in range(len(arr)):
final.append(sum(map(lambda x: x < arr[i], arr)))
return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.