blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
51a17e64d2967bdbe06323a92f24b992e4f7b75e | rishabh-22/Problem-Solving | /two_two.py | 611 | 4.03125 | 4 | """
given an array of numbers, find the possible numbers in it which are powers of two.
"""
def power_of_two(n):
x = int(n) if n[0] != '0' else 0
return x and (not(x & (x - 1)))
def two_two(a):
sub_strings = []
i = 0
while i < len(a):
for l in range(1, len(a)+1-i):
sub_string... |
c42bd40088a7b315f0b7d764e1671da36e28fbbb | Pearltsai/lesson7HW | /lesson7HW_1.py | 188 | 3.578125 | 4 | s=[]
x=int(input('學生數量'))
for i in range(x):
y=int(input('學生成績'))
s.append(y)
print('最高:',max(s))
print('最低:',min(s))
print('平均:',sum(s)/x)
|
0c1878735feb10a5b207a1bf93b2e1a2893dfa7e | JamieBort/LearningDirectory | /Python/Courses/LearnToCodeInPython3ProgrammingBeginnerToAdvancedYourProgress/python_course/Section4Modules/29ExerciseTimeAndMatplotlibPyplot.py | 3,256 | 3.984375 | 4 | # NOT DONE - COME BACK TO to address the following:
# Need to do the following.
# 1. see TODO comment below: consolidate all these for loops below.
# 2. graph plot code copied from ../LearningDirectory/Python/LearnToCodeInPython3ProgrammingBeginnerToAdvancedYourProgress/python_course/Section4Modules/28Matplotlib.py
# 3... |
ba75cea529e9d54b7da04825cd0cd0fe4c45de49 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4165/codes/1585_2895.py | 152 | 3.625 | 4 | var1=float(input("quantidade de jogos"));
var2=float(input("valor do jogo"));
var3=float(input("valor do frete"));
var4=(var1*var2)+var3 ;
print(var4); |
03a9120991f6eadbec9e80a80e49add0110b06ff | choijaehyeokk/BAEKJOON | /1978_소수 찾기.py | 348 | 3.671875 | 4 | import sys
N = int(sys.stdin.readline().rstrip())
numbers = list(map(int, sys.stdin.readline().split()))
cnt = 0
def is_div(n: int)->bool:
for i in range(2, n):
if n % i == 0:
return False
return True
for i in range(len(numbers)):
if numbers[i] == 1:
continue
elif is_div(numb... |
4e7570f3bae74debc4239a9265afde57872f8d69 | Bhargavij-learnings/python_training_assignments | /sum.py | 125 | 3.640625 | 4 | def sum(*args):
result=0
for value in args:
result=result+value
return result
s=sum(10,20,30)
print(s/3)
|
17c0aee7fb6d064a34f1a4a2c923aaf09560c45d | leonhostetler/undergrad-projects | /numerical-analysis/09_odes/ode_rk4.py | 1,146 | 3.84375 | 4 | #! /usr/bin/env python
"""
Solves the initial value ODE of the form
dy/dt = f(y,t)
with the initial condition y(0) = y_0. It is solved using the fourth-order
Runge-Kutta method.
Leon Hostetler, Mar. 2017
USAGE: python ode_rk4.py
"""
from __future__ import division, print_function
import matplotlib.pyplot as pl... |
7d6b81cc02757a1eee09e6246567bda0080dec68 | junyoung-o/PS-Python | /by date/2021.02.23/2164-1.py | 912 | 3.546875 | 4 | import time
start = time.time()
n = int(input())
class CQueue():
def __init__(self):
self.front = 0
self.rear = 0
self.q = [-1] * int(n / 2 + 0.5)
def is_empty(self):
if(self.rear == self.front):
return True
return False
def push(self, target):
... |
df66f4962c2fc5cfe73564737faad80a0bd1daa5 | DimonYin/Coursera_Courses_Dimon_Yin | /Data Structures and Algorithms (UCSD & NRUHSE)/Course 1_Algorithmic Toolbox/Week3/Programming Assignment 3_Greedy Algorithms/change.py | 610 | 3.859375 | 4 | # Uses python3
def get_change(rem):
value_list = [1, 5, 10]
# Sort first
sorted_value_list = sorted(value_list, reverse=True)
coin_list = []
for value in sorted_value_list:
coins = int(rem/value)
coin_list = coin_list + [value] * coins # Add needed coins into output coin list
... |
2da4a38d9a64a10f43cf134eb3becff31992f78a | wwzhen/leetcode_w | /排序算法/归并排序.py | 979 | 4.125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2021/6/8 12:07
# @Author : wwzhen
class Sort(object):
def sort(self, nums):
return self._sort(nums)
def _sort(self, nums):
if len(nums) < 2:
return nums
middle_place = len(nums) // 2
left = nums[0: middle_place]
right = ... |
5d7dbc8884f44894e0424c346308169a889383ff | RevathiRKNair/hello-world | /universal gates.py | 1,400 | 3.71875 | 4 | #! /usr/bin/python
a= input("enter first no:")
b= input("second number:")
class Gate(object):
def __init__(self,a,b):
self.input[0] = a
self.input[1] = b
self.output = None
def logic(self):
raise NotImplementedError
def output(self):
self.logi... |
b0b50262dad3e15d2ca74eeb2e99a1b258d3de5e | artorious/python3_dojo | /test_simple_test_functions_unittests.py | 2,071 | 3.546875 | 4 | #!/usr/bin/env python3
""" Tests for simple_test_functions.py """
import unittest
from simple_test_functions import *
class TestSimpleTestFunctions(unittest.TestCase):
""" Test class for simple_test_functions.py """
def setUp(self):
print('Setting up...........')
def tearDown(self):
... |
f65ce6bcb5a1ac81d3077e33351dca4eeaeccfa6 | Alibi14/thinkpython-solutions | /polindrome.py | 382 | 3.828125 | 4 | def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
def is_polindrome(word):
if len(word) <= 1:
return True
if first(word) != last(word):
return False
print(middle(word))
print('space')
return is_pol... |
83647cf3f12a1e32c7f784a83adb497429f0fb9d | HappyRocky/pythonAI | /LeetCode/22_Generate_Parentheses.py | 1,987 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 17 10:41:46 2018
@author: gongyanshang1
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
给定整数n,要求输出 n 对左右括号的所有可能的有效组合。
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",... |
d0dd79192d3f492f5fd40f2d18e737bdee4eda90 | gerardo-valq/Python_done_works | /Firsttermproject.py | 12,579 | 3.609375 | 4 |
# February 13, 2016
# Angeles Rodriguez Hernandez A01173339
# Gerardo Arturo Valderrama Quiroz A01374994
# Omar Rodrigo Orendain Romero A01374568
# Alfredo Alarcon Valencia A01375414
# Group 4
# Project
# START
# Import Turtle Library
from turtle import *
#Assigning a speed
speed(10)
# Color Setti... |
c71c4117f2a0a7b9bb9fff082be42009aaa34122 | alex123012/Bioinf_HW | /first_HW/first_hw_5.py | 405 | 4 | 4 | a = int(input('Enter number of iterations '))
if a < 2:
raise ValueError('Number of iterations is too small for this program')
fir = float(input('Enter number '))
sec = float(input('Enter number '))
fir, sec = (sec, fir) if sec > fir else (fir, sec)
for _ in range(a-2):
c = float(input('Enter number '))
... |
eeaf26cbd6371adae985d368a581ab58e6a8576c | Oscar-Oliveira/Data-Structures-and-Algorithms | /E_Data_Structures/ds_03_05_graph_03.py | 2,037 | 3.9375 | 4 | """
Bellman-Ford Algorithm
- See: https://www.youtube.com/watch?v=obWXjtg0L64
- See: https://www.programiz.com/dsa/bellman-ford-algorithm
"""
INFINITY = float("inf")
def bellman_ford_shortest_path(graph, start):
previous = {}
distances = {}
for neighbour in graph.keys():
previous[neigh... |
7685a94ddc185210f20c849c67723a5a49aca81a | Duskamo/controlledcar_determinedSim | /src/Maze.py | 732 | 3.625 | 4 |
from graphics import *
class Maze:
def __init__(self,win):
self.win = win
self.initialize()
def initialize(self):
# Set Borders
self.c = Rectangle(Point(50,50), Point(750,550))
self.c.setWidth(5)
# Set Maze
self.l1 = Line(Point(50,200), Point(550,200))
self.l1.setWidth(5)
self.l2 = Line(Point... |
9b3c3285b5c7223f64fda59f4076f880a2066139 | ravi089/Algorithms-In-Python | /String/anagram.py | 239 | 4.125 | 4 | # Check if two strings are anagram or not.
def anagram(strg1, strg2):
return ''.join(sorted(strg1)) == ''.join(sorted(strg2))
if __name__ == '__main__':
strg1 = 'stressed'
strg2 = 'desserts'
print (anagram(strg1, strg2))
|
528bf7f28b40ed04b63e709a39d3d65388f6cb1c | davidalejandrolazopampa/Mundial | /19.py | 288 | 3.65625 | 4 | medidas=[]
for x in range(1,6):
medidas.append(int(input("Agregar Lista: ")))
y=(medidas[0]+medidas[1]+medidas[2]+medidas[3]+medidas[4])/5
desviación=[abs(medidas[0]-y),abs(medidas[1]-y),abs(medidas[2]-y),abs(medidas[3]-y),abs(medidas[4]-y)]
print(medidas)
print(desviación)
|
704ee14892f11c8f632c73f3351dbc2b19d87baf | jlshix/nowcoder | /python/20_stack_with_min.py | 835 | 3.875 | 4 | """
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
"""
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
# s1 是普通栈, s2 是最小栈
self.s1 = []
self.s2 = []
def push(self, node):
# write code here
# 此时 s2 压入的是当前值对应的最小值
self.s1.append(node)
if ... |
a6fc982c4ec3547f94609f65f94e732c0d15568e | nameera0408/Practical-introduction-to-python_Brainheinold | /ch3_11sol.py | 191 | 3.703125 | 4 | kg = eval(input("Enter Your Weights in Kg: "))
pound = round(weight_kg * 2.20,1)
print("Your Weight in Pounds is :",pound)
#1/10 means pounds having only one number after the decimal point
|
b86652b54b86e491790790a5915e77899cbc1e7f | greenfox-velox/zsoltfekete | /week-03/day-02/35.py | 160 | 3.859375 | 4 | def factorial(input_number) :
factorta = 1
for i in range(1, input_number+1):
factorta = factorta * i
return factorta
print(factorial(10))
|
0b21bb3e1c9a5c50e1a3455267476d1176fa5266 | gconsidine/project-euler | /012.py | 1,236 | 3.984375 | 4 | #Greg Considine
#Project Euler -- Problem 12
import math
# Returns the number of divisors for any given number (triangular numbers in
# this case).
def getDivisorCount(n):
divCount = 1
i = 2
while i <= math.sqrt(n):
if n % i == 0:
divCount += 1
i += 1
return divCount * 2
# Exhuastivel... |
bc5fc54c9136c4886779ec12ad3b58563d1d66cd | Activity00/Python | /leetcode/1_linked_list/25. Reverse Nodes in k-Group.py | 1,932 | 3.921875 | 4 | """
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked lis... |
ff72a8e2bba4fc92b1a34317125f48a87b05f741 | hornedwarboy/AlgoToolBoxCoursera | /week3/MaximumSalary(Q7).py | 1,145 | 4.25 | 4 | def isLargestOrEqualto(digit,max_digit):
#This function checks for the best digit or number which makes the largest sequence of number(A/Q).
return int(str(digit) + str(max_digit)) >= int(str(max_digit) + str(digit))
def largestNumber(lst):
#This is the list where our ans is stored is stored as ... |
d7e8a6ead48abe0c5f3d23e569afecfb6e09c54e | gordon-sk/PycharmProjects | /PHYS_2237/bikeQuadraticResistanceHill_Chapter2V2.py | 13,511 | 3.828125 | 4 | # Edited by Gordon Kiesling, 1/26/17 for Phys 2237, edits are documented below with comments
# Program 2.3 Solution for the position and velocity of a bicycle traveling along a hill with quadratic air resistance
# (bikeQuadraticResistanceHill_Chapter2V1.py)
#
# Give the command python bikeQuadraticResistanceHill... |
6894c08b2da437e9ac627ef08c5249c49877ef41 | yyeunggg/Leetcode-Practice | /DP/646. Maximum Length of Pair Chain.py | 1,901 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 9 12:09:21 2020
@author: steve
"""
"""
646. Maximum Length of Pair Chain
https://leetcode.com/problems/maximum-length-of-pair-chain/
"""
# Can use DP in this problem
"""
Runtime: 2240 ms, faster than 39.90% of Python3 online submissions for Maximum Length... |
07a8db376caba62126c25ada7524c042462d7656 | ggstuart/pyasteroids | /pyasteroids/mass.py | 3,012 | 3.546875 | 4 | from math import pi, cos, sin, sqrt, atan
from random import random, randint, choice
MIN_RADIUS = 20
MAX_DENSITY = 0.05
class Point(object):
def __init__(self, position, arena):
self.arena = arena
self.arena.place(self, *position)
def position(self):
return self.arena.where_is(self)
... |
80c54bba5df60fe28d42a19d20f4e43be3704b96 | vishalpmittal/practice-fun | /funNLearn/src/main/java/dsAlgo/leetcode/P6xx/P657_RobotReturntoOrigin.py | 1,539 | 4.1875 | 4 | """
Tag: string, matrix
There is a robot starting at position (0, 0), the origin, on a 2D plane.
Given a sequence of its moves, judge if this robot ends up at (0, 0)
after it completes its moves.
The move sequence is represented by a string, and the character moves[i]
represents its ith mov... |
5553dcfbc8d3bcbe9a0af369aa5202aef6c58e7f | i-Xiaojun/PythonS9 | /Day12/1.装饰器进阶.py | 964 | 3.71875 | 4 | # 装饰器带参数实现
# FLAG = False
# def wrap_flag(FLAG):
# def wrap(func):
# def inner(*args,**kwargs):
# if FLAG:
# print('-----Before------')
# ret = func(*args,**kwargs)
# if FLAG:
# print('======After=======')
# return ret
# ... |
0c1721f1ca9493d92456f47be3b55124606176bc | Grey2k/yandex.praktikum-alghoritms | /tasks/sprint-5/M - Heap Sift Up/sift_up.py | 265 | 3.5 | 4 | def sift_up(heap: list, idx: int) -> int:
if idx == 1:
return idx
parent_idx = idx // 2
if heap[parent_idx] < heap[idx]:
heap[idx], heap[parent_idx] = heap[parent_idx], heap[idx]
idx = sift_up(heap, parent_idx)
return idx
|
5635b2b20ec83bbfc96123cf3e3fa757db80fecf | eulersformula/Lintcode-LeetCode | /Longest_Substring_Without_Repeating_Characters.py | 1,892 | 3.71875 | 4 | # Lintcode 384//Medium//Adobe//Amazon//Yelp//Bloomberg//Yelp
# Leetcode 3//Medium
#Given a string, find the length of the longest substring without repeating characters.
#Example:
#For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
#For "bbbbb" the longest sub... |
baf9a7f27bbb8bb66f3565d3b3be2daf9651d090 | dongrerohan421/python3_tutorials | /06_strings.py | 686 | 4.34375 | 4 | '''
This program explains Pytho's string
'''
# Escape character usefule to jump over any character.
# Use double back slash to print back slash in your output.
a = 'I am \\single quoted string. Don\'t'
b = "I am \\double quoted string. Don\"t"
c = """I am \\triple quoted string. Don\'t"""
print (a)
print (b)
print (... |
3d61675b72846e370d755723e8d9af1fd7b549b7 | andrefsp/models-to-production | /rnd/common/model_builder.py | 4,756 | 3.546875 | 4 | """ Code for building models """
import tensorflow as tf
class Model(object):
"""
Base model class
::
All models on Neuron must subclass and implement this methods.
"""
def __init__(self, config):
self.config = config
def get_callbacks(self, session):
""" Returns a... |
6d33ea99fbe4e278828c35a4ba1e74112d3cf430 | kfrankc/code | /python/max_path_tree.py | 1,202 | 4.03125 | 4 | # Given a binary tree, find the maximum path sum.
# The path may start and end at any node in the tree.
# Example :
# Given the below binary tree,
# 1
# / \
# 2 3
#
# Return 6.
import sys
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
... |
df4b00fbab5c9844961181e0e34ae6424bdc45db | shivampuri20/LPTHW | /exp14.py | 343 | 3.546875 | 4 | class thing(object):
def __init__(self):
self.number =0
def function(self):
print("i got called")
def add_me(self,more):
self.number+=more
return self.number
a=thing()
b=thing()
a.function()
b.function()
print a.add_me(20)
print b.add_me(30)
print a.add_me(40)
print a... |
d4c5968e7381220b270cb9dbe29d00d71e7c9c01 | abhiwalia15/practice-programs | /set_operations.py | 354 | 3.828125 | 4 | #python program to find perform different set operations .
#display the two sets.
E = {0,1,2,3,4,5,6,7,8,9,10}
N = {2,4,6,8}
#union of sets (U)
print("UNION =",E | N)
#intersection of sets (n)
print("INTERSECTION =",E & N)
#difference of sets (-)
print("DIFFERENCE =",E - N)
#SYMMETRIC DIFFERENCE OF SETS (/_\)
prin... |
89c98799fa77253ef5f66b5ffa7e988db69c23c7 | pixilcode/B7-Python | /hangmanBrendonBown.py | 966 | 3.890625 | 4 | #Excercise 3: Hangman
word = (input('Word >>> ')).lower();
answer = ('_' * len(word));
guesses = set(['']);
chances = int(input('Chances >>> '));
incorrect = 0;
for num in range(50):
print();
while incorrect < chances:
print('Already Guessed: ' + str(guesses));
guess = ((input('Letter >>> '))[0:1]).lower(... |
e35f1c78bbc87d9616f7df776b23a2367f20bf84 | Leopold0801/numpy-pandas_exercise | /numpy_copy.py | 531 | 3.625 | 4 | import numpy as np
a = np.arange(4)
# array([0, 1, 2, 3])
b = a
c = a
d = b
a[0] = 11
print(a)
# array([11, 1, 2, 3])
d[1:3] = [22, 33] # array([11, 22, 33, 3])
print(a) # array([11, 22, 33, 3])
print(b) # array([11, 22, 33, 3])
print(c) # array([11, 22, 33, 3])
... |
bc82c5e7522b04054b4340828fa0015584c531d5 | ayamschikov/python_course | /lesson_2/1.py | 630 | 4.0625 | 4 | # 1. Создать список и заполнить его элементами различных типов данных. Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа. Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
my_list = [1, 'test', [], {'key': 'value'}, ('tuple', 'tuple')... |
ecc3aad5add8aa3e89ed740a4221ce121e126677 | vinlok/vinlok.github.io | /_posts/algorithms/arrays/leetcode/max_profit_buy_sell.py | 177 | 3.5 | 4 |
algo:
1. set low price to = 9999
2. max_profit = 0
3. now iterate on prices:
if price > low:
max_profit= max(price-low,max_profit)
else:
low=prices
|
b2e4bfa81bb861b7ff5d98d8d68b87d83c7adaba | MelloWill36/Python-Curso-em-Video | /75.py | 499 | 4.0625 | 4 | num = (int(input('Digite um numero: ')),
int(input('Digite um numero: ')),
int(input('Digite um numero: ')),
int(input('Digite um numero: ')))
print(f'Voce digitou os valores {num}')
print(f'O valor 9 apareceu na {num.count(9)} vezes')
if 3 in num:
print(f'O valor 3 apareceu na {num.index(3)+1}ª'... |
011a0023f285b66d9349c38863090b6eb2851603 | nkmk/python-snippets | /notebook/arithmetic_operator_list_tuple_str.py | 1,160 | 3.953125 | 4 | l1 = [1, 2, 3]
l2 = [10, 20, 30]
t1 = (1, 2, 3)
t2 = (10, 20, 30)
s1 = 'abc'
s2 = 'xyz'
print(l1 + l2)
# [1, 2, 3, 10, 20, 30]
print(t1 + t2)
# (1, 2, 3, 10, 20, 30)
print(s1 + s2)
# abcxyz
# print(l1 + 4)
# TypeError: can only concatenate list (not "int") to list
print(l1 + [4])
# [1, 2, 3, 4]
# print(t1 + 4)
... |
039e56614b5e1f48dcedef53dcc536cbee9cef6a | DhanashriMadhav/DSA | /strings/reverse.py | 144 | 4.15625 | 4 | def reverse(str1):
i=-1
while i>=(-len(str1)):
print(str1[i],end="")
i-=1
str1=input("enter the string")
reverse(str1)
|
b8a7172cbe9576221f2ac75f6296cc278c6db95b | borekon/divicaubot | /utils.py | 906 | 3.546875 | 4 | import os
def get_files_by_file_size(dirname, reverse=True):
""" Return list of file paths in directory sorted by file size """
# Get list of files
onlyfiles = [f for f in os.listdir(dirname) if os.path.isfile(os.path.join(dirname, f))]
# Re-populate list with filename, size tuples
f... |
7f5b0e5928ae4060611b6337b397b4322d5a7c01 | 1MT3J45/pyprog | /area.py | 332 | 3.796875 | 4 | class Area:
def __init__(self):
self.r = 0
self.s = 0
def display(self):
a = 3.14 * self.r * self.r
return a
class New(Area):
def __init__(self,r,s):
self.r = r
self.s = s
def show(self):
s = self.display()
print "Circle area: ",s
a = self.s * self.s
return a
n = New(12,15)
print "Square area: ... |
9bf95cc73befc55b5a8b8eeef454c7698c99412b | green-fox-academy/FKinga92 | /week-02/day-02/reverse.py | 381 | 3.65625 | 4 | # - Create a variable named `aj`
# with the following content: `[3, 4, 5, 6, 7]`
# - Reverse the order of the elements in `aj`
# - Print the elements of the reversed `aj`
aj = [3, 4, 5, 6, 7]
for i in range(len(aj)//2 +1):
if i != len(aj)//2:
aj[i] += aj[len(aj)-i -1]
aj[len(aj)-i -1] = aj[i] - a... |
de920a51cd51a4584878e94a4828474f5ea8bf18 | jbenaventeheras/supremebot | /config.py | 631 | 3.65625 | 4 | import datetime
INTRO = """This is a Supreme bot"""
file_obj = open("keys.txt")
print(INTRO)
product_url = input('Copy and Paste Product URL (must contain "https://www."):\n')
if "https://www." not in product_url:
product_url = "https://www." + product_url
current_datetime = datetime.datetime.now()
keys = {}
k... |
2ef5a19ca08c1b199614d87c762414aba597675d | systemchip/python-for-everyone | /c5/cgi-bin/dice.py | 341 | 3.609375 | 4 | #!/usr/bin/env python3
import random
# 헤더를 출력한다
print("Content-Type: text/html")
print("") # 헤더와 몸체를 구별하는 빈 행
# 무작위 수를 얻는다
no = random.randint(1, 6)
# 화면에 출력한다
print("""
<html>
<head><title>Dice</title></head>
<body>
<h1>{num}</h1>
</body>
</html>
""".format(num=no))
|
cc774b543d143f1f17d6a2d88d465a762070b05c | AlvarocJesus/Exercicios_Python | /AulaTeorica/exerciciosModulos/exercicio4/main.py | 591 | 3.546875 | 4 | import verificaSenha
def main():
senha = input('Digite sua senha: ')
if verificaSenha.tamanhoMin(senha):
if verificaSenha.letraMaiuscula(senha):
if verificaSenha.letraMinuscula(senha):
if verificaSenha.umNum(senha):
print('Senha forte!')
else:
print('Senha tem que ter... |
e2c8f85229419f9abc9e3c77083b0dd152e2cd1f | llgeek/leetcode | /433_MinimumGeneticMutation/solutoin.py | 1,382 | 3.5625 | 4 | from collections import deque
class Solution:
def minMutation(self, start: 'str', end: 'str', bank: 'List[str]') -> 'int':
def buildGraph(bank):
bankset = set(bank)
graph = {}
for node in bankset:
if node not in graph:
graph[node] = set... |
920dcc7ec5ecc898379400a8a66f75d21f3840f9 | xwqiang/PyTest | /Test/SetTest.py | 559 | 3.5625 | 4 | '''
@author: xuwuqiang
'''
# import matplotlib.pyplot as plt
# -*- coding: utf-8 -*-
# fig = plt.figure()
# ax = fig.add_subplot(1,1,1)
def PlotDemo1():
# fig = plt.figure()
# ax = fig.add_subplot(1,1,1)
x = []
y = []
f = open('/Users/xuwuqiang/Documents/backyard/datas/teminalSum.csv')
for it... |
81a01565bf7be47feb941567b4971eb4736fcfcb | noserider/school_files | /myfirstbasic.py | 169 | 3.8125 | 4 | print ("What is your name?")
firstname = input()
print ("Hello,",firstname)
print ("What is your surname?")
surname = input()
print ("Hello,",firstname,surname)
|
8b1c62c61d616f51a668b8f4410040cb53c5b153 | pgThiago/learning-python | /python-exercises-for-beginners/009.py | 543 | 4 | 4 | # Tabuada em Python
print('==' * 4)
print('\033[34mTABUADA\033[m')
print('==' * 4)
n = int(input("Digite o valor que deseja saber a tabuada: "))
print("{} x {:2} = {}".format(n, 2, n * 2))
print("{} x {:2} = {}".format(n, 3, n * 3))
print("{} x {:2} = {}".format(n, 4, n * 4))
print("{} x {:2} = {}".format(n, 5, n * 5))... |
85cc423f5e8356863e1e6ee7f534427b04576527 | karthiklingasamy/Python_Sandbox | /B11_T5_Comprehension_Nested_For_Loop.py | 252 | 4.15625 | 4 | # List Comprehension using nested for loop
my_list = []
for letter in 'abcd':
for num in range(4):
my_list.append((letter,num))
print(my_list)
my_list1 = [(letter,num) for letter in 'abcd' for num in range(4)]
print(my_list1)
|
37c29ee436436c8c77313fe89b52ee7fce3bbb80 | Raj-kar/Python | /functions advance/unpacking_dict.py | 709 | 3.96875 | 4 | # 1st example
def greetings(first, second):
print(first + " greets " + second)
# greetings("Raj", "Rahul")
names = {"first": "Raj", "second": "Rahul"}
greetings(**names) # unpack the dict
# 2nd example
def calculate(num1, num2, num3):
print(num1+num2*num3)
calculate(1, 2, 3) # noraml pass values
num... |
2fa41df6b5b723c18c1c713cfad22a015f9add68 | rodrigopc-bit/treinamento-maratona | /H. Ovni/ovni.py | 218 | 3.625 | 4 | t=int(input())
for i in range(t):
a=input().split(" ")
b=int(a[0])+int(a[1])
if b>int(a[2]):
print("NAO CABE!",end="" if i==t-1 else "\n")
else:
print("CABE!",end="" if i==t-1 else "\n") |
a842726c573bca40852b9aabaf82aaf0e78b3ec0 | skogsbrus/advent_of_code_2018 | /01-part2.py | 957 | 3.828125 | 4 | import argparse
from pathlib import Path
from functools import reduce
from operator import add, sub
"""
You notice that the device repeats the same frequency change list over and over. To calibrate the device, you need to find the first frequency it reaches twice.
"""
def get_args():
parser = argparse.ArgumentPa... |
84720e95fc3d774974684e6ea424c13a79795986 | wcneill/Project-Euler-Solutions | /pe010.py | 898 | 3.921875 | 4 | import pe007 as p7
from timeit import default_timer as timer
def runtime(func, args):
"""
This method will run and return total run time of any function passed
to it.
:param func: The function to time.
:param args: Positional arguments for the function
:return: Runtime in fractional seconds
... |
645f2bcb7ab5792eba761c8903b286b020314217 | ABCmoxun/AA | /AB/linux1/day10/day09_exercise/01_mysum.py | 281 | 3.78125 | 4 | # 1. 写一个函数,mysum,可以传入任意个实参的数字,返回所有实参的和
# def mysum(....):
# ....
# print(mysum(1,2,3,4)) # 10
# print(mysum(5,6,7,8,9)) # 35
def mysum(*args):
return sum(args)
print(mysum(1,2,3,4)) # 10
print(mysum(5,6,7,8,9)) # 35 |
dc378420d3184a1b070a823b713b9f12bd800c48 | confettimimy/Python-for-coding-test | /• 프로그래머스/JadenCase 문자열 만들기.py | 673 | 3.859375 | 4 | # 첫 번째 나의 풀이 -> 정확성 43.8
def solution(s):
ls = s.split()
for i in range(len(ls)):
ls[i] = ls[i][0].upper() + ls[i][1:].lower()
# word[0] = word[0].upper() # 문자열 요소 변경불가라는 사실 잊지말기!!!
#word[0].upper() + word[1:].lower() # word[i]가 아니라 ls[i]로 해야 됨!
#print(word) # word만 바뀌고 ls 원... |
b6e96a5ccd19e524d7613b6ffdc408f584e8920d | beauthi/contests | /BattleDev/032020/ex4.py | 1,678 | 3.5 | 4 | from itertools import permutations
def compute_score(sacha_card, my_card):
if sacha_card == "feu":
if my_card == "eau":
return 1
if my_card == "plante":
return -1
if my_card == "glace":
return -1
return 0
if my_card == "feu":
return - ... |
1be24512439e947ee7dd1be15fec482c8fac8ea7 | tannupriyasingh/Coding-Practice | /Tree/maxDeptSolution.py | 559 | 3.625 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class maxDeptSolution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
height = 0
if root:
... |
cd6fb80cb9443d7609c90ad2ca9ca65f60c61216 | thamilanban-MM/Python-Programming | /Beginner Level/sum of N natural numb.py | 166 | 3.734375 | 4 | N=raw_input("")
if isinstance(N,str):
if ((N>='a') and (N<='z') or (N>='A') and (N<='Z')):
print("invalid input")
else:
N=int(N)
sum=(N*(N+1))/2
print(sum)
|
e7a002437ec9559a776502bdb847de6aeefc35d1 | seungjaeryanlee/clarity | /tests/test_recursion.py | 3,623 | 3.59375 | 4 | #!/usr/bin/env python3
"""
This file defines unit tests for the recursion module.
"""
from clarity.Board import Board
from clarity.Move import Move
from clarity.MoveType import MoveType
from clarity.recursion import divide, perft, negamax, _negamax_recur
from clarity.Sq import Sq
class TestRecursion:
"""
This... |
deb4e33d166bea120edb15beb03e39a1210ac609 | MilapPrajapati70/AkashTechnolabs-Internship | /day 4/task 2 (4).py | 583 | 4.40625 | 4 | # 2.Create a class cal2 that will calculate area of a circle.
# Create setdata() method that should take radius from the user. Create area() method that will calculate area .
# Create display() method that will display area
class cal2:
def setdata(self):
self.r = float(input("enter the radius o... |
dfe35b15056e92993d389a093acd6457b0fb2d0e | ajonaed/Python-DS | /Chapter 1/list_comprehension.py | 501 | 4.0625 | 4 | #Regular List
result = []
for i in range(0,21):
if i % 2 == 0:
result.append(i)
print(result)
# List creation using List Comprehensive syntax
results=[i for i in range(0,21) if i % 2 == 0]
print(results)
'''Both should create a new List, but way of creating a list is different
the comprehensive syntax i... |
256321ce4520d6bdaa4df53a35b55019137f33f6 | alexkie007/offer | /LeetCode/树/617. 合并二叉树.py | 1,383 | 4.125 | 4 | """
给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
示例 1:
输入:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ ... |
75bfa2e2da70b19778274844f8b2ab8afee1e5ea | hujeff/select_lunch | /V2.1/main.py | 1,695 | 3.84375 | 4 | import select_lunch
import random
def select_food():
lst = select_lunch.selectlunch() #从函数中获得的是一个元祖
lst = [x.strip() for x in lst]
randomchoice = random.choice(lst)
lst.remove(randomchoice)
choice_a = input('我们吃%s可好?(好或不好)'% randomchoice) #请用户判断所选内容是否符合要求
while True:
if choice_a == '好'... |
d473bd24568222cf40e25b99f0799d5d9625af80 | Vinz974/GomoBot | /gomoku_game/Game_board.py | 6,675 | 3.75 | 4 | import copy
class Board:
def __init__(self):
self.size = 9
self.white = []
self.black = []
self.win = False
self.board = [['.' for x in range(self.size)] for y in range(self.size)]
self.winLog = "Win!"
self.c = 'x'
self._isBlack = True
def _inBo... |
56aa3d18111b7b364e7696671f21e08278732667 | ROHANNAIK/datasleuthing | /Ex_Files_UaR_Python/Ex_Files_UaR_Python/Exercise Files/assign/problem1_7.py | 451 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 28 16:02:31 2017
@author: Rohan
"""
#%%
def problem1_7():
b1 = input("Enter the length of one of the bases: ")
b1 = float(int (b1))
b2 = input("Enter the length of the other base: ")
b2 = float(int (b2))
h = input("Enter the height: ")
h = float(i... |
36e25227a020fc944d185657e93e98db8785e6b8 | shahpriyesh/PracticeCode | /DynamicProgramming/FreedomTrail.py | 748 | 3.515625 | 4 | class FreedomTrail:
def freedomTrail(self, ring, key):
steps = 0
size = len(ring) - 1
for ch in key:
left = ring.find(ch)
right = size - ring.rfind(ch)
if left < right:
ring = self.rotate(ring, left)
else:
ring =... |
cb96b509015272dd421a3deba84568b2e9561c05 | Badr24/Code-in-Place-Projects | /project.py | 8,699 | 4.34375 | 4 |
""""
This program is a blood group test, the program first will ask to register an account with username and blood type
then it will store it in a dictionary as key and value.
The next the program will store the accounts in csv file in append mode to make sure not to overwrite the file
following the program will s... |
71394caacf26f286a465c8b24df40c88cd59710d | ausaki/data_structures_and_algorithms | /two_sum.py | 455 | 3.734375 | 4 | def two_sum(sequence, sum):
sequence = sorted(sequence)
i = 0
j = len(sequence) - 1
while i < j:
tmp = sequence[i] + sequence[j]
if tmp == sum:
yield sequence[i], sequence[j]
i += 1
j += 1
elif tmp < sum:
i += 1
else:
... |
fe394fc1640b1193d8344765fb6838f6be4fe2b9 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_PyAlgo-Tree/Cryptography/Transposition Cipher/transposition_cipher.py | 1,350 | 4.03125 | 4 | import math
key = int(input("Enter key: "))
# Encryption
def encryption(msg):
cipher = ""
text_len = float(len(msg))
text_list = list(msg)
col = key
# maximum row of the matrix
row = int(math.ceil(text_len / col))
# the empty cells at the end are filled with '/'
fill_null = int((row ... |
1f91cfd457f4e4d07702c4a207ebbfc903eee5be | Afra55/algorithm_p | /sort/selection_sort.py | 785 | 3.953125 | 4 | """
选择排序, O(n^2)
"""
from random import shuffle
def findsmallest(arr):
"""
获取列表中最小值的 index
:param arr: 列表
:return: index
"""
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
... |
48c0acebab1df40f37c1a0519e6e65f271d6115d | praveena2mca/praveena | /oddeven.py | 169 | 4.25 | 4 | y=int(input("enter the n value")
if(y%2==0):
print("the given number is even")
elif(y%2==1):
print("the given number is odd")
else:
print("the wrong input")
|
1646031137156a19601e5a4dbacff58b68b6c80b | eestec-lc-thessaloniki-it-team/Algorithm-Training | /Meeting_9-11-2019/Harrys-Giannis/heapSort.py | 522 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Simple Implementation of Heap using th heapq library. Heapify will transform the
#list to a heap and then we can use heappop to always get the minimum element
#of the heap. With a simple appending we will get the ordered list. O(n)+O(nlogn)
import heapq
def heapSort(l):... |
76f8f292838f492d64f3ff870c37eb8d2d716125 | ledbagholberton/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py | 155 | 3.609375 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
suma = 0
for i in range(1, 10):
if i in my_list:
suma = suma + i
return(suma)
|
92e0090200e83b0e01d6affc227d30c19118f0c3 | jfxugithub/python | /regular_expression.py | 3,155 | 3.890625 | 4 | """
[] 匹配[]中列举的字符(代表一个字符)
\d 可以匹配一个数字
\D 匹配非数字
\w 可以匹配一个字母,数字,下划线
\W 匹配非字符
\s 可以匹配一个空格(也包括tab等空白符)
\S 匹配非空格
. 可以匹配任意一个字符
* 表示任意多个字符(包括0个)
+ 表示至少一个字符
? 表示0个或一个字符
{n} 表示n个字符
{n,} 表示至少n个字符
{n,m} 表示n-m个字符
\b 匹配字间,用的少,需要网上查
"""
#####example
# \d{3}\s+\d... |
f2b42f7fdbd15e8c9d5343bbd3ff7aca8a8d4099 | MStevenTowns/Python-1 | /SecretMessage.py | 1,508 | 3.96875 | 4 | # M. Steven Towns
#Assignment 8
#2/4/2014
encoder=True
while encoder:
msg=raw_input('What do you want to encode?: ')
shift=int(raw_input('what do you want to shift it by?: '))%26
secret_msg=""
for i in range(len(msg)):
letter=msg[i]
if letter.isalpha():
if letter... |
8fe61f094c63b3b807aac938d3f4d2a0c0b36075 | capuanob/Cyber-Cell | /user_interface.py | 1,433 | 3.796875 | 4 |
class UI():
def print_menu(self):
print(
"Welcome to Cyber Cell! Would you like to view instructions on how to play? [Y/N]")
if self.validate_input():
self.print_instructions()
def validate_input(self):
response = input("Enter your choice: ")
while res... |
9f633cc6eafdf9b2fad8fffa4787f6cc032522c6 | alexluong/algorithms | /leetcode/non-decreasing-array/Solution.py | 802 | 3.578125 | 4 | class Solution:
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
isPossible = True
before = None
running = nums[0]
larger = 0
for i in range(len(nums)):
num = nums[i]
if num < running:
... |
f5f475396a9e70f89688d34d3e7b89a80869b787 | silvisig/pep20g06 | /modul6/modul6_1.py | 6,024 | 3.828125 | 4 | # iterators
class ListIterator():
def __init__(self, my_list: list):
self.my_list = my_list
def __next__(self):
if len(self.my_list) == 0:
raise StopIteration
return self.my_list.pop(0)
# o lista e un ob care se modifica , prin pop il modificam ,
# prin lista tin ... |
5878b0991e8f553f609e0a01d6f0c8630f659b7c | liquse14/MIT-python | /python교육/Code05-05.py | 148 | 3.703125 | 4 | a=int(input("정수를 입력하세요:"))
if a %2==0:
print("짝수를 입력했군요.")
else:
print("홀수를 입력했군요.")
|
7a31bd7409c5445ed43f24eeb932cef002338221 | bayajeed/Python | /hello.py | 287 | 3.90625 | 4 | #This is my first practice of PYTHON
print ("hello! this is my new world ")
""" hEA
ALDKJF JASDJFLK
ASDF AJSLFJS D
FASDF JASLDFJ
ADF;AJFLASF
ADSFJAKLDFJ
LJSLKDFJDSFL """
name="Bayaljeed"
print("Name "+name, type(name))
age=20
weight = 50
print("Age",age, type(age), "\nWeight " ,weight)
|
abbc0dedebc1dfb2dbb5880f871073e26a554932 | tobeyOguney/Zoo-of-Algorithms | /Insertion Sort/solution.py | 579 | 4.21875 | 4 | # Implements the insertion sort algorithm
# O(n^2) time | O(1) space
def insertion_sort(lis):
for i in range(1, len(lis)):
current_item = lis.pop()
is_last = True
for j in range(i):
if current_item < lis[j]:
lis.insert(j, current_item)
is_last =... |
6904a397edeada6708c584a70b9cb1ee0d645916 | adikmamytov/codify_homework | /adilet_mamytov_tuple.py | 420 | 4.28125 | 4 | # adilet mamytov
# Дан кортеж (1, '2', 3, 4, '5', 6, 7, '8') сформируйте новый без строк с помощью цикла for и проверки на int:
# type(i) == int, где i - новый элемент в цикле
my_tuple = (1, '2', 3, 4, '5', 6, 7, '8')
temp_tuple=[]
for i in my_tuple:
if type(i)==int:
temp_tuple.append(i)
new_tuple=tuple... |
fee108c1664ba50eef708c18e01723f805936c6d | kabaksh0507/exercise_python_it-1 | /sampleproject/book/BeginningPython3_O_REILLY/chapter6/6-5.py | 292 | 3.796875 | 4 | elm_list = {'name':'Hydrogen', 'symbol':'H', 'number':1}
class Elements():
def __init__(self, name, symbol, number):
self.name = name
self.symbol = symbol
self.number = number
hydrogen = Elements(**elm_list)
print(hydrogen.name, hydrogen.symbol, hydrogen.number) |
b93a9c42e583e01813d5521acff4b1cbc91ead5c | anatshk/SheCodes | /Exercises/lecture_8/lecture_8_ex1.py | 5,795 | 4.3125 | 4 | # Question 6: In sum...
def sum_(n):
"""Computes the sum of all integers between 1 and n, inclusive.
Assume n is positive.
"""
if n == 0:
return 0
return n + sum_(n - 1)
# print(sum_(1)) # 1
# print(sum_(5)) # 15
# Question 7: Misconceptions
def sum_every_other_number(n):
"""Retu... |
f66150d36c94db6ef61e8190d74b28eec042da1f | marciniakmichal1989/PythonTraining | /Mix-master/Nauka/Nauka/Front End/calculator.py | 2,044 | 3.828125 | 4 | from tkinter import *
root = Tk()
root.title("Calculator")
entry_box = Entry(root, width=35, borderwidth=5)
entry_box.grid(row=0, column=0, columnspan=3, padx= 10, pady= 10)
#-------------------------------------------
def button_click(number):
current = entry_box.get()
entry_box.delete(0, END)
entry_b... |
e0101539e3f43e778a32e67ede5f2fad7e25b322 | RogerioLS/HackerRank | /AvaliacaoParaPythonBasico/provaDoisBasico.py | 1,327 | 3.890625 | 4 | import math
import os
import random
import re
import sys
class Rectangle:
def __init__ (self, width, length):
self.width = width
self.length = length
def area(self):
return 2*(self.length + self.width)
pass
"""length = float(input('enter length:'))
width = float(input('... |
0ef99b13d515c26cf74089688ee5ea81873110ed | nshefeek/work | /snippets/sentence.py | 676 | 3.71875 | 4 | class Sentence:
def __init__(self, line):
self.line = line
self.pos = 0
self.words = self.line.split()
def __iter__(self):
return self
def __next__(self):
if self.pos >= len(self.words):
raise StopIteration
index = se... |
f37c911be55e150fd9a6dc60529cedbd767ae1e2 | aandr26/Learning_Python | /Pluralsight/Core_Python_Getting_Started/4_Introducing_Strings_Collections_and_Iteration/string_literals.py | 184 | 3.6875 | 4 | # Multiline strings
""" This is
a multiline
string"""
''' So
is
this. '''
m = 'This string\nspans multiple\nlines'
print(m)
k = 'A \\ in a string'
print(k)
s = 'parrot'
print(s[0])
|
a6989f43a875c69352bd5b004d9f2cad31a85314 | askdjango/snu-web-2016-09 | /class-20160928/report/박연준_에너지자원공학과/multiplication.py | 294 | 3.796875 | 4 | # 특정 수를 입력받아서, 구구단을 출력하는 프로그램을 작성
number = int(input("구구단 숫자를 입력하시오.\n"))
print("\n{} 구구단\n".format(number))
for i in range(1, 10):
answer = number * i
print("{} x {} = {}".format(number, i, answer))
|
fb51e712cf83f0b2a96c8569f6975b333016b0a8 | RanChenSignIn/Numpy_Pandas_Seaborn | /Numpy/numpy_Netease_could/numpy_index.py | 626 | 3.875 | 4 | import numpy as np
A=np.arange(3,15)#生成3-14的数据
print(A)
print("A[0]",A[0])
print('取第四个元素:',A[3])#取第四个
A=np.arange(3,15,1).reshape(3,4)#重排为3*4矩阵
print(A)
A2=A[2,2]#取A,array中的第2行第2列的元素
print(A[2,2])#同上
print(A2)
print(A[2][2])#取A,array中的第2行第2列的元素
print(A[:2][:2])
A23=A[:,2]#第二列所有的数据
print(A23)
for row in A:#打印每一行
... |
7517f4a6a0079717894908445d0840d529cbf9d5 | QuickRecon/CascadeCalculator | /Cylinder.py | 1,218 | 3.71875 | 4 | class Cylinder:
_gasloss = 5 # Fudge factor for gas lost during the transfer due to whips and such
def __init__(self, volume, pressure, label, max_pressure):
self.volume = volume
self.pressure = pressure
self.label = label
self.max_pressure = max_pressure
def transfill(sel... |
4586160ecabbfbd3bdb13875f13638a22a50fd1d | Andyporras/portafolio1 | /portafolio1_parte 2.py | 3,792 | 4.34375 | 4 | """
nombre:
pasarAentero
entrada:
num=numero entero mayor que cero
salida:
numero entero
retrincciones:
numero mayor que cero con decimales
"""
def pasarAentero(num):
if(isinstance(num,float) and num>0):
#comprobacion de numero tipo flotante
return pasarAentero_aux(num)
else:
... |
3ac07c343d5a2908ab23efda5a4c85c14fde46ef | yabincui/topcoder | /dp/CustomerStatistics.py | 810 | 3.640625 | 4 | class CustomerStatistics:
class Node:
def __init__(self, name):
self.name = name
self.count = 1
def __lt__(self, other):
return self.name < other.name
def reportDuplicates(self, customerNames):
nodes = []
for name in ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.