blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
f20f181d0c252f38d8fd6c38513bf6920b8a2685
JamieShin0201/python-basic
/15_list.py
918
4.03125
4
# 리스트 [] subway1 = 10 subway2 = 20 subway3 = 30 subways = [10, 20, 30] print(subways) subways = ["유재석", "조세호", "박명수"] print(subways) # 위치 확인 print(subways.index("조세호")) # 지하철 끝에 추가 subways.append("하하") print(subways) # 지하철 중간에 추가 subways.insert(1, "정형돈") print(subways) # 지하철에 있는 사람을 한 명씩 뒤에서 꺼냄 print(subways.pop...
1b1d85fd346147e1f1d7fffe68290fc5a062b7d8
rcarton/advent2020
/advent/days/day17.py
3,896
3.875
4
""" AOC Day 17 ~~~~~~~~~~ Multidimensional Conway! """ import itertools as its from typing import Dict, Generator, Iterator, List Pos = List[int] ACTIVE = "#" class World: """ Represents a conway world with a set number of dimensions. Only active cells are stored in the state. This class keeps t...
6b6452eb152ffbac5cf90b31724b5232501a3af2
rcarton/advent2020
/advent/days/day11.py
4,353
3.71875
4
from dataclasses import dataclass from enum import Enum from typing import Iterator, List, Optional class Cell(Enum): EMPTY = 0 OCCUPIED = 1 FLOOR = 2 @staticmethod def from_str(s: str): if s == ".": return Cell.FLOOR if s == "L": return Cell.EMPTY ...
6c17200acbda3c96b397ec552280806023a08c54
rcarton/advent2020
/advent/days/day07.py
3,649
3.5
4
import re from dataclasses import dataclass from functools import lru_cache from typing import Dict, Iterator, List, Tuple ParsedInput = List[Tuple[str, List[Tuple[int, str]]]] @dataclass class BagRule: color: str can_be_contained_by: List[str] must_contain: List[Tuple[int, str]] def first(puzzle_input...
0a2e545efc6f51758ee63cf3eb47e863751e6888
rcarton/advent2020
/advent/days/day10.py
2,034
3.84375
4
from typing import Iterator, List def first(puzzle_input: Iterator[str]) -> int: counts = find_jolt_diff_counts(int(n.strip()) for n in puzzle_input) return counts[0] * counts[2] def second(puzzle_input: Iterator[str]) -> int: return count_arrangements(int(n.strip()) for n in puzzle_input) def find_jo...
06b0f5a2ecfabbea723d1c53997f09bdf43119ec
Gloria-2001/POO-ESCOM
/tablasDeMultiplicar/tablasDeMultiplicar.py
333
3.96875
4
print("Este programa le ayuda a realizar tablas de multiplicar") num=int(input("Inserte el numero para el que quiera realizar la tabla")) limite=int(input("Inserte el limite para la tabla")) aux=0 while aux<=limite: print(aux*num) aux=aux+1 if num%2==0: print("El producto es par") else: print("El produc...
fd155ef44c9850bde9f09aa7f61a075ba5277bcb
J-Hooch/MIT6.0001
/contents/assignments/textbookexamples/3.5newton.py
256
3.625
4
#newton-raphoson for square root #find x such that x**2 - 24 is within epsilon of 0 epsilon = 0.01 y = 24.0 guess = y/2 while abs(guess*guess - y) >= epsilon: guess = guess - (((guess**2) - y) / (2*guess)) print(f"Square root of {y} is about {guess}")
d2ae1463f43cd36da023b4f9d8367df23f4eb71b
Batuhan-dev/BasicPyhtonAplication
/perfect number.py
231
3.703125
4
bolenleriTopla=0 girdi=int(input('')) for i in range(1,girdi): if girdi%i==0: print(i) bolenleriTopla=bolenleriTopla+i if bolenleriTopla==girdi: print("perfect number") else: print("not perfect number")
1ea4d1c460961c819d94256da701854abd0721aa
GitNickProgramming/Spring_2020
/CS_3120_MachLearn/Demo Code/0_demos/0_plotEx.py
842
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jan 19 19:06:23 2019 @author: fengjiang """ import numpy as np import matplotlib.pyplot as plt x=np.arange(0,3*np.pi, 0.1) y_sin = np.sin(x) y_cos = np.cos(x) plt.plot(x, y_sin) plt.plot(x, y_cos) # Plot the points using matplotlib plt.plot(x, y_...
7e489a671f3342c944248fe23b94e76ad33d6b1d
Vonewman/introduction_to_algorithm
/getting_started/insertion_sort/insertion_sort_python/insertion_sort.py
506
4.03125
4
""" - Implementation of the insertion sort algorithm in python - Author: Abdoulaye Diallo - Complexity O(n^2) """ def insertionSort(a): """ Implementation in python of the insertion sort algorithm - Complexity O(n²) """ for j in range(1, len(a)): key = a[j] i = j - 1 while...
72e29d448d4240b185a3a269dbdf42adb4573213
meqmeq/PythonDS
/Chap4/Discussion questions.py
1,572
4.09375
4
# Convert the following values to binary using “divide by 2.” Show the stack of remainders. # 17 # 45 # 96 def divide2(num): ans = [] while(num != 0): if (num % 2 != 0): ans.insert(0, 1) else: ans.insert(0, 0) num = num//2 return ans print(divide2(45)) #...
6aef8ce330ef04d435b55b47ab346b0b47cde17d
IgorTelles9/alien_invasion
/alien_invasion.py
1,137
3.59375
4
""" Módulo onde o jogo roda """ import pygame from pygame.sprite import Group from settings import Settings from ship import Ship import game_functions as gf def run_game(): """ Inicializa o jogo e cria um objeto para a tela """ pygame.init() ai_settings = Settings() screen = pygame.disp...
ffee22f258b5bfb7e668443c704e1356d898e933
NguyenNgocHaiIT/PythonBasic
/Day_6/Day_6_update.py
2,023
3.65625
4
from fractions import Fraction # global variable a_global = 1 def tong(a, b): # local variable return a + b # tong = a + a # return tong def tong_2(a, b): print(a + b) print(a_global) # result = tong(3, 4) # print(result) # # print(tong(4, 5)) # result_2 = tong_2(3, 4) # print(result_2) ...
de0523cdafafda64e8c5bcf11ec28a1672c33d5b
NguyenNgocHaiIT/PythonBasic
/Day_3/Day_3_update.py
2,366
3.5625
4
# for i in range(0, 9): # print(i) # for i in range(0, 9, 2): # print(i) # for i in range(1, 5): # print(i * i) # for i in range(5): # print(i) # for i in range(1, 5): # for j in range(0, 5): # print('%d / %d' % (i, j)) # for i in range(1, 5): # for j in range(1, 5): # print...
b7b57316b974ced348f7253a1ba0ae03bd6f9aa3
NguyenNgocHaiIT/PythonBasic
/Day_8_OOP/Mouse.py
1,084
3.78125
4
from Day_8_OOP.Animal import Animal class Mouse(Animal): # def __init__(self, name, age, weight): # self.name = name # self.age = age # self.weight = weight def __init__(self, name, age, weight, country, year): super(Mouse, self).__init__(name, age, weight) self.country ...
8f11f8ef2bf54feb5a9b6b8b5bcd23dce4f6c783
afthabvp/Dynamic-Programming
/2/seq_game.py
1,662
3.65625
4
""" The number sequence game starts with a sequence S of N numbers written on a line. Two players alternate turns. At his turn, a player must select and remove either the first or the last number remaining in the sequence. The player score is the sum of all the numbers he has taken. Each player attempts to maximize ...
fde4ed7ef02d9bf9a4cd0d32561aa6050c96b0e8
voe1999/adventofcode2018
/day06_chronal_coordinates.py
6,489
3.5625
4
""" The device on your wrist beeps several times, and once again you feel like you're falling. "Situation critical," the device announces. "Destination indeterminate. Chronal interference detected. Please specify new target coordinates." The device then produces a list of coordinates (your puzzle input). Are they pla...
a136ed6d6d14a7cb08b7773278996e3668e2d498
erwanvivien/dofus_move_bot
/mapping/map.py
4,139
3.578125
4
import sys import re def get_content(filename: str) -> str: """ Gets whole file content and returns it """ f = open(filename, "r") content = f.read() f.close() return content MAPS_NAME = ["Incarnam", "Amakna"] res = {} def get_line_info(line: str, map_name: str, separator: str) -> tu...
0e5b2fb756eb9c9a2eddab6fd3fca7524aefd29a
SamuelSunbright/Mathematic-analysis
/practice_newtondownhill.py
409
3.59375
4
x=eval(input("please input the initial x0 = ")) n=0 def f(x): return x*x*x-x-1 def fd(x): return 3*x*x-1 while True: lam=1 y=x-lam*f(x)/fd(x) while abs(f(y))>abs(f(x)): lam=lam/2 y=x-lam*f(x)/fd(x) if abs(y-x)<5E-6: print(y) print(lam) ...
f83dd4fec070d0ad94b6f8eb4de7c21784868b2b
SamuelSunbright/Mathematic-analysis
/pratice_RungeKutta.py
368
3.703125
4
import math def f(x,y): return y-2*x/y a=0 b=1 x=0 y=1 h=eval(input("please input h:")) for i in range(int((b-a)/h)): k1=f(x,y) k2=f(x+h/2,y+h*k1/2) k3=f(x+h/2,y+h*k2/2) k4=f(x+h,y+h*k3) y1=y+h*(k1+2*k2+2*k3+k4)/6 y=y1 x=x+h print("y is {:.4f} when x is {:.1f}".fo...
2f69b2620798d10de0b6eb730ee28e82cb032a67
vikky1993/Mytest
/test3.py
1,997
4.34375
4
# Difference between regular methods, class methods and static methods # regular methods in a class automatically takes in instance as the first argument and by convention we wer # calling this self # So how can we make it to take class as the first argument, to do that we gonna use class methods #just add a decor...
c96e6097a041e6486419b1b064866e46ab8bf834
Bluemi/rnn_test
/video_localization/src/util/images/__init__.py
6,475
3.625
4
import cv2 import numpy as np def is_in_range(frame, position): """ Checks whether the given position is inside the frame :param frame: The frame to check against. Should have dtype float with values between 0 and 1 :type frame: np.ndarray :param position: The position in absolute coordinates as ...
07745ef626e8d31364637c31609258df61ac05dc
capuche777/password_manager
/pw.py
570
3.875
4
#! python3 # pw.py - An insecure password locker program. import sys, pyperclip import json PASSWORDS = [] with open('passwords.json') as json_file: PASSWORDS = json.load(json_file) if len(sys.argv) < 2: print(sys.argv) print('Usage: python pw.py [account] - copy account password') sys.exit() acc...
f3647d812b9d9494ca35ee3b48162d6476cd2e8e
balemessenger/bale-bot-samples
/new_api_example/conversationbot.py
5,497
3.671875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ First, a few callback functions are defined. Then, those functions are passed to the Dispatcher and registered at their respective places. Then, the bot is started and runs until we press Ctrl-C on the command line. Usage: Example of a bot-user conversation using Conve...
1fc2fa98e06bdf57a0e64a3343f72a8137300832
sachinkalra20/demo
/demo5.py
141
4.09375
4
x=int(input("enter any number")) print(x) if not x==50: print("the value is different from 50") else: print("the value of x equal to 50")
522ff8f499329e790d7dab43f3ab3b7ccb092b08
Thameem27/PythonTraining
/Python_Day1_Assignments.py
1,396
4
4
# First Task names = ["john", "jake", "jack", "george", "jenny", "jason", "john"] temp_name = [] for i in names: if i not in temp_name: temp_name.append(i) for j in temp_name: if len(j) < 5 and 'e' not in j: print("Unique Strings whose length is less than 5 and doesnt contain letter e ...
f16aa8a92d21bf8267df9a3929a28c0ad4149183
mat94b/AiSD_Python
/6/6.5/fracs.py
2,066
3.546875
4
from fractions import gcd class Fracs: def __init__(self, x, y): self.x = x self.y = y def __str__(self): final="" if self.y==1: final = str(self.x) return final elif self.y!=1: final=str(self.x)+"/"+str(self.y) return final def __repr__(self): return "Fracs("+self.x+","+self.y+")" d...
d5aa59071d68298f8329dc476308119923c07caf
mat94b/AiSD_Python
/6/6.5/test.py
2,194
3.828125
4
import unittest from fracs import * class TestFracs(unittest.TestCase): def setUp(self): self=Fracs(2,1) def test_add_frac(self): print("ADD - TEST") a=Fracs(2,1) b=Fracs(3,1) z=a.__add__(b) self.assertEqual(z.x,5) self.assertEqual(z.y,1) def test_sub_frac(self): print("SUB - TE...
647de4f4cac1ad44cdd1660a2a81c00d468e1c21
ParkerCS/ch00-loops-functions-aotoole55
/ch00_problem_set(FUNCTIONS).py
3,284
4.46875
4
# 18/20 #SECTION 2 - FUNCTIONS (20PTS TOTAL) #PROBLEM 1 (Length of String - 3pts) # Make a function which asks the user to enter a string, then prints the length of that string. # You will need to use the input() function. # Make a call to that function def length(): string = input("Enter a string: ") print(l...
3d891ab050621beb39df665cf7e7845f16b6d9af
shoumu/HuntingJobPractice
/leetcode/62_unique_paths.py
1,151
4.125
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Author: shoumuzyq@gmail.com # https://shoumu.github.io # Created on 2015/12/16 15:39 def unique_paths(m, n): """ according to the Combinatorics, the result is C(m - 1)(m + n -2) :param m: :param n: :return: """ a = m + n - 2 b =...
daea664462f1e727b6d55bd030cd139fb75b4c42
shoumu/HuntingJobPractice
/leetcode/110_balanced_binary_tree.py
859
3.890625
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Author: shoumuzyq@gmail.com # https://shoumu.github.io # Created on 2016/3/8 11:14 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class ...
404820f96031c26c9a848ac5c0859d8099dee43c
shoumu/HuntingJobPractice
/leetcode/240_search_a_2d_matrix_2.py
1,348
3.6875
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Author: shoumuzyq@gmail.com # https://shoumu.github.io # Created on 2016/3/1 11:53 def search_matrix(matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if matrix: return search(matrix, target, ...
3ef300e086afbc252bf4172732b4c908347dd30a
shoumu/HuntingJobPractice
/leetcode/173_binary_search_tree_iterator.py
1,653
4.0625
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Author: shoumuzyq@gmail.com # https://shoumu.github.io # Created on 2016/3/8 10:01 # Definition for a binary tree node class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class BSTIterato...
88bd3051416a263bdd7a718b108e319cab3e7d3b
shoumu/HuntingJobPractice
/leetcode/238_product_of_array_except_self.py
1,233
3.65625
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Author: shoumuzyq@gmail.com # https://shoumu.github.io # Created on 2015/11/1 14:27 def product_except_self(nums): product = 1 zero_count = 0 out = [] for num in nums: product *= num if num is 0: zero_count += 1 ...
489897b33a28a80d63fc12d87fc7af5e5a7696a2
shoumu/HuntingJobPractice
/leetcode/77_combinations.py
792
3.625
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Author: shoumuzyq@gmail.com # https://shoumu.github.io # Created on 2016/3/8 12:41 class Solution(object): def combine(self, n, k): """ :type n: int :type k: int :rtype: List[List[int]] """ self.combines = [...
ca0bc21ad8af26a2e23c2bdc1ddd0ca1e29acaa1
friedrice00/snakifyfinal
/Digitalclock.py
137
3.8125
4
# Read an integer: a = int(input()) # Read a float: # b = float(input()) # Print a value: # print(a, b) print(a // 60, " " + str(a % 60))
e6e3d86e8aa39574517d0a1e27a3cf930a14ddec
emembrives/tinkerings
/oldnews/selection/distances.py
2,801
3.5
4
import math from clean_text import clean_text def compute_distance(unigrams, bigrams, tweet1, tweet2, debug=False): total_distance = [] if debug: print tweet1['text'], tweet2['text'] for word1 in clean_text(tweet1['text']).split(' '): word1_index = -1 if word1 in unigrams: ...
9f9bb2ba1f1a40eb11bcccf0bf1f4f72743cb54a
Huni1153/Study_Python
/StudyProject/DBAdressBook/classContainer.py
1,329
3.6875
4
from noDBAdressBook import classContent class Container(): # 생성자 def __init__(self): self.listContent = list() print("Container 생성자 호출") # def setListContent(self, listContent): # set메소드 # self.listContent = listContent # # def getListContent(self): # get메소드 # retur...
a1359c67ff145887971c321d59d20f207a9e2b7f
nimoutmang/python-1
/exercise3/final5.py
294
3.828125
4
number=int(input("Enter>>")) condition=True number1=1 while number !=72 and condition: number1=number1+1 if number1 == 4: condition = False if number<72: number=int(input("Enter>>")) if condition: print("Win") else: print("lost")
41fa2c122d7dc0de5b06c2e8b47f286ac911616b
nimoutmang/python-1
/exercise3/ex1.py
322
4
4
fruits=[ ["mango", "yellow", 1], ["banana", "yellow",14], ["coconut","white",15], ] fruitName=input("Enter>>") result=True for fruit in fruits: if fruit[0]==fruitName and result: print(fruit[1], fruit[2]) result=False if result: print("NotFound") ...
7cf273190d96620eee668d08dc2db2285ad01b3b
zkroliko/ADPTO-Project--Queens
/generator/generator.py
4,162
4.03125
4
#!/usr/bin/env python # coding=utf-8 # generator.py import random from sys import * PRINT_MOVES = True MAX_TRIES_FOR_TARGET = 10 MAX_TOTAL_EXPONENT = 25 # 60 MAX_BOARD_SIZE = 128 directions = { "top_left": (-1, -1), "top": (0, -1), "top_right": (1, -1), "right": (1, 0), "bottom_right": (1, 1)...
c66b500e7fcc5d3a91861f3bf4af1b564329f124
QBoens/Projet-Python
/Rogue-Like/venv/Include/Inventory.py
16,381
3.609375
4
import json from Include.Objects import * class Inventory(): """ Classe qui correspond à l'inventaire d'un Character """ def __init__(self, proprio): self.proprio = proprio self.list_objects = list() self.amount_gold = 0 self.slot_armor = dict() self.slot_armor ...
2d6c47c140910e675b9465ea5599f6e54d871ae6
samdotpage/PiCode
/play dem cards wright.py
1,671
3.75
4
import random #import random module class Ting: #make a class for level objects def __init__(self, maxx, Tingno): #when initializing, get cap and level no. self.maxx = maxx self.number = random.randint(0, maxx) #Get random number between 0 and cap self.level = Tingno def check_numbe...
6b66cbbdb06804c86c757ca97397895a314ecfeb
RamaryUp/hackerrank
/Python/sets/symmetric_difference.py
1,060
4.28125
4
''' HackerRank Challenge Name : Symmetric Difference Category : Sets Difficulty : easy URL : https://www.hackerrank.com/challenges/symmetric-difference/problem Given sets of integers, and , print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either ...
3f3e6e52a701699f567f22ad090eae737d2babe1
SinghTejveer/stepic_python_in_action_eng
/solutions/s027.py
3,152
4.03125
4
# pylint: disable=invalid-name, too-many-boolean-expressions # pylint: disable=too-many-branches, too-many-return-statements """ Given six real numbers – a, b, c, d, e, f. Solve the following system of linear equations: ax + by = e cx + dy = f 4x + 0y = 5 0x + 0y = 0 Output format - If the system...
0ac58a6f8374d222ac239f3f24d08c4144269813
SinghTejveer/stepic_python_in_action_eng
/solutions/s030.py
1,206
4.09375
4
# pylint: disable=invalid-name """ You are given coordinates of two queens on a chess board. Find out, whether they hit each other or not. INPUT Four integer numbers x1,y1,x2,y2 are being typed. OUTPUT Type "YES" (uppercase) if they hit each other or "NO" if the don't. You may need the function, that calcul...
ef64e4a52c2f1f0d14755358ba29b6f945a86336
SinghTejveer/stepic_python_in_action_eng
/solutions/s217.py
713
4.25
4
"""Given a real positive number a and an integer number n. Find a**n. You need to write the whole program with a recursive function power(a, n). Sample Input 1: 2 1 Sample Output 1: 2 Sample Input 2: 2 2 Sample Output 2: 4 """ def solve(num: float, exp: int) -> float: """Calculate num*...
c79a3bf57776ed7c72b1dfff58fdf2f62929c7ac
SinghTejveer/stepic_python_in_action_eng
/solutions/s091.py
1,056
3.578125
4
"""Cover intervals with points Given n intervals. Find the set of points having the minimum size (cardinality), for which each of the given intervals contains at least one of the points. The first line given 1≤n≤100 - number of intervals. Each of the next n lines contains two 0<=l<=r<=109 numbers, setting the beginni...
99f3382c8b97ce2f4195f6ac93d9712d662cace5
SinghTejveer/stepic_python_in_action_eng
/solutions/s005.py
1,065
4.15625
4
# pylint: disable=invalid-name """Difference of times Given the values of the two moments in time in the same day: hours, minutes and seconds for each of the time moments. It is known that the second moment in time happened not earlier than the first one. Find how many seconds passed between these two moments of time...
6423b59c917c93bb85227a0a2fb3b42b0d985ee0
SinghTejveer/stepic_python_in_action_eng
/solutions/s042.py
718
3.75
4
""" Find the number of "Ds", "Cs", "Bs" and "As" for the last test on informatics in the class consisting of n students. The program gets number n as input, and then gets the grades themselves (one by one). The program should output four numbers in a single line - the number of "D", the number of "C", the number of "B"...
b010def52ffa05d79a9e21ac6e05ab79f6664985
SinghTejveer/stepic_python_in_action_eng
/solutions/s040.py
1,085
3.9375
4
# pylint: disable=invalid-name """ In the Bioinformatics Institute a competition is held between the computer science and biology students. The winners will get a large and tasty pie. The team of biology students consists of a students, computer science team — b students. It is necessary to pre-cut the pie so that it...
d1b38c7be08f5b200b9121266acdc1bc8e3e1b92
SinghTejveer/stepic_python_in_action_eng
/solutions/s098.py
2,413
3.75
4
# pylint: disable=invalid-name """ Each square of the rectangular table NxM contains some number. Initially the player is located in the top left square. In one move he is allowed to move to the neighbouring cell either to the right or down (left and upward moves are not permitted). When passing through a square the...
85288d85c45185c3505ac16f9fc76d02459e83a3
SinghTejveer/stepic_python_in_action_eng
/solutions/s080.py
423
4.1875
4
""" Write a program, which reads the line from a standard input, using the input() function, and outputs the same line to the standard output, using the print() function. Please pay attention that you need to use the input function without any parameters, and that you need to output only that, what was transferred to ...
635b21b2b499a326d1fcd90171caae43e544c653
SinghTejveer/stepic_python_in_action_eng
/solutions/s041.py
278
3.5625
4
# pylint: disable=invalid-name """ Print the sum of all integers from a to b (a < b). """ def solve(a, b): return sum(range(a, b + 1)) def main(): a = int(input().rstrip()) b = int(input().rstrip()) print(solve(a, b)) if __name__ == '__main__': main()
ccea58b9c387c6c2363870330ef8d04e5c1502e5
SinghTejveer/stepic_python_in_action_eng
/solutions/s057.py
337
4.03125
4
"""The smallest natural divisor Given an integer, not less than 2. Find its smallest natural divisor, different from 1. """ def solve(num): i = 2 while True: if num % i == 0: return i i += 1 def main(): num = int(input().rstrip()) print(solve(num)) if __name__ == '__mai...
116f2c05238eb1e6a9e64f5c50d350efe4fadf0e
paiabhay/OpenCV-basics
/Image Processing/2. Display Image - show cmap.py
754
3.59375
4
import cv2 import matplotlib.pyplot as plt # Read an image img = cv2.imread('../Images/sunflower.jpg') gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) def plot_image(input, is_gray=False): if not is_gray: img_gray = cv2.cvtColor(input, cv2.COLOR_BGR2RGB) plt.imshow(img_gray) else: pl...
140a796cb273b709cf792d018dc49354a6ad6d6b
snehangsude/Spaceship
/main.py
1,850
3.546875
4
from turtle import Screen from spaceship import Ship from blocks import Blocks from scorecard import Score from ammunation import Ammo import time def main(): def close(): """Close the screen/window""" screen.bye() screen = Screen() screen.bgcolor("grey20") screen.title("Spaceship") ...
1fa292cd14bb5696ac24e16bf2b4c7c300482cfb
JafarAkhondali/CryptoMath101-exercices
/Q4-RabinImproved/Helper.py
1,022
3.5625
4
def l(str): print("[✨] %s " % str) def calculate_max_bits_for_number(num): bits = 1 max_size = 1 while num > max_size: bits += 1 max_size = (max_size << 1) | max_size return bits def powmod(a, b, c): if b < 3: return a ** b % c if b % 2 == 0: return (powmo...
043b79f48cd198730c881bec8b3eb084d00bbd7f
embatbr/whatever
/less-than-1-hour/problem1.py
692
3.703125
4
# not using iteration in this problem def sum_for_loop(eltos): ret = 0 for i in range(len(eltos)): elto = eltos[i] ret = ret + elto return ret def sum_while_loop(eltos): ret = 0 i = 0 while i < len(eltos): elto = eltos[i] ret = ret + elto i = i + 1 ...
8cd239ffb02b98a02631b30b9c3cb4f7d7ad7172
ydhwa/python_lectures
/practice/practice01.py
5,044
3.65625
4
# 문제 1. 키보드로 정수 수치를 입력 받아 그것이 3의 배수인지 판단하세요. def problem1(): print('[문제 1]') try: var = int(input('수를 입력하세요: ')) print('3의 배수가 아닙니다.' if var % 3 != 0 else '3의 배수 입니다.') except ValueError: print('정수가 아닙니다.') print() # 문제 2. 키보드로 정수 수치를 입력 받아 짝수인지 홀수 인지 판별하는 코드를 작성하세요. def pro...
63150fdffd5cb18db160d1dbbccbcb99c5100ed8
ydhwa/python_lectures
/lambda/map_filter.py
703
4.0625
4
def f(x): return x ** 2 # map(f, [1, 2, 3, 4]) # map은 iterator 객체이다. it = map(lambda x: print(x**2, sep=' '), [1, 2, 3, 4]) next(it) next(it) next(it) next(it) print('===========================') # 만듦과 동시에 출력시키려면? # list에 iterator를 인자로 주면 list가 알아서 next를 시켜(next를 시킨다면 그 과정에서 실행이 됨) 리스트에 넣는다. lst = list(map(la...
92be9315e52bb642bdab6c8d3777cc7f7c7f1c6e
fxz200/FXFX
/猜數字.py
12,083
3.765625
4
# -*- coding: utf-8 -*- # 進入迴圈,直到玩家正確設定難度 while(True): # 取得使用者輸入的難度 levelset=(input('請輸入難度(1~5):')) #各難度對應的次數 if levelset==('1'): time=25#次數 print("難度已設定為1")#顯示遊戲難度 print("-------------------------------------------------------") break#跳出迴圈 ...
dbf0649dd26de099627e5585fd6549677be906e6
jorgeacosta19/BrandTech_WebDev
/A6/6.4.py
255
4.09375
4
#4- Write a program that asks the user for a number n and prints the sum of the numbers 1 to n n=int(input("Please input a number:")) i=0 acum=0 while i < n: i+=1 acum=i+acum print(("The sum of the numbers from 1 to n is: {}").format(acum))
c9f91f18ffbf5ce4f1b750f0583b176b27b921f7
sumitkumar25/Algorithms_Py
/test/diffPairs.py
622
4.03125
4
def binarySearch(arr,val,start,end): if start <= end: m = start + (end-start)//2 elem = arr[m] if val == elem: return elem elif val < elem: return binarySearch(arr,val,m+1,end) else: return binarySearch(arr,val,start,m-1) return None #...
5f555ade48cfd78e63a3b5565a577e06a67bc292
skypinacolada/Project-Euler
/016_Power_digit_sum.py
328
3.984375
4
''' 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2**1000? ''' import datetime start = datetime.datetime.now() def summa(): res = 0 for i in str(2**1000):res += int(i) return res print(summa()) print(datetime.datetime.now() - start) #...
30ea565aa5a1705bf40104ff763e3519014312aa
skypinacolada/Project-Euler
/003_Largest_prime_factor.py
702
3.734375
4
''' The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? ''' import datetime start = datetime.datetime.now() def is_prime(num): for div in range(2, int(num**(1/2))+1): if num%div==0 : return False return True def factors(num): res = [] ...
81e57b1ccbf605b63d2b83a79ef6accf3a78161f
ElikBelik77/Genetic-Pathfinding
/NeuralNetwork.py
3,520
3.53125
4
import numpy import random class Neuron: def __init__(self): """ Initiates a new neuron """ self._connected_neurons = [] self._input = 0 self._weights = [] def feed_forward(self): """ This function feeds the signal forward to all connected neur...
052152f586d3b5e17ec2854f75ec2d3bd9449c56
rkdtmddnjs97/algorithm
/BOJ/2021_1/1181_new.py
235
3.71875
4
T = int(input()) words = [] for t in range(T): word = str(input()) word_len = len(word) words.append((word,word_len)) words = list(set(words)) words.sort(key= lambda x:(x[1],x[0])) for value, key in words: print(value)
26cda7c6f5c0c0dea8d12621d1ce57aefca1d016
DaltonC-create/100_Days_of_Code
/BlackJack/main.py
2,161
3.671875
4
import random, art cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] user_cards = [] dealer_cards = [] def deal_card(): return random.sample(cards, 2) def draw_card(): return random.choice(cards) def Blackjack(): print(art.logo) user_cards = deal_card() dealer_cards = deal_card() user_score = sum(use...
8c3ed77439371b18c45e60d0c1623efa5e2570c7
bthuynh/python-challenge
/PyPoll/main.py
2,879
4.125
4
# You will be give a set of poll data called election_data.csv. # The dataset is composed of three columns: Voter ID, County, and Candidate. # Your task is to create a Python script that analyzes the votes and calculates each of the following: # The total number of votes cast # A complete list of candidates who receive...
8a4876cd4aae26f15d9673aac9fdf90aa58b573c
peltierchip/the_python_workbook_exercises
/chapter_1/exercise_17.py
787
4.1875
4
## #Compute the amount of energy to achieve the desired temperature change H_C_WATER=4.186 J_TO_KWH=2.777e-7 C_PER_KWH=8.9 #Read the volume of the water and the temperature change from the user volume=float(input("Enter the amount of water in milliliters:\n")) temp_change=float(input("Enter the value of the temperature...
cf737d75cb2478e8fd3a0c0634b49652cdbcd749
peltierchip/the_python_workbook_exercises
/chapter_5/exercise_126.py
888
4.0625
4
## #Simulate the distribution of cards from exercise_125 import createDeck, shuffle #Store the number of hands and the number of cards per hand NUM_HANDS=4 NUM_CARDS=5 ##Deal the cards to players # @param n_h the number of hands # @param n_c the number of cards # @param d_c the deck of cards # @return the list contain...
dc186dd1782eb6b18c73d37d9aff0f9afcbf5023
peltierchip/the_python_workbook_exercises
/chapter_2/exercise_35.py
191
4.5
4
## #Check if an integer is even or odd #Read the integer from the user n=int(input("Enter an integer:\n")) if (n%2==0): print("%d is even"%n) else: print("%d is odd"%n)
d08a243b383d0addaafc1bb0a2f81c8ff72b91ec
peltierchip/the_python_workbook_exercises
/chapter_7/exercise_163.py
1,126
4.09375
4
## # Read all the files in the baby names data set and identify all the # names that have been most popular in at least one year # Store the first year and the last year as constants FIRST_YEAR = 1900 LAST_YEAR = 2012 # Create two list to store the most popular names p_n_b = [] p_n_g = [] # Process each year in the ra...
1e0ed285d5f8797eab8da2e8bd076f1c7078185a
peltierchip/the_python_workbook_exercises
/chapter_2/exercise_49.py
894
4.40625
4
## #Determine the animal associated with the inserted year #Read the year from the user year=int(input("Enter the year:\n")) #Check if the year is valid if year>=0: #Determine the corresponding animal and display the result if year%12==8: animal="Dragon" elif year%12==9: animal="Sn...
4878ceeb7108bd2885a2fccdce8abb5312be586d
peltierchip/the_python_workbook_exercises
/chapter_8/exercise_184.py
1,378
4.59375
5
## # Perform the flattening of a list, which is convert # a list that contains multiple layers of nested lists into a list that contains all the same elements without any nesting ## Flatten the list # @param data the list to flatten # @return the flattened list def flattenList(data): if not(data): return d...
5d8a7606ac90a78fb1303d7f7e93c1be4e9aa563
peltierchip/the_python_workbook_exercises
/chapter_5/exercise_115.py
995
4.5
4
## #Determine the list of proper divisors of a positive integer entered from the user ##Create the list of proper divisors # @param n the positive integer # @return the list of proper divisors def properDivisors(n): p_d=[] i=1 #Keep looping while i is less or equal than about half of n while i<=(n//2): ...
b3f81cd9792372a13ee9a09e03775b4c95aeacaf
peltierchip/the_python_workbook_exercises
/chapter_5/exercise_130.py
1,143
4.34375
4
## #Identify unary + and - operators in a list of tokens and replace them with u+ and #u- respectively from exercise_129 import tokenizing ##Replace unary + and - operators respectively with u+ and u- # @param ts the list of tokens # @return the list of tokens where the unary + and - operators have been substituted def...
f08114b5f25112a2f4b604ed1df58218901bdfeb
peltierchip/the_python_workbook_exercises
/chapter_4/exercise_109.py
943
4.15625
4
## #Display all the magic dates of the 20th century from exercise_106 import daysMonth #Store the first year and the last year as constants FIRST_YEAR=1901 LAST_YEAR=2000 ##Determine if the date is a magic date # @param y the year # @param m the month # @param d the day # @return True if the date is magic. False other...
8312a957ec2cc7de0eacaa4fda57e20f04689b70
peltierchip/the_python_workbook_exercises
/chapter_5/exercise_120.py
785
4.1875
4
## #Display a list of items formatted ##Formatting items in a list # @param l the list # @return a string containing the formatted elements def formattingList(l): i=0 n_l=l if len(l)==0: return "No items have been entered." if len(l)==1: return str(l[i]) delimeter=" " n_s="" ...
d58c3325359ae564c265e490b0dbf0240d51a137
peltierchip/the_python_workbook_exercises
/chapter_2/exercise_47.py
1,246
4.4375
4
## #Determine the season from the day of the year entered #Read the day of the year fom the user month=input("Enter the month:\n") day=int(input("Enter the day:\n")) season=" " #Determine the season if (month=="January") and (1<=day<=31): season=="Winter" elif (month=="February") and (1<=day<=28): sea...
cac1940a614d6f16c162029f1feda06fb0332e04
peltierchip/the_python_workbook_exercises
/chapter_6/exercise_138.py
1,081
4
4
## # Create a dictionary that maps from key to character num_keypad={1:[".", ",", "?", "!", ":"], 2:["A", "B", "C"], 3:["D", "E", "F"], \ 4:["G", "H", "I"], 5:["J", "K", "L"], 6:["M", "N", "O"], 7:["P", "Q", "R", "S"], \ 8:["T", "U", "V"], 9:["W", "X", "Y", "Z"], 0:" "} # Read a text message from the user txt_message=...
1d460dae11b9cf1493fa428c3d32e07fcf3910d8
peltierchip/the_python_workbook_exercises
/chapter_4/exercise_95.py
1,319
4.3125
4
## #Capitalize a string entered from the user ##Capitalize the string # @param string the string to capitalize # @return the string for which the capitalization has been realized def capitalize_it(string): c_string=string i=0 while i<len(string) and c_string[i]==" ": i=i+1 if i<len(string): ...
029562d3c3a05977df813e73fbda14bf86927683
peltierchip/the_python_workbook_exercises
/chapter_8/exercise_181.py
1,233
4.125
4
## # Determine whether it is possible to form the dollar amount entered by # the user with a precise number of coins, always entered by the user from itertools import combinations_with_replacement ## Determine whether or not it is possible to construct a particular total using a # specific number of coins # @param d_...
04c6910c0ccb89150e8b2a4cfe6d624d2fb8554e
peltierchip/the_python_workbook_exercises
/chapter_7/exercise_151.py
1,017
3.75
4
## # Display the concatenation of one or more files whose names are provided as # command line arguments import sys # Verify that at least one command line argument (in addition to the .py file) was supplied if len(sys.argv) == 1: print("At least the name of a file name must be provided as a command line argument....
ab065da1c97d276ae71cff4985aa8b33314cf6ee
peltierchip/the_python_workbook_exercises
/chapter_1/exercise_7.py
247
4.1875
4
## #Calculation of the sum of the first n positive integers #Read positive integer n=int(input("Enter a positive integer\n")) #Calculation of the sum s=(n)*(n+1)/2 #Display the sum print("The sum of the first %d positive integers is: %d" %(n,s))
ef155eb105efa824a70bfc824dc1b35e34a3a64b
peltierchip/the_python_workbook_exercises
/chapter_4/exercise_107.py
1,283
3.953125
4
## #Reduce a fraction entered by the user to lowest terms #Determine the fraction reduced to lowest terms # @param n the numerator # @param d the denominator # @return the numerator and the denominator of fraction reduced to lowest terms def fractionLowestTerms(n,d): if n==0: return (0,1) gcd=min(n,d) ...
5be98f13a7da3362eb8947334e91a6fab61437d7
peltierchip/the_python_workbook_exercises
/chapter_4/exercise_90.py
1,468
4.03125
4
## #Display the entire text of the song "The Twelve Days of Christmas" from exercise_89 import determine_ord_number #Store the upper limit and the lower limit as constants LOW_LIMIT=1 UPP_LIMIT=12 ##Display a precise verse of the song # @param n_verse the number of the verse # @return (None) def determine_verse(n_vers...
7483911b1100cc93fd10dda7b49ade3d9c78d6c0
peltierchip/the_python_workbook_exercises
/chapter_6/exercise_146.py
1,163
3.71875
4
## # Generate and display a Bingo Card from random import randrange # Store the number of numbers per column as constant NMBRS_PER_CLMN=5 # Generate a Bingo Card # @return the dictionary representing the Bingo Card def generateBingoCard(): b_c={"B":[], "I":[], "N":[], "G":[], "O":[]} i=1 j=15 for k i...
b6f80becd1d1f37802a427950c059b41788d2b0d
peltierchip/the_python_workbook_exercises
/chapter_6/exercise_136.py
921
4.71875
5
## # Perform a reverse lookup on a dictionary, finding keys that # map to a specific value ## Find keys that map to the value # @param d the dictionary # @param v the value # @return the list of keys that map to the value def reverseLookup(d,v): # Create a list to store the keys that map to v k_a_v=[] # Check ...
c22deedf7d33043df0d14f90d3068ea1776b5f54
peltierchip/the_python_workbook_exercises
/chapter_7/exercise_172.py
1,981
4.15625
4
## # Search a file containing a list of words and display all of the words that # contain each of the vowels A, E, I, O, U and Y exactly once and in order # Create a list to store vowels vowels_list = ["a", "e", "i", "o", "u", "y"] # Read the name of the file to read from the user f_n_r = input("Enter the name of the ...
b9a6cb431b02ff057c8ce4aff5a20ae724f78b30
peltierchip/the_python_workbook_exercises
/chapter_5/exercise_111.py
718
4.4375
4
## #Display in reverse order the integers entered from the user, after being stored in a list #Read the first integer from the user n=int(input("Enter the first integer:\n")) #Initialize integers to an empty list integers=[] #Keep looping while n is different from zero while n!=0: #Add n to integers integers.ap...
eff97d621b989c079cb0d1359d1c56b485d575e7
eduschadesoares/pythonCodes
/pythonCodes/Binary Tree/treeController.py
1,287
3.78125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from fileHandler import File from tree import Tree import getch, keyboard, os class Controller: def start(self): tree = Tree("example") def get_words(): data = self.file.readFile() if data: root = True ...
5c6fb2e3f67634210023db01bc62034612cbb454
spalladino/algoritmos-gcba
/codigo/python-intro/lineal.py
208
3.859375
4
# Busqueda secuencial de un elemento en un arreglo def busquedaLineal(buscado, arreglo): for i, elemento in enumerate(arreglo): if elemento == buscado: return i return -1
ec1a997a36b08ef98d89222d97b026e9fa3cffd3
spalladino/algoritmos-gcba
/codigo/python-sorting/selectionsort.py
226
3.875
4
def sort(array): for i in range(0, len (array)): min = i for j in range(i + 1, len(array)): if array[j] < array[min]: min = j array[i], array[min] = array[min], array[i]
c8d3894865a13cc14767160f6b5913792e952d83
KynanBertulli/HackerRank
/PythonChallenges/HackerRank_Python/Split_and_Join.py
298
3.609375
4
""" HackerRank Python Split and Join @author Kynan Bertulli """ def split_and_join(line): # write your code here splitword = line.split(" ") joinword = "-".join(splitword) return joinword if __name__ == '__main__': line = input() result = split_and_join(line) print(result)
84e1d58ad16f91825fcfb06eac1c1226b61f5e6a
Lycurgus1/python
/day_1/Dictionaries.py
1,220
4.53125
5
# Dictionary student_records = { "Name": "Sam" # Name is key, sam is value , "Stream": "DevOps" , "Topics_covered": 5 , "Completed_lessons": ["Tuples", "Lists", "Variables"] } # Can have a list in a tuple student_records["Name"] = "Jeff" print(student_records["Completed_lessons"][2]) # fetching ind...
1467bd581d54b3244d0ed003f2e5a47d0d6e77a7
Lycurgus1/python
/day_1/String slicing.py
567
4.21875
4
# String slicing greeting_welcome = "Cheese world" # H is the 0th character. Indexing starts at 0. print(greeting_welcome[3]) # Gets 4th character from string print(greeting_welcome[-1]) # Gets last character from string print(greeting_welcome[-5:]) # Gets 1st character to last x = greeting_welcome[-5:] print(x) # St...
2ecaa40da83339322abdb4f2377cbe44fad0b3b6
Lycurgus1/python
/OOP/Object Orientated Python.py
1,496
4.25
4
# Object orientated python # Inheritance, polymorhpism, encapsulation, abstraction class Dog: amimal_kind = "Canine" # Class variable # Init intalizes class # Give/find name and color for dog def __init__(self, name, color): self.name = name self.color = color def bark(self): ...
e663be6383c2ed0ce3548ace8e5115b2a69980e0
Lycurgus1/python
/day_1/Tuples.py
209
3.65625
4
# Tuples, can use things that never change, NHSid etc. meats = ("Salami", "Chorizo", "Steak") print(meats) x = list(meats) x.insert(0, "Max") meats = tuple(x) print(meats) # y = ', '.join(meats) # print(y)