blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3d15d5fa67f3ece167bf7c8a09809b21fd57114c | Remor53/lesson2 | /find_person.py | 1,133 | 4.0625 | 4 | if __name__ == '__main__':
friend_list = ["Вася", "Маша", "Петя", "Валера", "Саша", "Даша"]
friend_name = friend_list[-1]
while friend_name != "Валера" and len(friend_list) > 1:
friend_list.pop()
friend_name = friend_list[-1]
if len(friend_list) > 1 or friend_list == ["Валера"]:
... |
91b5efc3931ab0459ad3d71b78e33f1473e62d52 | SilicateBird/Color_Detection_Android | /test_something/triangledistance.py | 402 | 3.78125 | 4 | import math
# pythagorean_distance
def pytha(point1, point2):
return math.hypot(point2[0] - point1[0], point2[1] - point1[1])
# find distance from pointO to vertices of triangle ABC
def triangle_distance(pointO, pointA, pointB, pointC):
return [pytha(pointA, pointO), pytha(pointB, pointO), pytha(point... |
7a0409586f4dd8d2bf79efe1e7f363a6d25ffece | ebmm01/ppc-2019-1 | /contest_prova_2/exA.py | 105 | 3.53125 | 4 | x = input()
if x.count('a') > len(x)/2:
print(len(x))
else:
print(int(2*(x.count('a'))-1))
|
ae0d8c58ead2bf7dadfd6c272b5bc680a04c7fb2 | Songyang2017/Python-Learn-record | /函数/1.py | 808 | 3.984375 | 4 | # python有很多内置函数,可参见:https://docs.python.org/3/library/functions.html
# abs() 取绝对值,有且只有一个参数
# max()可以接收多个参数,返回最大的那个,相反min()返回最小的
max(1,2,23,54,-534) #54
int('123')
# 123
int(12.34)
# 12
float('12.34')
# 12.34
str(1.23)
# '1.23'
str(100)
# '100'
bool(1)
# True
bool('')
# False
# 函数名就是一个指向一个函数的引用,可以将函数名赋给一个变量
a = abs
a... |
ec199b50c16c4176388d77199265cd4998401066 | WinterWhiteDragon/til | /python/binary+search.py | 445 | 3.828125 | 4 | def binary_search(data, target):
data.sort()
start = 0
end = len(data) -1
while start <= end:
mid = (end + start) // 2
if data[mid] == target:
return mid
elif data[mid] > target:
end = mid - 1
elif data[mid] < target:
start = mid + 1
return None
lis = [7, 1, 55, 66, 2, 3]
idx = binary_search(l... |
042b23d60ad09019faeba4f35d47c968ae0451b2 | hellJane/Python_DataAnalysis | /LinearAlgebra/scipy_linalg_basics.py | 2,176 | 3.84375 | 4 | import scipy.linalg as sl
import numpy as np
print('''
When SciPy is built using the optimized ATLAS LAPACK and BLAS libraries,
it has very fast linear algebra capabilities.
---------------------------------------------------------------------------
scipy.linalg contains all the functions in numpy.lin... |
ebc059bfe56e245dbe65d6fbfee0d28001faee15 | coderleo/py_test | /init_new_test.py | 259 | 3.59375 | 4 | class Person:
def __init__(self,name,age):
self.name = name
self.age = age
def __new__(cls,*args):
print('on __new__')
return super().__new__(cls)
if __name__ == '__main__':
p = Person(1,2)
print(p.age) |
d5c233f4c92d936cbb9859d545d9dcafa9783046 | acmfi/AdventCode | /2021/day11/FORGIS98/DumboOctopus.py | 1,682 | 3.75 | 4 | def print_matrix(matrix):
for i in matrix:
print(i)
print("")
def is_valid(matrix, x, y):
return x >= 0 and y >= 0 and x < len(matrix) and y < len(matrix)
def flash(matrix, posx, posy):
for i in range(posx - 1, posx + 2):
for t in range(posy - 1, posy + 2):
if (i == posx ... |
60e3e4f5c3675c8d74d87ddd5fdc8c79465ecb77 | ComteAgustin/learning-py | /strings.py | 1,258 | 4.0625 | 4 | myStr = "hello world"
# Functions
dir(myStr) # Return methods and properties, that i can use
myStr.upper() # Return the string in uppercase
myStr.lower() # Return the string in lowercase
myStr.swapcase() # Convert the uppercase en lower case and the reverse
myStr.capitalize() # Convert the first letter in uppercase
... |
866acd9b313db12aaf49c00486558c3067f03836 | shafirpl/InterView_Prep | /Basics/Colt_Data_structure/Graphs/Basics/graphs.py | 1,835 | 3.765625 | 4 | class Graphs:
def __init__(self):
self.adjancy_list = {}
def addVertex(self,vertex):
if(self.adjancy_list.get(vertex) is not None):
return
self.adjancy_list[vertex]= []
def addEdge(self,first_vertex,second_vertex):
if(self.adjancy_list.get(first_vertex) is None ... |
e668a1e0c4ce064fa735404500f6828e55649ebb | dbetm/cp-history | /Interviews/CrackingTheCodeInterview/BitManipulation/AB_Decimal2Binary.py | 1,563 | 4.21875 | 4 | """
Given a (decimal - e.g. 3.72) number that is passed in as a string,
print the binary representation. If the number can not be represented
accurately in binary, print “ERROR”.
"""
from math import isclose
def int_2_bin(n: int):
ans = ""
while n:
ans += str(n % 2)
n //= 2
return ans[::... |
1fb2daec6c55d3992809ca5b789cfdc3c3633e92 | fermihacker/ProjectEuler100 | /Problem112.py | 699 | 3.625 | 4 | from time import time
increasing = lambda n : list(str(n)) == sorted(list(str(n)))
decreasing = lambda n : list(str(n)) == sorted(list(str(n)), reverse = True)
bouncy = lambda n : not (increasing(n) or decreasing(n))
def proportion(upper_limit):
k = len([1 for i in range(101, upper_limit) if bouncy(i)])
... |
6c66d309d4cd366cc01d1133e6325befe3123d4b | maysuircut007/python-basic | /10.if.py | 489 | 3.703125 | 4 | '''
if boolean Expression :
statement
'''
age = int(input("ป้อนอายูของคุณ : "))
if age >= 15: # ทำเมือเงื่อนไขเป็นจริง
print("คำนำหน้าของคูณเป็น นาย หรือ นางสาว") # statement ภายใน
print("จบโปรเเกรมด้านใน if") # จบ statement ภายใน
print("จบโปรเเกรม")
|
be6009bb18627deee80a56589ccaf3a7131dec76 | wert-rar/zoo | /rock.py | 3,297 | 3.625 | 4 | import math
import random
from typing import Any, Callable
import pygame as pg
pg.init()
# --------set screen---------------
HEIGHT, WIDTH = 1000, 1000
screen = pg.display.set_mode([HEIGHT, WIDTH]) # setup screen
colors = [
(0, 216, 255), # light blue
(0, 0, 255), # blue
(153, 255, 170), ... |
760788db408d8bf1bccad4f6567089fae9757a42 | Watebear/python-slam | /ch3/eigenMatrix.py | 692 | 3.5625 | 4 | import numpy as np
# 创建一个 2x3 的矩阵
A = np.mat([[1, 2, 3], [4, 5, 6]])
# 创建一个 1x2 的向量
b = np.array([1, 2, 3])
# 创建随机数矩阵
C = np.random.randint(1, 10, (3, 3))
print('A is 2x3 :\n', A)
print('b is 1x3 :', b)
print('C is 3x3 :\n', C)
# 转置
print('A.T:\n', A.T)
# 求各元素之和
print(np.sum(A))
print(np.sum(A, axis=0))
print(np.sum... |
943c00c74fc78ca43c352c446d949e522ab69ed0 | jaebradley/leetcode.py | /top_k_frequent_elements.py | 2,068 | 3.90625 | 4 | """
https://leetcode.com/problems/top-k-frequent-elements/
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.... |
1781fd49dbdd2ceb97cbea5659665c843845229e | careduardosilva/TheHuxley | /Strings/Inverter uma string.py | 136 | 4.125 | 4 | string = input()
if(len(string)<= 255):
print(string[::-1])
#string[::-1] eh uma forma de slicing, vai mostrar a "string" invertida
|
0e992fc36e36b4801a93c466630e5c1fdd4a911a | segmond/pythonThingz | /coroutine/study/queue.py | 1,242 | 3.84375 | 4 | # produce/consume simulation
from random import randint
class Queue:
queue = []
queue_capacity = 5
def full(self):
if len(self.queue) >= self.queue_capacity:
return True
else:
return False
def empty(self):
return len(self.queue) <= 0
def add(self, i... |
98f04f68bb2a0459d35ecb201baa0cd3a95c2e78 | adam-gomez/codeacademy-data-science | /list_comprehension_code_challenge.py | 1,734 | 3.65625 | 4 | nums = [4, 8, 15, 16, 23, 42]
double_nums = [num * 2 for num in nums]
nums = range(11)
squares = [x ** 2 for x in nums]
nums = [4, 8, 15, 16, 23, 42]
add_ten = [x + 10 for x in nums]
nums = [4, 8, 15, 16, 23, 42]
divide_by_two = [num / 2 for num in nums]
nums = [4, 8, 15, 16, 23, 42]
parity = [num % 2 for num ... |
1ddd174a3f890acd7829655a218e0cfd31cfcb73 | unfailure/Good_Choices | /Item.py | 432 | 3.8125 | 4 | class Item:
def __init__(self, day, month, year, item_name, cost, category):
self.day = day
self.month = month
self.year = year
self.item_name = item_name
self.cost = cost
self.category = category
def print_item(self):
print("{0}/{1}/{2} {3} ${4} purchas... |
96175a45f72cd4cec926c136117f9a84afb485dd | airenb/com404 | /AE1 Review- TCA 3/3-loop.py | 238 | 4.15625 | 4 | print("How many heroes must we gather?")
heroes = int(input())
print("gathering heroes...")
min_heroes = 0
while(heroes>min_heroes):
heroes = heroes - 1
print(".... found hero," ,heroes,)
print("all heroes have been gathered") |
7a9b4dde1ccf2d9aa1e9c1f0881fabf51106472c | aimaroalberto/pythonLibAimaro | /src/CommandLineArgsParser/parserAccumulateExample.py | 2,620 | 3.5625 | 4 | import argparse
def ciaone():
print("ciano")
parser = argparse.ArgumentParser(prog = None,#'The name of the program (default: sys.argv[0])',
#usage = 'The string describing the program usage (default: generated from arguments added to parser)',
des... |
dd163dd9824b7f24fc0d6229369da927a1692691 | deshiwabudilaksana/Recommender | /recommender/utils.py | 1,066 | 3.6875 | 4 | import numpy as np
from datetime import datetime, timedelta
def status_printer(num_steps, general_duration):
"""
This function prints the duration of one process with #iterations=num_steps
and duration = general_duration.
"""
sec = timedelta(seconds=int(general_duration))
d_time = datetime(1, ... |
8f3a704de39d2d43911f01cba84d5c4b98e803d8 | devmei/KNOU | /35301_Python_R/Chapter06/ch06_01.py | 818 | 4.0625 | 4 | # 8강. 파이썬 Pandas와 R의 dplyr (1)
import pandas as pd
from pandas import Series, DataFrame
# 1.2 Panda 구동과 자료의 생성
# Python 1.1 Series 객체와 DataFrame의 생성
def chap06_01():
s = Series([10, 20, 30], index=['a', 'b', 'c'])
print(s)
'''
a 10
b 20
c 30
dtype: int64
'''
s = pd.Serie... |
b8d57efa297a30f50e0d2b6fe2a7dd2f8f14e759 | Chekoo/Core-Python-Programming | /6/queue.py | 776 | 3.671875 | 4 | queue = []
def enq():
queue.append(raw_input('Enter the new string: '))
def outq():
if len(queue) == 0:
print 'This is error'
else:
print 'Remove [', `queue.pop(0)`, ']'
def viewq():
print queue
cmd = {'e': enq, 'o': outq, 'v': viewq}
def showmenu():
some = '''
e: enter
... |
b80f51777658094fd6c26179096ef014e4104903 | AndrewMiranda/holbertonschool-machine_learning-1 | /supervised_learning/0x08-deep_cnns/2-identity_block.py | 1,824 | 3.703125 | 4 | #!/usr/bin/env python3
"""File that contains the function identity_block"""
import tensorflow.keras as K
def identity_block(A_prev, filters):
"""
Function that builds an identity block as described in
Deep Residual Learning for Image Recognition (2015)
Args:
A_prev is the output from the previous ... |
1d3bd10cf8b3c23d31c2eb9f43d93a10b6d7f428 | keerthz/luminardjango | /Luminarpython/languagefundamentals/largestamongthree.py | 406 | 4.1875 | 4 | num1=int(input("enter num1"))
num2=int(input("enter num2"))
num3=int(input("enter num3"))
if((num1>num2) & (num1>num3)): #30>10 ,30>20
print("num1 is largest",num1)#30
elif((num2>num1) & (num2>num3)): #40>20 ,40>30
print("num2 is largest", num2) #40
elif((num3>num1) & (num3>num2)):# 50>10,50>20
print("num3 ... |
5af6b4d27974e91201e2ab000efeaf8002ed8d76 | Sreelekshmi-60/Programming-lab | /1.3-2area.py | 131 | 4.25 | 4 | r=float(input("Enter the radius of circle :"))
from math import pi
area=pi*r*r
print("Area of circle having radius ",r,"is ",area)
|
be5290d22e94158c185257b94d30086b105ce716 | oscarhscc/algorithm-with-python | /剑指offer/调整数组顺序使奇数位于偶数前面.py | 1,117 | 3.90625 | 4 | '''
题目描述
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
'''
# 解法1 常规思路,需要额外的空间
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
odd = []
even = []
for i in array:
if i % 2 == 1:
... |
683ec6f9c6c7bdff2cdbcdbc68fe20bc4039d235 | Dimen61/leetcode | /python_solution/Tree/106_ConstructBinaryTreeFromInorderAndPostorderTraversal.py | 1,079 | 3.953125 | 4 | # 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 buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
... |
8c3b890f4a5b1dde4458a8a57e9fcca02a5cff45 | mridulpant2010/leetcode_solution | /OOAD/gfg/User.py | 605 | 4.09375 | 4 | from abc import ABC,abstractmethod
class User(ABC):
'''
is the user-class really an abstract one?
which all the methods will be considered for the abstraction?
'''
def __init__(self,userId,name,password):
self.__userId=userId
self.__name=name
#need to take care fo... |
c1099c6999df89f4abaf930f4c9c7fec6291953e | Iamsdt/Problem-Solving | /problems/LeetCode/blind150/array&hash/p36.py | 1,275 | 3.609375 | 4 | from collections import Counter
from typing import List
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
def check(values):
di = Counter(values)
for j in di:
# not filled
if j == ".":
continue
... |
36e68617bb8e8401a29ca98908f9cbdc7c7052df | Kysland/study_polygon | /Python/Lab2/2.py | 425 | 3.953125 | 4 | print("start")
def get_less():
list1 = []
#list2 = []
print("Enter 5 numbers")
for a in range(5):
b = int(input("Enter number: "))
list1.append(b)
c = int(input("Enter number for min sort: "))
m1 = [i for i in list1 if i < c]
#list2.sort(list1, c) - typoi debil
print(m1)... |
ecd101076d2eb278ff784aa553c2a6de0114c15f | MandragoraQA/Python | /praktika_urok4_3.py | 283 | 3.734375 | 4 | chislo=int(input("Введите 4-значное число: "))
a=chislo//1000
b=chislo%1000 #остаток от деления на 1000
c=b//100
d=b%100 #остаток от деления на 100
e=d//10
f=d%10 #остаток от деления на 10
print(a*c*e*f) |
c59e69e1d7c56142dd6212118d509ebcefd9c225 | abhisheksingh75/Practice_CS_Problems | /Stack/Rain Water Trapped.py | 1,116 | 3.75 | 4 | """
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
Input Format
The only argument given is integer array A.
Output Format
Return the total water it is able to trap after raining..
For Example
Input 1:
A = [0,1,0... |
29366f42eb1eda8e43274dba61deabe54de3b347 | Rotbot9k/SeleniumBase | /examples/wordle_test.py | 3,858 | 3.703125 | 4 | """ Solve the Wordle game using SeleniumBase. """
import ast
import random
import requests
from seleniumbase import __version__
from seleniumbase import BaseCase
class WordleTests(BaseCase):
word_list = []
def initialize_word_list(self):
txt_file = "https://seleniumbase.io/cdn/txt/wor... |
45f59ac1eb9246ea49115be5b7096093bc3b4997 | AamodPaud3l/python_assignment_dec8 | /acceleration.py | 332 | 4.125 | 4 | #Program to find value of acceleration(a) in the formula v=u+at
def function(v,u,t):
a = ((v - u) / t)
return a
v = float(input("Enter final velocity: "))
u = float(input("Enter initial velocity: "))
t = float(input("Enter time period: "))
acc = function(v,u,t)
print("{0} m/s^2 is the required acceleration".... |
725d9befd3cd0682e88c340eae8eca05b6527387 | poo250696/python_training | /classes/example.py | 890 | 3.5 | 4 | import prblm7
a_list = [1, 2, 3, 4, 5]
print(a_list[2])
b_dict = {
'a': 'AAA',
'b': 'BBB'
}
print(b_dict['b'])
c_module = prblm7.is_prime(47)
print(c_module)
print(prblm7.TEST_PRINT)
class Test(object):
def __init__(self, name):
self.test = name
def print_test(self):
return se... |
d5108f7ff937830f4b98684ac45c9293a0a8d36a | zitkat/ukoly_py_zs2018 | /03_cykly/fun/cykly.py | 3,018 | 3.59375 | 4 | from toolz import *
from operator import mul, and_, add
from math import sqrt, ceil
print("".join(map(lambda x: "a\n", range(5))))
print("".join(map(lambda x: "Radek {0}\n".format(x), range(5))))
print("".join(map(lambda x: "{0} na druhou je {1}\n".format(x, x**2), range(5))))
print("".join(map(lambda y: "".join(m... |
99d70ca4f9e6fd72e0a2d040876eccb33e462552 | MariaCuenca26/Buscador- | /buscador.py | 902 | 3.84375 | 4 | class buscador:
def __init__(self,dato):
self.lista=dato
def recorrerElemento(self):
for ele in self.lista:
print(ele,end=" ")
for ele in self.lista[::-1]:
print(ele,end=" ")
print()
for pos, ele ... |
b99d85c560af22f7d7b7d5e6c771f180861ecd65 | coldhair/DetectionSystem | /merger.py | 602 | 3.734375 | 4 | def merger(tuple):
sta = set()
str_lis = []
ok = []
for x, y in tuple:
sta.add(x) # 通过集合自动去重
for m in sta:
for n, p in tuple:
if m == n:
str_lis.append(p)
str = '、'.join(str_lis)
str = m + str
ok.append(str)
ret... |
4b7318d8a9016631a38cdc163f618d26627f4883 | viviann-montenegro/learning-notes | /Python/python-exercicios/ex-26.py | 387 | 3.90625 | 4 | """
Leia um valor de área em metros quadrados m² e apresente-o convertido em hectares.
A fórmula de conversão é: H = M * 0.0001, sendo M a área em metros quadrados e H a área em hectares.
"""
m = float(input('Digite o valor da área em metros quadrados: '))
h = m * 0.0001
print(f'O valor da área em metros quadrados: {... |
7aa3df4029387020389d5b295bdbda6d24ad1e2d | spen0203/PythonGroundUp | /Python Basics/Classes.py | 791 | 4.09375 | 4 |
#Normal class with methods
class myClass():
def method1(self): #self refers to the class object it is similiar to this in java
print("myClass method1")
def method2(self, someString):
print("myClass method2 " + someString)
#Inheritance
class anotherClass(myClass): #another class is inheritin... |
46a8cbaf28453a91375dfba8d9c5df9d3b3fedf1 | n1az/crypto-matrix | /main.py | 2,086 | 3.75 | 4 | from getpass import getpass
www = getpass("Enter your password@mint : ")
securityCode = {}
matrixList = []
encodedMatrix = []
pattern = [
[1,2,3],
[1,1,2],
[0,1,2]
]
pattern2 = [
[0,1,-1],
[2,-2,-1],
[-1,1,1]
]
#This method with Initialize the securityCode like 'A':1, 'B':2... 'Z':26
def initia... |
579376ea8f7ba13a09822a4aebdd2ac906c2ac6f | rogatka/data-structures-and-algorithms | /data_structures/graphs/adjacency_matrix.py | 2,163 | 3.625 | 4 | class AdjacencyMatrix:
def __init__(self, n):
self.n = n
self.matrix = [[0]*n for i in range(0, n)]
def __validPos(self, start, end=0):
if (start < 0) or (start > self.n-1) or (end < 0) or (end > self.n-1):
print("Invalid position")
return False
return T... |
f8ed4f67a731b3999511ad0de843040c86ec95b9 | ThisIsSoSteve/simple-game-using-machine-learning | /actions.py | 2,585 | 3.984375 | 4 | '''
Used to display and perfrom actions for the user and their opponent
'''
class Actions:
def __init__(self):
#ToDo: pass in user and ai
#ToDo: create action type enum
self.action_type_attack = 1
self.action_type_affect = 2
#actions lists
self.player_actions = (('... |
f0b667e19397f1e50d7902e246ad4ba4361d6c05 | highshoe/PYTHON | /python-18-object-oriented/src/.svn/text-base/multi_type_customize.py.svn-base | 1,320 | 3.8125 | 4 | '''
Created on 2009-9-29
@author: selfimpr
'''
class NumStr(object):
def __init__(self, self_number = 0, \
self_string = ''):
self.self_number = self_number
self.self_string = self_string
def __add__(self, target):
return self.__class__( \
self.self_numbe... |
7cf6171e90e0ce9ee62ed24897747303aa613f8e | Arolg/2021_python006 | /Lab1/Ex10.py | 133 | 3.828125 | 4 | import turtle
turtle.shape('turtle')
n = int(input())
x = 1
while x <= n:
turtle.circle(50)
turtle.left(360 / n)
x += 1
|
7f1e2a0e17ac23a4f749be80502c25431d9e9565 | bernard16/tut3 | /CONVOL.TUT3.py | 621 | 3.921875 | 4 | # TUTORIAL 3
#QUESTION 1(A).Write a function that will shift an array by an arbitrary amount using a convolution.
#ANSWER:
import numpy as km
from matplotlib import pyplot as plt
def convl(f,ab):
ft = km.fft.fft(f)
return km.real(km.fft.ifft(ft*ab))
x = k... |
6ccf62360a589eb55f9efd0fa3359a9874dcf75a | Mitsz/Universidade | /tela/telasistema.py | 461 | 3.78125 | 4 | class TelaSistema():
def tela_opcoes(self):
print('----- UNIVERSIDADE -----')
print('ESCOLHA O NÚMERO DA OPERAÇÃO QUE DESEJA REALIZAR')
print('1 - Gerenciar curso')
print('2 - Gerenciar disciplinas')
print('3 - Gerenciar atividades')
print('4 - Gerenciar professores'... |
e97bda682a515df2e21c032a6cf2b7fb18af6c05 | xiaohuanlin/Algorithms | /Intro to algo/chapter 4/Strassen.py | 3,802 | 3.609375 | 4 | import unittest
class Matrix:
def __init__(self, X):
self.X = X
self.size = len(X)
@property
def left_top(self):
return Matrix([self.X[i][:self.size//2] for i in range(self.size//2)])
@property
def right_top(self):
return Matrix([self.X[i][self.size//2:] for i in r... |
dd877528493dc4d3d97ab378254ce1766e9d6501 | romersjesusds/T06_damian_angulo | /Angulo/condicionales_multiples/ejer4.py | 536 | 3.59375 | 4 | #EJER4
import os
#declaracion de variables
base_menor,base_mayor,altura,area,figura =0.0,0.0,0.0,0.0,""
#input
figura="trapecio"
base_menor=float(os.sys.argv[1])
base_mayor=float(os.sys.argv[2])
altura=float(os.sys.argv[3])
#processing
area=((base_mayor*base_menor*altura)/2)
#output
print("###############")
print("#f... |
1543e74a974a1a456d7cb46140caeef3776ced63 | JakubJDolezal/opencitations_Cleanup | /reference_comparison_utils.py | 826 | 3.640625 | 4 | """Comparison utils for references used as temporary measure before a comparison class is created"""
def compare_arrays(array1, array2):
"""Simple comparison of two arrays of hashed dois, either cited or citing, if it is empty it returns nothing.
Goes through all the elements and finds how many are equal
... |
d9d3da10bd55d32dd63b1df489f10b94e9856ed1 | reroze/data_analyse | /APriori/set_test.py | 610 | 3.828125 | 4 | '''a = [1, 2, 3]
b = set(a)
print(b)
for i in range(len(a)):
print(a[i])
print(a[2])
'''
'''
c = {1,2,3}
d = {2,3,4}
x = set(c|d)
y = x
print(x)
print(y<=x)
'''
c = [
{'hello', 'buffer'},
{'hello', 'good'},
{'hello', 'buffer'}
]
newx = set({'hello', 'good'})
if newx in c:
print('hello')
a = frozen... |
960a94a49f14d07bdaebfa1ec1393e9453c8f758 | OurGitAccount846/pythontraining | /exampleprograms/merge.py | 261 | 4.09375 | 4 | def merge_Dict(dict1,dict2):
result=dict2.update(dict1)
return result
def main():
dict1={1:10,2:20}
dict2={3:30,4:40}
dict3=merge_Dict(dict1,dict2)
print("after merging two dictionary is :",dict3)
main()
|
6981d2e6494b0be72b6d2a52097bd4780b8d3d27 | mwharmon1/FunctionParameterAndReturnValueAssignment | /test_functions/test_string_functions.py | 433 | 3.921875 | 4 | """
Author: Michael Harmon
Last Date Modified: 9/29/2019
Description: Unit tests to test the multiply_string
function in string_functions.py.
"""
import unittest
from more_functions import string_functions as sf
class MyTestCase(unittest.TestCase):
def test_multiple_string(self):
self.assertEqual(sf.multi... |
fc3d1ba17f5dbc9a8af74833af09b454d0f34819 | GriffithGNeumark/Hex-Invasion | /src/game/game.py | 9,219 | 3.5 | 4 | """
.. module: game
:synopsis: Game module. Contains the Game class, which allows us to control
the game and manipulate the map. This is the primary class from which the
game state is changed and from which we can access the current map.
"""
import os, sys
import copy
from . import movevector
fr... |
bea1baa1b4007fc0e5e7b6815e283bee5f22e608 | er-aditi/Learning-Python | /While_Loop_Programs/Movie _Tickets.py | 427 | 4.09375 | 4 | age = "Enter Age: "
# while True:
# age_1 = input(age)
# if int(age_1) < 3:
# print("Ticket is Free")
# elif int(age_1) < 12:
# print("Ticket cost is 10")
# else:
# print("Ticket Cost is 15")
# Continue
while True:
age_1 = input(age)
if int(age_1) < 3:
continu... |
42d873952995eace3868a6fb8c993c4a450bd117 | SlashTec/MY-DSA-Problem-Solving | /String Manipulation/palindrome Check.py | 1,189 | 4.15625 | 4 | # the Space Complexity is O(1) and the Time Complexity is O(N) (the best)
def palindrome_check(str):
left=0
right=len(str)-1
while left<right:
if str[left] !=str[right]:
return False
left+=1
right-=1
return True
string = "abcdsdcba"
print(palindrome_check(string))
... |
4014aac19c6fb378e1304f27d9db3d5e19cf7bcc | huangj485/binary-division | /division.py | 1,365 | 3.625 | 4 | def flip(s): #flips bits
if s == "0":
return "1"
else:
return "0"
def div(A, B, n): #n is bit length
nA = n
nB = n
toReturn = ""
toReturn += "Divisor: " + str(A) + "\n"
toReturn += "Dividend: " + str(B) + "\n"
toReturn += "Number of Bits: " + str(n) + "\n"
toReturn += "Actual Quotient: " + s... |
0b63060c8c36cf18e696691bbe2336ca887a1833 | EVolpert/seller_ranking | /list_sales.py | 938 | 3.515625 | 4 | import tabulate
def get_ordered_sales(connection):
with connection.cursor() as cursor:
sql = f'''
SELECT seller.seller_name, item_sum.total_value, sale.customer_name, sale.item_name, sale.item_value, sale.created_at
from sale
left join seller on ... |
6c7c12f8d422d5f0497c27f3296f38ca397fc131 | tlylt/ctci-solutions | /ch-02-linked-lists/07-intersection.py | 2,270 | 3.875 | 4 | # Return an intersecting node if two linked lists intersect.
# 1.Run through each linked list to get the lengths and the tails
# 2.Compare the tails. If they are different, return immediately
# 3.Set two pointers to the start of each linked list
# 4.On the longer linked list, advance its pointer by the difference in l... |
664fdae8876b077a072c2c2615ba9d56b2e8418f | hdpoorna/rough_path_sig | /scripts/python/s_x_lev2.py | 1,391 | 3.65625 | 4 | """
s_x_lev2.py
@author: Poorna
Python 2.7
"""
def split_x1x2 (data) :
"Splits data points into X1 and X2 lists"
X1_temp = []
X2_temp = []
for point in data :
X1_temp.append(float(point[0]))
X2_temp.append(float(point[1]))
return X1_temp, X2_temp
def s_x_lev2 (dim1, ... |
5d79486ed47f17a4489c42ab0ecfab3a7fde260e | icarogoggin/Exercitando_python | /Exercicios06_DobroTriploRaizQuadrada.py | 177 | 3.8125 | 4 | var = int(input('Digite um número: '))
print(f'O dobro de {var} vale {var*2}')
print(f'O triplo de {var} vale {var*3}')
print(f'A raiz quadrada de {var} vale {var**(1/2):.2f}') |
f995a628624de519ab1aadc53329f846d8520b09 | staylorofford/staylorofford | /traffic_calculations/calculate_commute_path.py | 9,081 | 3.96875 | 4 | import argparse
import datetime
import glob
from itertools import permutations
import math
import matplotlib.pyplot as plt
def parse_path(path_file, path_columns):
"""
:param path_file: path to path file
:return: list of line segment vertices on path
"""
vertex_list = []
with open(path_file, ... |
30c4699ccac86d9ce9901c06db46c2774260b845 | jty-cu/LeetCode | /Algorithms/061-旋转链表.py | 967 | 3.5625 | 4 | '''
遍历,确定链表长度,对k进行优化
从旋转点开始,把链表分成两份,拼接
'''
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if not head:
return None
## 遍历,确定链表长度
l = 0
dummy = ListNode(-1)
dummy.next = head
tail = dummy
while tail.nex... |
3ca57333b091e60497240f52897c0f8b2d9f1c3b | vicai/cci-py | /ch9_recursion_and_dyamic_programming/9_3.py | 1,220 | 3.578125 | 4 | def magicSlow(array):
for i in xrange(len(array)):
if(array[i]==i):
return i
return -1
# use binary search with distinct sorted array
def magicFast(array):
return help(array, 0, len(array)-1)
def help(array, head, tail):
if(head>tail): return -1
mid = (tail-head)/2+head
if(... |
0d03ef6e30cf76825ff40289535670199483ed39 | nmessa/Stratham-Girls-Coding-Club | /Code for 12.13.2017/Finished Code/backwords.py | 286 | 4.25 | 4 | ##backwords.py
##Author: nmessa
##Date: 12.13.2017
#user enters a word and stores in word
word = input("Enter a word: ")
#if the word has more than 5 characters print it backwards
#or else print it normally
if len(word) > 5:
print(word[::-1])
else:
print(word)
|
2c10e73badb2385c0e9f22b1dd7adc33e16454bf | JeffyLu/whiteboard | /剑指offer/树的子结构/main.py | 830 | 3.953125 | 4 | # -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
if not all([pRoot1, pRoot2]):
return False
if pRoot1.val == pRoot2.val:
res = ... |
6e8b3083b3b025b7b75776bd75bf8f992fcb5cd7 | chikin1993/Cryptography | /my caesar decypher.py | 946 | 4.4375 | 4 | # program to brute-force a caesar cipher
# asking for message
plainText = input('Message to be decrypted: ')
# symbol set for the encryption
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# empty string to fill with encrypted symbols
translated = ''
# converting to uppercase to fit in with LETTERS
plainText = p... |
0a276f2f494d9d882b32a6efa15b85294aaa9865 | wangxiaohui2015/python_basics | /basic_06/class_static_method.py | 490 | 3.546875 | 4 | class Animal:
instance_account = 0
def __init__(self):
Animal.instance_account += 1
def __del__(self):
print("Deleted instance.")
Animal.instance_account -= 1
@classmethod
def show_account(cls):
print("Instance account %d " % cls.instance_account)
@staticmetho... |
b780d649290b9102a3776fd0b02c492cd9e7471d | alekseytanana/coding-challenges | /python_stepik/1_6_1_classes_inheritance.py | 1,041 | 3.671875 | 4 | n = int(input())
classes = {}
def is_subclass(dic, subclass, superclass):
if subclass == superclass:
return "Yes"
for c in dic[subclass]:
if c == superclass:
return "Yes"
if len(dic[c]) > 0:
for val in dic[c]:
if is_subclass(dic, val, superclass)... |
9723d32e8c449ef74ca1bce6ea7f2711a8eb9418 | hoodielive/fluid-python | /play/without_an_iterator.py | 219 | 3.75 | 4 | def squares(value=0):
while True:
value = value + 1
yield (value - 1) * (value - 1)
generator = squares()
print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))
|
8ba156a9b8fecdba56711834a746a6d89f1a62db | feiyu4581/Leetcode | /leetcode 201-250/leetcode208.py | 1,932 | 4.03125 | 4 | class Node:
def __init__(self, val):
self.val = val
self.childs = {}
self._is_word = False
def next(self, char):
if char not in self.childs:
self.childs[char] = Node(char)
return self.childs[char]
def search(self, char):
return char in self.chil... |
0a7b657edec6c25ec56b4af025129b857fe432c4 | tsunny92/PptProj | /Pythonscripts/classdemo.py | 362 | 3.828125 | 4 | #!/usr/bin/env python
class Vehicles:
carname='Fer'
color='red'
price=60000
def descrip(self):
desc_string = "%s has a %s color worth %s" % (self.carname, self.color , self.price)
return desc_string
car1 = Vehicles()
car2 = Vehicles()
car2.carname = 'Merc'
car2.color = 'silver'
car2.price = 10000
pr... |
7f6d4f1e784e14a30479c89b616d04d27c588ca9 | Aasthaengg/IBMdataset | /Python_codes/p02789/s857142944.py | 72 | 3.53125 | 4 | x,y=map(int,input().split())
if x==y:
print("Yes")
else:
print("No") |
e733748820966b15c1ed0dea461d8f3d5ef55b93 | RichardAfolabi/Scientific-Python | /worksheet.py | 6,420 | 3.6875 | 4 | import numpy as np
import numpy.random as rand
from scipy.optimize import curve_fit
import scipy.io as scpy
import matplotlib.pyplot as plt
#%%
import random
alplist = ['c','a','t','d','o','g']
random.shuffle(alplist)
#%%
def cls(): print "\n" *50 #Function to clear screen.
cls()
# Unlike matlab, lis... |
a47ada57ae3bd892371069dac382648950dc5424 | satyam-seth-learnings/python_learning | /Harshit Vashisth/Chapter-22(GUI App1)/251.tkinter.py | 3,733 | 3.65625 | 4 | # python tkinter tutorial
# tee-kinter,tk-inter,kinter
# stater code
# from tkinter import *
# win=Tk()
# import tkinter
# win=tkinter.Tk()
import tkinter as tk
from tkinter import ttk
from csv import DictWriter
import os
win=tk.Tk()
win.title('GUI')
# create labels
# widgets -->label,buttons,radio button-tk,ttk
# pack... |
53f9fb479f99082e3abd6d03942b7cdccc06816b | gayu-ramesh/IBMLabs | /factorial.py | 221 | 4.28125 | 4 | num=int(input("enter a number"))
fact=1
if num==0:
print("factorial does not exist")
elif num<0:
print("enter number greater than 0")
else:
for i in range(1,num+1):
fact =fact* i
print(fact) |
28862fef15f06baf44411defd965d681d8301330 | krashnerd/Scrabble-AI | /utils.py | 793 | 3.609375 | 4 | def get_start_of_word(grid, start_loc, direction = 1):
loc = list(start_loc)
letter = board[loc].get_letter()
while loc[direction] >= 0 and letter is not None:
loc[direction] -= 1
letter = board[loc].get_letter()
loc[direction] += 1
return loc
def grid_transpose(grid):
retur... |
e46121cabb3518a1f74b18829be5b0b4c72b7069 | barbar1k1/HW | /DZ/HW5/practice5.1.py | 263 | 3.6875 | 4 | a = ["EejgKgiiGugGF", "hwgwUEGGHuewghw", "sgheHUREIHrghe"]
def operation(a,operation):
return operation(a)
def upper(a):
res = list(map(str.upper, a))
return res
def lower(a):
res = list(map(str.lower, a))
return res
print(operation(a, upper)) |
318c5ce31f93cc0ae01967fda161699100f381d7 | diegojserrano/Python-1-SAE | /5-6.py | 187 | 3.96875 | 4 | conjunto1 = {3,8,5,2,8,6}
conjunto2 = {3,8,10}
interseccion = set()
for buscado in conjunto2:
if buscado in conjunto1:
interseccion.add(buscado)
print (interseccion) |
6b5ab48be14eb7647556f9fd9f7cacf6b4a3496d | tjha/Tabular-MonteCarlo-TD0-Qlearning | /mdp/lib/gridworld.py | 4,568 | 3.546875 | 4 | import numpy as np
import sys
from gym.envs.toy_text import discrete
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
class GridworldEnv(discrete.DiscreteEnv):
"""
Grid World environment testing the effect of discount factor on finding
shortest path. Your goal is to reach the exits as soon as possible.
The grid lo... |
8c7a281e1ad80448ca14cabf9f9ae7ff614e5d38 | zhengjiani/pyAlgorithm | /prac17.py | 1,898 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/6/13 10:09
# @Author : zhengjiani
# @Software: PyCharm
# @Blog :https://zhengjiani.github.io/
"""
题目描述:
给定一棵二叉树的其中一个节点,请找出中序遍历序列的下一个节点。
如果给定的节点是中序遍历序列的最后一个,则返回空节点;
二叉树一定不为空,且给定的节点一定不是空节点;
某结点有右孩子,则该结点在其中序遍历序列下的后继为其右子树最左下的那个结点
若某结点没有右孩子,且它是其父结点的左孩子,则其父结点为其后继
若它是其父结点的右孩子,则一直往... |
c83eedca5fdb4de4129f7fef6af5a4312ee66ff6 | NataliaKravchenko/python-notebook | /python3 testing_scripts.py | 630 | 3.859375 | 4 | # Python Script 1
mynumber=1
myfloat=3.14
mystring='Hello World!'
myboolean=True
mylist=[1,2,3,4,5]
print(mynumber)
print(myfloat)
print(mystring)
print(myboolean)
print(mylist)
print(f'{type(mynumber)}, {type(myfloat)}, {type(mystring)}, {type(myboolean)}, {type(mylist)}')
#Python Script 2
my_list=[1,2,3,4,5,6,7,8,... |
12efc0dd95b726757d9bcc81261c5b0bb50dc531 | eandrew45/Cracking_the_coding_interview_python | /Chapter_3-Queues-and_stacks/queue_implementation_array.py | 811 | 4.125 | 4 | '''
QUESTION:
Implement a Queue with methods:
add(item): Add item to the end of the list
remove(): remove first item in list
peek(): Return the top of the queue
isEmpty(): return true iff the queue is empty
SOLUTION:
Use an array to do this
'''
######### our implementation starts here ###########
class Queue():
... |
2d85bf912ca59b3ed5851345c1dad40a391a2be8 | niamhlennon/AlgorithmsDataStructuresCA2 | /MovieDictionaryCA2GitHub.py | 17,303 | 3.796875 | 4 | from functools import total_ordering
from math import log, ceil
#insert authorship, copyright, etc here
@total_ordering
class Movie:
""" Represents a single Movie. """
def __init__(self, movietuple):
""" Initialise a Movie Object with a tuple of the 7 data elements. """
if len(movietuple) != ... |
a4291d2a76a8a8cfa12e7a7e81bc6209abfe7f30 | itsuhi/AutomatePython | /Dictionary.py | 3,748 | 4.3125 | 4 | """
Write a function named isValidChessBoard() that takes a dictionary argument and
returns True or False depending on if the board is valid.
A valid board will have exactly one black king and exactly one white king.
Each player can only have at most 16 pieces, at most 8 pawns, and all pieces must be
on a valid space ... |
a5902b64a7490950fa661f1978db83c577da2b13 | YuweiHuang/Basic-Algorithms | /leetcode/tree/1038.把二叉搜索树转换为累加树.py | 808 | 3.53125 | 4 | #
# @lc app=leetcode.cn id=1038 lang=python3
#
# [1038] 把二叉搜索树转换为累加树
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
... |
6727c8bf1c1a0e4b5c9f41748bc422a15a2c9719 | aifulislam/Python_Demo_Five_Part | /program3.py | 747 | 3.671875 | 4 | #03/October/2020--------
#Python Numbers----
#int--------
x = 1
y = 5564546645
z = -544
print(x)
print(type(x))
print(y)
print(type(y))
print(z)
print(type(z))
#float--------
x = 1.10
y = 1.0
z = -55.21
print(x)
print(type(x))
print(y)
print(type(y))
print(z)
print(type(z))
#float--------
x... |
4d07795543989fe481e1141756f988d276f82c02 | tlechien/PythonCrash | /Chapter 7/7.4.py | 469 | 4.25 | 4 | """
7-4. Pizza Toppings: Write a loop that prompts the user to enter a series of
pizza toppings until they enter a 'quit' value. As they enter each topping,
print a message saying you’ll add that topping to their pizza.
"""
if __name__ == '__main__':
topping = None
while topping != "quit":
if topping:
... |
5291f2876bdfe403a235862d5c1246c555307f52 | Venki152/Python | /Yatam_V_Unit5.py | 1,499 | 4.6875 | 5 | # Write a function called FindLarger that accepts two integer arguments arg1 and arg2.
#•In the function, print the larger number on the screen
#Sample Output:
#Inside the Function, the Larger Number is: arg1 # assuming arg1 is larger
#•Where the function was called from, print the smaller number on the screen ... |
863f8f86626f53abe3e7f28f39b278fc8eafb098 | Vya-cheslav/geek | /outOfQuarter/Алгоритмы и структуры данных на Python/lesson_3/task_5.py | 780 | 4.25 | 4 | # 5. В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и позицию в массиве.
# Примечание к задаче: пожалуйста не путайте «минимальный» и «максимальный отрицательный». Это два абсолютно разных значения.
array = [random.randint(-100, 100) for _ in range(20)]
big_negative = [0, -1000]
for ... |
78a14a01b0e3b4c983bc3b549403cadf672f7ca7 | matt24ck/ca117 | /triathlon_v1_111.py | 901 | 3.796875 | 4 | #!/usr/bin/env python3
class Triathlon(object):
def __init__(self, athletes={}):
self.athletes = athletes
def add(self, inst):
self.athletes[inst.tid] = inst
def remove(self, i):
del self.athletes[i]
def lookup(self, i):
try:
return self.athletes[i]
... |
6a54bb3593b4d345ecbd6accbe57d42b46cc06df | zhouzihanntu/Leetcode | /22. Generate Parentheses/generateParenthesis.py | 501 | 3.640625 | 4 | class generateParenthesis:
def __init__(self):
self.res = []
def solution(self, n: int):
self.dfs(n, n, "")
return self.res
def dfs(self, left, right, str):
if left == 0 and right == 0:
self.res.append(str)
return
if left > 0:
... |
8da65219f2253b8fef4879e47ca3c81db8d3e64a | avsuv/python_level_1 | /5/5.py | 277 | 3.546875 | 4 | with open('5.txt', 'w') as file:
nums = input('Введите числа через пробел: ')
file.write(nums)
numbers = []
with open('5.txt', 'r') as file:
numbers = file.read().strip().split()
summ = 0
for num in numbers:
summ += int(num)
print(summ) |
bda2b191f58f61af9522694010fc19a73765e178 | 40003357/IceCream_Shop2 | /icecream.py | 12,489 | 4.15625 | 4 | #!/usr/bin/env python
"""
# This code is to facilitate and automate Ice cream shop
# Date/Time: 07-June-2021 6:40pm
# Author: Vudayagiri Nagaraju
# Contact: vudayagiri.nagaraju@ltts.com
"""
from abc import ABC, abstractmethod
class Login(ABC):
""" Login class used for user or admin profile"""
... |
54aa769275426f553cefd08d56c76abcbfae9cb2 | m-clement/ProgrammingCR | /Objective6/calculator/TestCalculator.py | 747 | 3.84375 | 4 | import unittest
from Calculator import Calculator
class TestHelloWorld(unittest.TestCase):
def test_subtracting_10_from_8_should_equal_minus2(self):
expected = -2
program = Calculator()
result = program.subtract(8, 10)
self.assertEqual(expected, result)
def test_subtra... |
d3447ea3b69861c0ec81777842da668d469076fb | marijamilanovic/Search-Engine | /scripts/Pretraga.py | 11,055 | 3.515625 | 4 | from scripts.Parsiranje import *
from structs.set import *
logicalOperators = ["and", "or", "not"]
def standardQuery(inDir, inWord):
if (len(inWord) > 0): # dozvoljeno do 3 reci
sub_str = inWord.split() # nebitno... |
d27a5b5838feba3686299e228ed002f238746954 | bniebuhr/biodim | /py_backup_2017_10_d10/identify_habareapix_deprecated.py | 867 | 3.59375 | 4 |
def identify_habarea(indiv_xy_position, habareapix_map, userbase = False):
"""
This function identifies the habitat area of a patch in which an individual is.
If userbase = False (simulation on the DataBase maps), the area is in number of pixels;
if userbase = True (simulation on the user (real) maps),... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.