blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
1fa61cfc52c3571bbc749803949ceef0ce1b3c9a | davidcg97/JuegoMedieval | /Medieval Game.py | 3,290 | 3.5 | 4 | import random
class Ciudadanos:
def __init__(self): # Constructor
Granjeros.__init__(self)
Artesanos.__init__(self)
Militares.__init__(self)
Taberneros.__init__(self)
Curas.__init__(self)
self.profesion = random.choice(profesion)
self.cantidad = cantidad
... |
62008b0cbfc79cdde766ba6d018826faf18f7765 | AkshayVaswani/PyCharmProjects | /1-28-19/exit slip.py | 408 | 3.75 | 4 | import turtle
import math
alex = turtle.Turtle()
wn = turtle.Screen()
wn.bgcolor("white")
alex.color("green")
alex.pensize(3)
size=20
def square(size):
for i in range(4):
alex.forward(size)
alex.left(90)
for i in range(5):
square(size)
alex.penup()
alex.right(135)
alex.forward(math.... |
52484a18d615e3a863a7ac4fe13f0f74a6340e4e | DaltonLarrington/Dalton-Larrington-Data-Structures | /Dalton Larrington DS Level 04 - Recursion/DS Level 04 Part B 2.py | 488 | 4.21875 | 4 | #Fibonacci Sequence Non-recursive
#Programmer: Dalton Larrington
#Date: 2-13-18
import time
startTime = time.time()
def fib(n):
x = 0
y = 1
#Will find the nth number in the range 0 to n adding z and y each time
for i in range(0, n):
z = x
x = y
y = z + y
return x
#... |
fd174d26829328977e106090f0ca4a3ccf2eab6b | samirsaravia/Python_101 | /Bootcamp_2020/AdvancedPython/Regular_expressions/basics.py | 1,286 | 3.625 | 4 | import re
#
# [aeiou] Match any vowel
# [^aeiou] ^ inverts selection, this matches any consonant
# [a-z] Match any lowercase letter from a-z
# \d Matches any decimal digit; this is equivalent to the class [0-9]
# \D Matches any non-digit character; this is equivalent to the class
# [^0-9]
# \s Matches any whitespace c... |
489b667d5b4be2277b5cfe1c3750e12aef8d5e1e | MashodRana/Computer-Vision | /contour_pixels/contour_pixels.py | 2,557 | 4.09375 | 4 | # Load necessary packages
import cv2
import numpy as np
import matplotlib.pyplot as plt
def preprocess_image(img):
"""
This method for preprocessing the image.
First convert the image into gray scale image then apply binary thresholding to get
better result on contour detection.
parame... |
20a815648421e020386fb49b4c027a29e9ce2807 | kimgeonsu/python_19s | /bingo_20193125.py | 2,076 | 3.703125 | 4 | # 5x5 빙고 게임
import random
board=[[' ' for x in range(1,6)] for y in range(5)]
n=1
for r in range(5) :
for c in range(5) :
board[r][c]=n
n += 1
numlist=[]
comlist=[]
bingo=0
#빙고판 만들기
while True :
for r in range(5) :
for c in range(5) :
print("{:>3}" .fo... |
b3dd985d5b21a6d0ec87831b370a8dc8c87d1b3f | devpla/algorithm | /BOJ/02579-계단_오르기-yeonhee.py | 348 | 3.5 | 4 | n = int(input())
stairs = [0] + [int(input()) for _ in range(n)]
dp = [0] * (n+1)
if n == 1:
print(stairs[1])
elif n == 2:
print(stairs[1] + stairs[2])
else:
dp[1] = stairs[1]
dp[2] = stairs[2] + stairs[1]
for i in range(3, n+1):
dp[i] = max(dp[i-2] + stairs[i], dp[i-3] + stairs[i] + sta... |
5fac13a7530eeae5ee5703e8ba992c294bc12d72 | sunset375/CodingDojo-1 | /Python/Python_Knowledge/algos/w4d3/main.py | 333 | 4.03125 | 4 | # 0, 1, 1, 2, 3, 5, 8
def fibonacci(num):
if num < 2:
return 0
if num == 2:
return 1
return fibonacci(num-2) + fibonacci(num-1)
fibonacci(5) # -> 3
def fibonacci(5):
if num < 2:
return 0
if num == 2:
return 1
return fibonacci(num-2) + fibonacci(num-1)
fibon... |
856bc5a4ba75f38de0b1a94c0b0ac1918268b917 | CYanLong/learn-python3 | /chapter9-example/feild.py | 278 | 3.671875 | 4 | class Counter:
count = 0 #类属性定义在外面.
def __init__(self): #实例属性定义在__init__方法中
self.__class__.count += 1
if __name__ == '__main__':
print(Counter.count) #0
c1 = Counter()
print(Counter.count) #1
c2 = Counter()
print(Counter.count) #2 |
a6a2d369ddccdb3fc6c0c247db86fa0a93db32e5 | vsivakumar9/Python-general | /PyParagraph/main_pypara1.py | 3,558 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 19 13:18:49 2018
@author: Shiva
"""
#Program reads thru a text file to obtain statistics like approx word count,
#sentence count, average letter count per word, average sentence length etc.
import os
import re
#filepath = os.path.join("raw_data","paragraph_1.txt")
#o... |
bd15c8f22ccf30cef979007d3e2af8a12ba2ecae | gerrycfchang/leetcode-python | /easy/judge_route_circle.py | 1,516 | 4.15625 | 4 | # 657. Judge Route Circle
#
# Initially, there is a Robot at position (0, 0).
# Given a sequence of its moves, judge if this robot makes a circle,
# which means it moves back to the original place.
#
# The move sequence is represented by a string. And each move is represent by a character.
# The valid robot moves ... |
6bfc6cf501fb828f1cdbf0f3d21e91b8ad53078a | OZ-T/PythonDesignPatterns | /decorator/decorator_tree_class.py | 2,687 | 4 | 4 | """
A working, clean Binary Search Tree class in Python.
The Binary Search Tree data structure maintains the following invariants:
1. For any node to the left of a given point in the tree, such node has a value smaller than the given point.
2. For any node to the right of a given point in the tree, such node has a... |
84417f4b8612b779717fcec448a81d396be3cfc1 | 26barnwal11/Algorithms-1 | /Sorting/Quick Sort/QuickSort.py | 753 | 3.921875 | 4 |
import array
"""" Quick Sort implementation as done in CLRS """
def quicksort(arr,first,last):
if first<last:
middle = partition(arr,first,last)
quicksort(arr,first,middle-1)
quicksort(arr,middle+1,last)
def partition(arr,first,last):
""" Taking last element as Pivot """
pivot =... |
45985142e570b097fab134d1245a0f05e27f6058 | scarvalhojr/programming | /leetcode/3sum-closest/solution_b.py | 1,136 | 3.5625 | 4 | #!/usr/bin/env python
from bisect import bisect_left
from sys import maxint
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
closest_sum = None
closest_dist = maxint
length... |
0a34d061fc47755236f5790a4fa7c62e781b4a3d | paumih/handwriting-characters-extraction | /handwriting_char_extraction.py | 4,695 | 3.71875 | 4 | import os
from cv2 import cv2
import numpy as np
import math
def rotate_image(image, angle):
"""
Rotates the given image by the input angle in the counter-clockwise direction
Parameters
----------
image : ndim np.array
image to be rotated
angle : floa... |
02e1c54278a092333d77aa76221a6223e37a6e6e | abhishekdwibedy-2002/Spectrum_Internship_Task | /prgm1.py | 803 | 4.65625 | 5 | # Python3 program to Convert characters of a string to opposite case
# Function
def case_converter(string):
length = len(string)
for i in range(length):
# Checks for lower case character
if string[i] >= 'a' and string[i] <= 'z':
# Convert it into Upper case
... |
f35ad76356e42fab906bb790aa36252d74555e35 | Man0j-kumar/python | /remove 3rd.py | 247 | 3.671875 | 4 | def removethird(int_list):
pos=2
idx=0
len_list=(len(int_list))
while len_list>0:
idx=(pos+idx)%len_list
print(int_list.pop(idx))
len_list-=1
nums=[int(x) for x in input().split()]
removethird(nums) |
bf164acce47738ecce1a629b7fea65721fa65c69 | Devrother/algorithm-exercises | /Dovlet/3stair-rendezvous/seunguklee/solution.py | 120 | 3.53125 | 4 | a, b = map(int, input().split())
def gcd(x, y):
return x if y == 0 else gcd(y, x % y)
print((a + b) // gcd(a, b))
|
07cca0cb8b55a1f4e970a1851ce04134e9dc9c8b | nosbod18/Alien-Crash | /choose_path_2.py | 10,077 | 3.6875 | 4 | # 2/10/20
# Evan Dobson
# Project: Alien crash
# Module: choose_path_2
import time
import random
import variables as var
def choose_path2(): # defines a function to allow the player to choose a path
is_helecopter = random.randint(1,2) # sets a random number (1 or 2) to is_helecopter
if is_helecopter == 1: # ... |
0f6d7266af4a384ce3eacf12090e7aa274693404 | dwitka/tsp_solver | /tspturtle.py | 1,696 | 4.03125 | 4 | import turtle
f = 16
def draw(L):
"""(list of tuples-->None)
Draws a line from one set of coordinates to the next
until all coordinates have been connected and then
returns to starting points."""
turtle.speed(10)
length = L.__len__() - 1
for item in L:
turtle.penup()
turtle.... |
10a804ead02715ddc9b9bf2a530ede3237d0db93 | dev-danilosilva/integer-arithmetic-expression-evaluator | /interpreter.py | 7,586 | 3.5 | 4 | '''
expr : term ((PLUS | MINUS) term)*
term : factor ((MUL | DIV) factor)*
factor : (PLUS | MINUS) factor | INTEGER | LPAREN expr RPAREN
'''
from enum import Enum
from typing import Any
# ==== Lexical Analyzer ====
class TokenType(Enum):
START = 0
INTEGER = 1
PLUS = 2
MINUS = 3
... |
1276b131313f780195fd5c61746f58ab19f2b3a4 | rashmitallam/PythonBasics | /count_upper_lower_case_dict.py | 1,527 | 4.03125 | 4 | #WAP to accept a sentence which contains upper and lower case characters, return a dict containing count of total no. of upper and lower case chars
def CountUpperLowerDict(s1):
res=dict()
u_count=l_count=0
for ch in s1:
if ch != ' ':
if ch.isupper():
if res.g... |
fd01d7fd0b173fa5ea4509bb192f7db03c0069b0 | xhuang68/XHSimpleProjects | /sort_algorithm_python/merge_sort.py | 622 | 3.984375 | 4 | __author__ = 'xiaohuang'
def merge_sort(array):
if len(array) <= 1:
return array
mid = len(array) / 2
left = merge_sort(array[:mid])
right = merge_sort(array[mid:])
return merge(left, right)
def merge(left, right):
result = []
while len(left) > 0 and len(right) > 0:
if le... |
9b63be2473b73ea213cb074558ec54e6c1c7b4d7 | sumanthmadupu/MyPython | /guessing_game.py | 495 | 3.96875 | 4 | #guessing game
import random
comp_num = random.randint(1,9)
usr_inp = input("Guess a number between [1,9] : ")
attempt = 1
while(1):
try:
if comp_num > int(usr_inp):
print("Go higher")
elif comp_num < int(usr_inp):
print("Go lower")
else:
print("Awesome.You got it in "+str(attempt)+" times")
break
... |
ac3e2eadd27227b2748fe342b474060054217f7c | PFSDevTeam/kaffeeklatsch | /kaffeeklatsch/forms/RegistrationForm.py | 1,238 | 3.515625 | 4 |
#File: RegistrationForm.py
#@author: Ryan Dombek, Geoff Floding, David Hovey
#Description: this file contains the form to register the user
# based on given credentials
# Imports
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField
from wtforms.validators import DataRequired, ... |
4a73f8d597120103b06ed2489eb6fc1c0f115022 | badbit/int-python | /pira.py | 465 | 4.28125 | 4 | #progama para hacer una piramide
def piramide (escalon):
numero= 1
estrellitas= 1
espacio= escalon
while numero<=escalon:
print("%s%s" %(espacio*" ", estrellitas *"*"))
espacio=espacio-1
estrellitas=estrellitas+2
numero=numero+1
print("\esta es... |
b8a1fafb5ba4161f22cb0505fa7fd558b87478f1 | jjpikoov/university | /python/1/1.py | 2,861 | 4.0625 | 4 | #!/usr/bin/env python
from sys import argv
from random import randint
def roll_dice():
"""Function returns random number from 1 to 6"""
return randint(1, 6)
def game(number_of_matches):
"""Game"""
player1_won_games = 0
player2_won_games = 0
for match in range(number_of_matches):
prin... |
a702c65c643f8623c8c474e7455888df0a5d4de3 | MajidSalimi/Python-Learning | /WorkingWithFiles/Files.py | 260 | 3.921875 | 4 | #Opens a read-only File
f=open('MyFile.txt','r')
#Reads file's content
file_content=f.read();
#closes the file
f.close()
#opens or creates a writable files
f2=open('a_file.txt','w')
#writes in the file
f2.write("This is my first program with files")
f2.close() |
eb8939664c8d052a0bafe2a89a030571b86cd71f | meloLeeAnthony/PythonLearn | /05-object面向对象/01类和对象.py | 1,072 | 4.15625 | 4 | """
Created on 2018年10月10日
@author: Administrator
"""
# <class '__main__.Dog'>
class Dog(object):
"""
面向对象的对象
"""
@staticmethod
def run():
"""
面向对象的方法
"""
print("running")
# init不是构造器,只是完成对象的初始化操作,默认调用,可以在创建对象的时候写成参数
def __init__(self, name, age):
... |
827b61898c325f8c827bd68ed0cb86b1c65ec635 | repsac/invert_binary_tree | /_unittest.py | 580 | 3.703125 | 4 | import invert_binary_tree
TREE_A = tuple(range(1, 8))
TREE_A_INVERT = (1, 3, 2, 7, 6, 5, 4)
TREE_B = tuple(range(1, 32))
TREE_B_INVERT = tuple([1, 3, 2] + list(reversed(range(4, 8)))
+ list(reversed(range(8, 16)))
+ list(reversed(range(16, 32))))
def run_tests():
assert invert_... |
fa0a903dff422680f6a2244283c2f6358be3c874 | enterpriseih/Python100days | /day01_15/day11/file3.py | 541 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 写文本文件
# 将100以内的素数写入到文件中
# @Date : 2019-07-14 16:13:22
# @Author : yaolh (yaolihui129@sina.com)
# @Link : https://github.com/yaolihui129
# @Version : 0.1
from math import sqrt
def is_prime(n):
for factor in range(2,int(sqrt(n)) + 1):
if n % factor == 0:
retu... |
9b13d87c9f8236d26e9c238155a260d63272588b | deepcpatel/data_structures_and_algorithms | /Graph/number_of_islands_II.py | 3,740 | 4 | 4 | # Link: https://www.lintcode.com/problem/number-of-islands-ii/
# Approach: Every new land block can create three possibilities. If it is isolated (no neighbouring land), then it creates new island. If it has one surrounding island, then it can extend that island
# or else if there are detached surrounding island, then... |
8e598c4f1898bce19e8776d5f0c580fa3ae108d6 | RensOliemans/dmx-hackathon | /color.py | 1,267 | 4.03125 | 4 | """
Module containing the Color class
"""
class Color:
"""Color object, having r, g, b, and a to_hex method."""
r = 0
g = 0
b = 0
def __init__(self, r, g, b):
self.r = r or 0
self.g = g or 0
self.b = b or 0
def to_hex(self):
"""Converts this object to a hex repr... |
6fa8dd08d37c74094bc74373aa88078fba4e9160 | AxelRaze/Subsecuencia | /Subsecuencia.py | 1,010 | 3.578125 | 4 | class Subsecuencia:
maximo = 0
datosSecuenMax = []
def _lis(self,arr, n):
# caso base _punto_quiebre
if n == 1:
return 1
maxFinalizaado = 1
for i in range(1, n):
res = self._lis(arr, i)
if arr[i - 1] < arr[n - 1] and res + 1 ... |
6e6bccda0b771bb7f3c16e14a937687b7ed0aeea | Jimut123/code-backup | /python/python_new/Python 3/elif.py | 213 | 4.40625 | 4 | #Program checks if the number is positive or negative# And displays an appropriate message
num=3.4
#num=0
#num=-4.5
if num>=0:
print("Positive number")
elif num==0:
print("Zero")
else:
print("Negative number")
|
e0cb9722eb6a70891511a09b4afe531d0b2bde28 | arozrai/removeFiles-project99 | /RemoveFiles.py | 1,926 | 3.8125 | 4 | import time
import os
import shutil
def main():
path = input("Which folder will you want to apply this program on? ")
days = int(input("Delete files over what days old: "))
seconds = time.time() - (days * 24 * 60 * 60)
print(seconds)
pathExists = os.path.exists(path)
deletedFoldersCount = 0... |
d9c7fe58b3b09ffd0e45e640ed83fd532afbd176 | WustAnt/Python-Algorithm | /Chapter5/5.2/5.2.2/5-4.py | 553 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/8/21 17:14
# @Author : WuatAnt
# @File : 5-4.py
# @Project : Python数据结构与算法分析
def binarySearch(list,item):
'有序列表的二分搜索递归版本'
if len(list) == 0:
return False
else:
midpoint = len(list) // 2
if list[midpoint] == item:
return True
... |
1a708735606c875b34212081359558e198b5aa5b | dinobobo/Leetcode | /702_search_sorted_array_unknown_size.py | 730 | 3.8125 | 4 | # Find boundary and binary search
class Solution:
def search(self, reader, target):
"""
:type reader: ArrayReader
:type target: int
:rtype: int
"""
# Binary search
def binary_search(l, r):
while l <= r:
mid = l + (r - l)//2
... |
3dfd5cdcda7b93d4e7c065a437789942b8eb9567 | tipdaddy78/keep_quiet_defusal | /modules/wire_sequence.py | 1,358 | 4 | 4 | red = [" ", "c", "b", "a", "ac", "b", "ac", "abc", "ab", "b"]
blue = [" ", "b", "ac", "b", "a", "b", "bc", "c", "ac", "a"]
black = [" ", "abc", "ac", "b", "ac", "b", "bc", "ab", "c", "c"]
def solve_wire_sequence():
print("WIRE SEQUENCE MODULE - START")
red_count = 0
blue_count = 0
black_count = 0
... |
a88d22d984b206d0ce70750336faa5766315882a | brunnaarruda/lab2018.2 | /navio.py | 2,008 | 3.578125 | 4 | class Campo:
def __init__(self):
self.navio = [] # é uma lista de lists == matriz
def lerCampo(self, l, i, j, b = False):
achou = b
if l[i][j] != '#':
return
else:
if achou == False: #comeca com falso e muda pra vdd pq achou o navio
achou ... |
80a1862d15c253316ecd1d91bdfadca6c452b332 | cognitiaclaeves/sphinx-autodoc-example | /src/silly_module.py | 774 | 3.71875 | 4 | # coding: utf-8
import pandas as pd
class PandasInput():
"""Class responsible for dealing with input pandas objects
(docstring written using Google style)
Attributes:
csv_file (str): filename of the csv file
"""
def __init__(self, csv_file):
self.csv_file = csv_file
def load... |
a97d81a99ae5b4d90ae5eb9e133e8e603dba8ceb | Jirada01/Python | /test2 5_2.py | 462 | 3.53125 | 4 | list_name = [มาม่า,ลาบ,ส้มตำ,ข้าวแกง]
list_price = [12,60,40,25]
class shoplist :
def show_shoplist (self):
print ("แสดงรายการสินค้า [a]\n","เพิ่มรายการสินค้า [s] \n","ออกจากระบบ [x]\n")
def show() :
for x in range(0,len(list_name)) :
def input_list() :
x = shoplist()
x... |
f8826f8d5268b9150bbf9cf3828898015c024c2a | misterwhybe/dataprocessing | /Homework/Week_1/visualizer.py | 1,185 | 3.953125 | 4 | #!/usr/bin/env python
# Name: wiebe jelsma
# Student number: 12468223
"""
This script visualizes data obtained from a .csv file
"""
import csv
import matplotlib.pyplot as plt
from statistics import mean
def visualize():
INPUT_CSV = "movies.csv"
START = 2008
END = 2018
# dictionary for t... |
1710ac1d81c4665706a2a79691acd5cfdb627224 | AolDunedein/BioLab | /run.py | 998 | 3.578125 | 4 | import fetch_sequence
import blasting
import dict_csv_gene
# FERRAMENTA CRIADA EM CONJUNÇÃO PELOS GRUPOS 13 e 9
# fetch_sequence
while True:
inp = input("Insira o seu grupo: ")
g=9
try:
g = int(inp)
if g<0 or g>13:
raise ValueError("Not Valid")
except Exception:
pri... |
bf6a6485023d46693ee45973be858af11fd5e780 | nidhi2509/Mini-Python-Projects | /gradient-2.py | 1,389 | 3.78125 | 4 |
import image
def copy_image(img):
'''
Creates a copy of an image by iterating over the height and width and copying
each pixel to a new image.
Preconditions:
img is an image object
Postconditions:
return a copy of that image object
'''
assert isinstance(img, image.Image)... |
8e40514dbad21219feb29d65a558c0ace8e4be35 | dongyueqian/pythonspider | /05_thread_process.py | 334 | 3.78125 | 4 | import math
def fn(n):
if n<2:
return False
if n==2:
return True
if n % 2 == 0:
return False
sq = int(math.floor(math.sqrt(n)))
for i in range(3,sq+1,1):
print(i,'------')
a = n % i
print(a)
# return sq
print(fn(27))
# for i in range(3,4,2):
# ... |
4ac13cbe272d8ed915e0bc275a03603d1ee11265 | tlee0058/python_basic | /compare_lists.py | 1,690 | 4.59375 | 5 | # # Assignment: Type List
# # Write a program that takes a list and prints a message for each element in the list, based on that element's data type.
# # Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a num... |
af7178afda5d5a2b40081c43ffcf0df33e69b979 | BigNianNGS/AI | /python_base/exercise.py | 2,683 | 3.75 | 4 | '''
第一题:利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示
'''
# ~ while(1):
# ~ score = input('请输入成绩(q for quit):')
# ~ if score == 'q' or score == 'quit':
# ~ break
# ~ score_int = float(score)
# ~ if(score_int >= 90):
# ~ print('A')
# ~ elif(score_int >= 60):
# ~ print('B')
# ~ else:
# ~ print(... |
426b5525fe953b527e13b92f54dec102f545f90d | mneary1/csmatters | /Unit1/inputCheckingStudent.py | 3,570 | 4.40625 | 4 | #This file's purpose is to practice checking inputs and using operators such
#as loops and if statements.
def main():
#Print out welcome
print("Hello there! \n This program will take a number and run it through")
print(" a series of tests.")
#Use getValidInput to get a number
number = getValidInp... |
34a36764e1ff6f2dcc120b020b71706033d0e198 | Jaredcscott/Project-Euler | /src/python/prob14.py | 1,028 | 4.03125 | 4 | def even(num):
return num/2
def odd(num):
return (3 * num) + 1
num = 1
longestChain = 0
while num < 1000000:
chain = []
curNum = num
while curNum != 1:
if curNum % 2 == 0:
chain.append(curNum)
curNum = even(curNum)
chain.append(curNum)
... |
50c802ca6a97315598e63c67f71f37d482c22274 | oshsage/Python_Pandas | /py4e/CodeUp/1063_Ternary.py | 514 | 3.75 | 4 | # 입력된 두 정수 a, b 중 큰 값을 출력하는 프로그램을 작성해보자.
# 단, 조건문을 사용하지 않고 3항 연산자 ? 를 사용한다.
a, b = input().split(' ')
c = int(a)
d = int(b)
print(c) if c>=d else print(d)
# 새로 알게 된 것: 파이썬은 삼항연산자를 지원하지 않는다.
# [true_value] if [condition] else [false_value] // 파이썬 지원
# if문과 비슷할 수 있겠으나 뒤에 계속 이어붙이는 것이 특징이다.
# ex) bb = 1 if aa == 0 else aa |
9e4a9ba5a5858a854db5795d7ad9fed19c5860e1 | 2morrow-py/Learning-Python | /Seção 6 - Estruturas de Repetição em Python/loop_while.py | 738 | 3.984375 | 4 | """
Loop while
Forma geral
while expressão_booleana:
//execuão do loop
O bloco do while será repetido enquanto a expressão booleana for verdadeira.
Expressão Booleana é toda expressão onde o resultado é verdadeiro ou falso.
Exemplo:
num = 5
num < 5
# Exemplo 1
numero = 1
while numero... |
4ba3600eed38439df459e71a27012fa9786bbe99 | cagataybalikci/Python-Password-Generator-App | /main.py | 4,124 | 3.546875 | 4 | from tkinter import messagebox
from tkinter import *
import password_generator
import pyperclip
import json
# CONSTANTS
DARK = "#383e56"
ORANGE = "#fb743e"
# PASS WORD GENERATOR
def generate_password():
gen_password = password_generator.random_password()
password_input.insert(0, gen_password)
pyperclip.... |
fa6a894756b9c81d019dc11c774ddbed82ae24a1 | wechuli/python | /decorators/exercises/ex6_test.py | 694 | 3.890625 | 4 | # Write a function called delay which accepts a time and returns an inner function that accepts a function.When used as a decorator, delay will wait to execute the function being decorated by the amount of time passed into it. Defore starting the timer, delay will also print a message informaing the user that there wil... |
ed2327f14695f1bad68b1db7da44dce0fcf1b5e8 | leandrotominay/pythonaprendizado | /aula07/mediaAluno.py | 332 | 4 | 4 | import math
#Desenvolva um programa que leia as duas notas de um aluno, calcula e mostre a sua média
print("**PROGRAMA QUE LE NOTAS E FAZ A MEDIA**")
nota1 = float(input('Digite a primeira nota: '))
nota2 = float(input('Digite a primeira nota: '))
media = (nota1 + nota2) / 2
print("A media do aluno é igual a {}".forma... |
3861c887e367c4c50f2d600d96a984801b85e80b | bhumish/project-euler | /85.py | 327 | 3.5 | 4 | #!/usr/bin/env python
import math
def squares(row,col):
return row* (row+1) * col * (col+1) / 4
topl = 2000000
dist = 2000000
for r in range(1,100):
for c in range(1,100):
temp = squares(r,c)
d = int(math.fabs(topl-temp))
if d<dist:
answer = (r,c)
dist = d
print dist, answer
print "area", answer[0]*ans... |
a969fcec83e35191f18eef942a900e1dfa39ced7 | Parth-Shah-Tool-Kit/complete-python-tutorial | /part3/exercise5.py | 299 | 4.21875 | 4 | '''
Input a name from the user
and then input argument to be searched
print the number of times the argument was present
'''
name = input("Enter your name: ")
arg = input("Enter query to be searched: ")
count = name.count(arg)
print(f"The query {arg} was present {str(count)} times")
|
297874250282427cbf99ae3a7e316205b1f7d23d | bopopescu/education | /chapter 1_begins/enterpret.py | 551 | 3.53125 | 4 | from datetime import datetime
import random
import time
odds = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59]
#последовательный вывод с каждой строки
#for i in "123":
#повторение количество раз
for i in range(3):
right_this_minute =datetime.today().minute
if right_this... |
5ae52df265ac9cf088b9873b426ba305967d4ecb | osamadel/Python-Online-Courses | /Misc_TestCode/problem_set_1-3.py | 1,240 | 4.09375 | 4 | """
Description :
A program to calculate the credit card balance after one year if a person only pays the minimum monthly payment
required by the credit card company each month.
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
monthlyPaymentRate - minimum mont... |
c17f760d7e87f15da9f00fb9528b8369006ce650 | EdwardJPeng94/Personal-Projects | /Connect Four Draft.py | 11,716 | 3.71875 | 4 | from tkinter import *
import tkinter.messagebox
root = Tk()
root.title('Connect Four')
#------------------------------------variables--------------------------------##
count = 0
moves_o = []
moves_x = []
placement_0 = 6
placement_1 = 6
placement_2 = 6
placement_3 = 6
placement_4 = 6
placement_5 = 6
placement_6 = 6
#... |
21cfa43f700c71ada3697a3c8524a4711ce2a3e1 | naddleman/aoc2018 | /day06-chronal.py | 2,656 | 3.65625 | 4 | """
https://adventofcode.com/2018/day/6
given a list of points
find the area of the largest finite set of coordinates closest to some point
Theorem: The area V(p) is infinite if p is on the boundary of the convex hull
"""
import numpy as np
TEST_INPUT = """1, 1
1, 6
8, 3
3, 4
5, 5
8, 9"""
def from_coord(coord: str)... |
77b561320c697c35aea4afb3461f80a4ac40a82e | lastz/lastz | /tools.python2/maf_sort.py | 4,401 | 3.515625 | 4 | #!/usr/bin/env python
"""
Sort alignment blocks in a maf file, according to the user's choice of key
--------------------------------------------------------------------------
:Author: Bob Harris (rsharris@bx.psu.edu)
"""
import sys,re
validKeys = ["score","pos1","pos2","beg1","beg2","end1","end2","diag","name1","na... |
59ed88c230cb05f940deef27643a942f4b7952c2 | LiudaShevliuk/python | /lab4_1.py | 256 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
a = float(input('Enter positive number: '))
b = float(input('Enter one more positive number that greater than 0: '))
x = math.sqrt(a * b) / (math.exp(a) * b) + a* math.exp(2 * a / b)
print(x)
|
f0902857df6d09d947b2f22f82f21cfaac4f61cb | SLEDAssessment/shop | /shop.py | 969 | 3.8125 | 4 | from stock import Stock
print (" M A I N - M E N U")
print ("1. Create Customer")
print ("2. View Customers")
print ("3. Action 3")
print ("4. Action 4")
print ("5. Action 5")
while True:
# Get user input:
choice = input('Enter a choice from the menu [1-5] : ')
# Convert input (number) to ... |
8366cc24b51dd932638772dce320e2c2e0ff0dbb | KumarLokesh15/Model-Deployment | /salary.py | 514 | 3.5625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
def salary_exp_pred(exp):
df = pd.read_csv('Salary_Data-1.csv')
x = df.iloc[:,0]
y = df.iloc[:,1]
x = x.values
y = y.values
model = LinearRegression()
... |
b4013fda23af65683ac8e99c2817badf559cb5c4 | Hugomguima/FEUP | /1st_Year/1st_Semestre/Mnum/Exame/Exame 2014/Pergunta7.py | 257 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 10 16:25:25 2020
@author: Hugo
"""
f = lambda x : x**4-4*x**3+x-3
g = lambda x : (4*x**3-x+3)**(1/4)
def picard(x):
for i in range(3):
print(x)
x = g(x)
picard(3.5) |
7ed232a59607d87aceecc6ad8f8b95278e01a8ca | RyanIsBored/unit-3 | /squares.py | 115 | 3.78125 | 4 | #Ryan Jones
#2/26/18
#squares.py
num = int(input('Enter a number: '))
for i in range(0,(num)):
print((i+1)*(i+1)) |
dc1c456f30dd01d71a3f18e1f05f64ea95b9e1d0 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/59/tables.py | 1,336 | 4.0625 | 4 | #
# c_ MultiplicationTable
#
# ___ - length
# """Create a 2D self._table of (x, y) coordinates and
# their calculations (form of caching)"""
# _length ?
# _table # list
# ___ i __ r.. 1 ? +1
# row # list
# ?.a.. ?
#
# j 1
# ... |
892a5ed8857652a2a54ab6a17b6dc8f689147717 | privateOmega/coding101 | /clap/nth-fibanocci.py | 609 | 3.78125 | 4 | def fibanocci_doubling(number):
if number == 0:
return (0, 1)
else:
a, b = fibanocci_doubling(number >> 1)
c = a * ((b << 1) - a)
d = a * a + b * b
if number & 1:
return (d, c + d)
else:
return (c, d)
def main():
noOfTestCases = int(i... |
fddd856d0b857bcc47902377158e82bd145c5d1c | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/dsrkir001/util.py | 1,505 | 3.625 | 4 |
#A module of utility functions to manipulate 2-dimensional arrays
#27 April 2014
#Kiran Desraj
#import function to be used when copying the grid
import copy
#create a 4x4 grid :
def create_grid(grid):
for i in range (4):
grid.append ([0]*4)
return grid
#print out a 4x4 grid in 5-width columns ... |
26c8497323e31c5e4453258b6c7dbd498bb5e9f5 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_116/940.py | 1,605 | 3.71875 | 4 | def checkline(line):
if (line[0]=='X' or line[0]=='T') and (line[1]=='X' or line[1]=='T') \
and (line[2]=='X' or line[2]=='T') and (line[3]=='X' or line[3]=='T'):
return 'X won'
if (line[0]=='O' or line[0]=='T') and (line[1]=='O' or line[1]=='T') \
and (line[2]=='O' or line[2]=='T') a... |
eb718a6b30964893f08aa2eaa03f828ecfcf312b | 353solutions/353bytes | /ml/bool-index/snail.py | 520 | 3.625 | 4 | """
Draw a green (color=[0, 0xFF, 0]) square on the snail image
- line width=5
- top left: (217, 42)
- bottom right: (525, 275)
"""
import matplotlib.pyplot as plt
img = plt.imread('snail.jpg').copy()
plt.imshow(img)
tl_x, tl_y = 217, 42 # x = row, y = column
br_x, br_y = 525, 275
width = 5
color = [0, 0xFF, ... |
712a7429a3f821993e2bdf298d0ba206c52df8ab | 0verlo/python_playground | /sumtest.py | 232 | 3.953125 | 4 | #!/usr/bin/env python
# coding=utf-8
def calc_sum(*numbers):
sum = 0
for value in numbers:
sum = sum + value
return sum
sum = 0
for x in list(range(11)):
sum = sum + x
print(sum)
print(calc_sum(1,2,3,4,5))
|
0499a60f0aa47df52aae2c12e8981dfbcaa9a24c | Urobs/daily-coding-problem | /problem12/index.py | 260 | 3.609375 | 4 | def count_unique_climb_ways(distance, steps):
count = 0
for step in steps:
if distance - step == 0:
count += 1
elif distance - step > 0:
count += count_unique_climb_ways(distance - step, steps)
return count |
a7a99791590c5172ddc0db67bccac7ebe495cd12 | phamd1989/Algorithms | /Inversions.py | 1,183 | 3.5625 | 4 | import sys
def inversionList(arr):
size = len(arr)
if (size == 1):
return arr
low_arr = arr[0:size/2]
high_arr = arr[size/2:size]
return mergeAndCount(inversionList(low_arr), inversionList(high_arr))
def mergeAndCount(low_arr, high_arr):
global count
combined_arr = []
l = len(... |
ec560397c393da2d8edef59287b535d1327e2879 | herbertguoqi/drivercommend | /logic/recommend.py | 769 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#抽象类加抽象方法就等于面向对象编程中的接口
from abc import ABCMeta,abstractmethod
class recommend(object):
__metaclass__ = ABCMeta #指定这是一个抽象类
@abstractmethod #抽象方法
def Lee(self):
pass
def Marlon(self):
pass
class recommendImplDB(recommend):
def __init... |
fbb45074da49dea11e3d77b207797cbc960e2fdc | CHALASS770/WOG | /live.py | 3,069 | 3.953125 | 4 | from GuessGame import *
from time import sleep
from MemoryGame import *
from CurrencyRouletteGame import *
def welcome(name):
print("Hello %s ! Welcome in World of Game!!! "% name)
print("Here you can find many cool games to play ")
def load_game():
valideplay = True
while valideplay == True:... |
0b5e933e23d5226d910ea953eda6009c01e4c1fd | m-baez/platzi-retos_semana3 | /reto1.py | 386 | 3.84375 | 4 | # Reto #1 Longitud del string
"""Pide a tu usuario que ingrese el nombre de su curso favorito, obtén la longitud de ese string y muéstralo en pantalla."""
def main():
print('-'*60)
curse = str(input('Ingresa el nombre de tu curso favorito: ').__len__())
print('\nEsta es la longitud de caracteres: %s' % c... |
cd13a24b5b3a31f7c138bea9ed2b5ac08e4cb9cd | jlc175/For_Offer-Python3 | /数据结构/数组/3.数组中重复的数字/题目一/FindDuplicateEdit.py | 965 | 3.734375 | 4 | def duplicate(nums):
# 判断是否输入了[0,n-1]以外的数字
for num in nums:
if num < 0 or num > len(nums) - 1:
return False
# 从头遍历数组
for i in range(len(nums)):
# 当前位置的数字不在它应该的位置
while nums[i] != i:
# 如果当前位置的数字与它应该在的位置的数字相同,则找到了一对相同的数字
if nums[i] == nums[nums[i... |
731387ce57aabc297c84fecec52234b9e1fe2829 | TonyHoanTrinh/MathVisualizations | /fractalsimaging/fractalsimaging.py | 2,762 | 4.0625 | 4 | '''
Import the libarires to get access to mathematical functions and imaging
'''
import numpy
from numba import jit
import matplotlib.pyplot as plt
'''
The Mandelbrot Set:
For us define this as the set of complex numbers c such that when c are equated into the formula fc = z^2 + c, the formula was not
diverge pass a... |
a503d5c05d9af595b921725f90caf0644870acbc | DavidWellsTheDeveloper/DailyCodingChallenge | /Problem #28 [Medium].py | 2,123 | 4.125 | 4 | # Good morning! Here's your coding interview problem for today.
# This problem was asked by Palantir.
# Write an algorithm to justify text. Given a sequence of words and an integer line
# length k, return a list of strings which represents each line, fully justified.
# More specifically, you should have as many words a... |
0c059e1437dbb659eb0fc8bdeeac9e5f299eaed8 | rrabit42/Python-Programming | /Python프로그래밍및실습/ch5-function/lab5-13.py | 223 | 4.0625 | 4 | def findMax(list) :
max = list[0]
for i in range (1, len(list)) :
if max < list[i] :
max = list[i]
return max
numbers = [5, 2, 9, 8, 1, 4, 7, 3, 6]
max = findMax(numbers)
print(max) |
5c65395313abe7d17b5328c12a52cff83d68aeec | daparthi001/python | /Module2/Commands9.py | 605 | 3.828125 | 4 |
# # cmp() - This method returns -1 if x < y, returns 0 if x == y and 1 if x > y
#
# print "cmp(80, 100) : ", cmp(80, 100)
# print "cmp(180, 100) : ", cmp(180, 100)
# print "cmp(100, 100) : ", cmp(100, 100)
# print "cmp(80, -100) : ", cmp(80, -100)
#
# #max()
# arr = [2,3,5,7,9,11]
# print "Max value :: %d"%max(arr)... |
c6c8d001b1bbaa2c044c178f08a8d9c6e408a1b9 | heliormarques/labprog2019.2 | /dijkstra.py | 1,435 | 3.578125 | 4 | inf = float("inf");
vetor = {};
vetor['a'] = {};
vetor['a']['b'] = 6;
vetor['a']['d'] = 1;
vetor['b'] = {}
vetor['b']['d'] = 2;
vetor['b']['e'] = 2;
vetor['b']['c'] = 5;
vetor['c'] = {};
vetor['c']['e'] = 5;
vetor['d'] = {};
vetor['d']['e'] = 1;
vetor['e'] = {};
def dijkstra(vetor, start, finish):
... |
368cd1abb302797f76e0f48536014543bae9aff6 | djanshuman/Algorithms-Data-Structures | /Python/Searching/Binary_Search_Recursive.py | 458 | 3.765625 | 4 | '''
Created on 02-Jun-2020
@author: dibyajyoti
'''
def Search(alist,element):
if(len(alist) ==0):
return False
else:
mid=len(alist)//2
if(alist[mid]==element):
return True
else:
if(element > alist[mid]):
return Search(alist[mid... |
68ca4adaae6f8a0830f83acded0c29b7970850ca | jmctsm/Udemy_2020_Complete_Python_BootCamp | /15_PDFs_and_Spreadsheets/00-Working-with-CSV-Files.py | 1,159 | 3.8125 | 4 | import csv
def line_break():
for x in range(0,25):
print("*", end="")
print("\n")
# Reading CSV Files
line_break()
data = open("example.csv", encoding="utf-8")
print(data)
# Encoding
line_break()
csv_data = csv.reader(data)
data_lines = list(csv_data)
print(data_lines)
print(data_lines[:3])
for line... |
c5260e1253d76b7f4253e499a2e0f274338018c9 | dawidgdanski/python-training | /learningpython/decorators/timerdeco1.py | 1,313 | 3.765625 | 4 | # File timerdeco1.py
# Caveat: range still differs - a list in 2.X, an iterable in 3.X
# Caveat: timer won't work on methods as coded (see quiz solution)
import sys
import time
force = list if sys.version_info[0] == 3 else (lambda X: X)
class timer:
def __init__(self, func):
self.func = func
sel... |
a6c86d695cf8bb25f3ebe3db7cb4f2917966816e | kdheepak/hawk-dove | /species.py | 3,832 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
r"""
Evolutionary game theory
The strategy of the Hawk (a fighter strategy) is to first display aggression, then escalate into a fight until he either wins or is injured.
The strategy of the Dove (fight avoider) is to first display aggression but if faced with major escal... |
0fb5c770b39584f088df120e9970f5e5e100bd15 | yogeshasok/Python_Assgn01 | /Yog_python/Ass_20.py | 202 | 3.578125 | 4 | limit = int(input("Enter the limit to generate Fibo series "))
li =[0,1]
a = 0
b = 1
c = 0
res=0
while(c<limit):
li.append(a+b)
res=a+b
print res
a = b
b = res
c = c+1
print li
|
2f3a453d8e8ccfc169e805029019d115b74ce716 | vyashole/learn | /05-inputs.py | 1,094 | 4.46875 | 4 | # User input can be taken from the console using the input()
user_name = input("Enter your name:")
print("Hello, " + user_name)
# note that input always comes in as string
# so id a use puts in 5 python gets "5"
# To convert your data types you can use casting
# int() - casts to an integer number from an integer liter... |
a77db03253de0c74ab66bc4c9827a1aff2ddf8fd | Andrea-Vigano/rnenv | /rnenv111/rn/rn.py | 48,194 | 3.796875 | 4 | """
RN 1.11 class module
Following the 'functional RN representation' protocol, based on the
dynamic representation of real numbers as a sequence of integers and operations that bind them.
Operations between numbers aren't new, they are normally performed by the language itself, but in the case of
mathematically repr... |
edb038a532a4abb86d24f3aa306391b5a993c976 | BetiaZ/FinalProject17 | /game1.py | 17,097 | 4.34375 | 4 | #introduction
print("""ISLAND ADVENTURE
~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~
YOU WAKE UP ON A DESERTED ISLAND. YOUR GOAL IS TO MAKE IT TO THE OTHER SIDE OF THE ISLAND,
WHERE THERE ARE SHIPS THAT CAN TAKE YOU HOME, IN THE SHORTEST AMOUNT OF TIME POSSIBLE.
GOOD LUCK (YOU'RE GONNA NEED IT).""")
#this c... |
b288148e339c4022224b898eb9a718d889593083 | KRyan07901/python-challenge | /PyBank/mainbank.py | 670 | 3.71875 | 4 | # First we'll import the os module
# This will allow us to create file paths across operating systems
import os
# Module for reading CSV files
import csv
with open('budget_data.csv') as file:
csv_reader_object = csv.reader(file)
# Use return number of lines method
csv_reader_object.line_num
# Count # of ... |
24c460d06a6fc2035d7983b3b71327d8e4e184cf | Jayas234/Project_fILES | /dbsevencode.py | 265 | 3.59375 | 4 | def even(s,n):
i=2
c=0
while(True):
if i%2==0:
print(i,end=" ")
c=c+1
if c==4:
break
i=i+1
s,n=map(int,input().split())
n1=even(s,n)
'''
s=2
n=4
output= 2 4 6 8 '''
|
efad42ddd8ac6f919a359134c7e7301dbedc6bb7 | DevinS73/notes | /twod_lists.py | 804 | 4.375 | 4 |
a=[[1,2,3],
[4,5,6]]
##One way to traverse a 2d list:
#for i in range(len(a)):
# for j in range(len(a[i])):
# print(a[i][j],end=' ')
# print()
##Another way to traverse a 2d list:
def print_2d_list(lst):
for row in lst:
for element in row:
print(element,end=' ')
print(... |
f6cbfb53a059265923d1f438904d704a9df8b822 | yash0024/AutomatedPuzzleSolving | /puzzle.py | 1,299 | 3.78125 | 4 | """
=== Module Description ===
This module contains the abstract Puzzle class.
DO NOT MODIFY ANYTHING IN THIS MODULE.
"""
from __future__ import annotations
from typing import List
class Puzzle:
""""
A full-information puzzle, which may be solved, unsolved,
or even unsolvable. This is an abstract class... |
84792bce9ddfd5deffd08c523a8d33289152693f | deepak00108/coding | /addition of complex | 928 | 3.796875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
#Write your code here
class comp :
def __init__(self,r,i):
self.r = r
self.i = i
def add(self,other) :
other.real2 = real2
other.img2 = img2
c = complex(self.r+other.re... |
cb9d299a055e334c6ccac1c69a199f8c0e1e5394 | GPython21/Gayane | /Lesson 3/Lesson3-Ex.1.py | 317 | 4.03125 | 4 | def check_palindrome_1(avtobuska):
reversed_avtobuska = avtobuska[::-1]
status = 1
if (avtobuska != reversed_avtobuska):
status = 0
return status
avtobuska = "fsdfdsf"
status= check_palindrome_1(avtobuska)
if(status == 1):
print("It is a palindrome ")
else:
print("Sorry! Try again")
|
1dad408bc798923b7b1f84375982d203ca1c8fb4 | yunnyang/Practice_Code | /medium/leetCode648.py | 625 | 3.5625 | 4 | # 648. Replace Words
import collections
class Solution:
def replaceWords(self, dict: List[str], sentence: str) -> str:
words = sentence.split(" ")
visited = collections.defaultdict()
for i in range(len(words)):
word = words[i]
if word in visited:
w... |
d9c3495132f3f935de1c46b188af433fd39bdc21 | bssrdf/pyleet | /K/KthMissingPositiveNumber.py | 1,958 | 3.828125 | 4 | '''
-Easy-
Given an array arr of positive integers sorted in a strictly increasing
order, and an integer k.
Find the kth positive integer that is missing from this array.
Example 1:
Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...].
The 5th missi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.