blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
36ac27b360e2831d71b662635b8332c72af2c84c
Kajal2000/question_python
/m_qus.py
800
3.671875
4
# more qus 7 list1 = [1, 342, 75, 23, 98] list2 = [75, 23, 98, 12, 78, 10, 1] new_list = [] i = 0 while i < len(list1): if list1[i] in list2: new_list.append(list1[i]) i = i + 1 print new_list # questions 6 string_list = ["Rishabh", "Rishabh", "Abhishek", "Rishabh","Divyashish", "Divyashish"] new_list = [] i = ...
f2e5ecf19b541470a4ccc606288d89bf947eef65
Lord-Kanzler/DS-Unit-3-Sprint-1-Software-Engineering
/DS13_Unit3_Week1_Sprint_Challenge_ALEX_KAISER/acme_report.py
1,071
3.890625
4
# !/usr/bin/env python from random import randint, sample, uniform from acme import Product # Useful to use with random.sample to generate names ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved'] NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???'] ## Not working, yet! def generate_p...
e3bd7e7e8441f8b0e080542e91f9d0a0e9661fc5
jerryzhang2019/VScode-git-leetcode
/Python3入门+进阶/9-14继承/ClassStudent.py
1,384
3.75
4
from ClassHuman import Human # 类的调用方法 class Student(Human): # 定义一个学生Student类,继承Human的属性 def __init__(self, school, name, age): # 在构造函数中增加新的变量school,改写子类的构造函数 self.school = school # 新的实例变量 # Human.__init__(self,name, age) # 在子类里面调用父类的构造函数,需要注意的地方是不要忘记添加self,否则会报错 # 同时上面的方法是不可取的,我们一般不这么使用...
7fabe025fdf1c8bdd5d69919cac47e53cbe9d295
vsofat/SoftDev
/Fall/03_csv/occupationPicker.py
917
3.671875
4
import csv import random # csv library makes reading the csv we have easier because there are "," in various spots and we can not simply split along the "," with open('occupations.csv') as csv_file: #code by Vishwaa, edited by kiran read = csv.reader(csv_file, delimiter = ",") dict = {} l = 0 for ...
d209bfd85aae20c99cc46041c66f3975065bb0b4
miaalexkatz/CS550
/guess.py
451
3.953125
4
import random randomNumber = random.randrange(0,10) guess = False def start(): user = int(input("I'm thinking of a number between one and ten...: ")) def check(): if user==randomNumber: guess = True print("Yay! You've won! That's pretty cool") elif user>10 or user<1: print("I litera...
62da0d9a059a6226d4a2e4fada0a4053059af154
k4u5h4L/algorithms
/leetcode/Insertion_Sort_List.py
2,676
4.0625
4
''' Insertion Sort List Medium Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head. The steps of the insertion sort algorithm: Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. At each iteration, in...
62a60040e1ac41e8aced27991bf41cc4313f4f79
kuzaster/python_training_2020
/HW2/task5/task05.py
792
4.03125
4
""" Some of the functions have a bit cumbersome behavior when we deal with positional and keyword arguments. Write a function that accept any iterable of unique values and then it behaves as range function: import string assert = custom_range(string.ascii_lowercase, 'g') == ['a', 'b', 'c', 'd', 'e', 'f'] assert = ...
1430984b0806a47a71914bddf76d7668a3d73ffa
carlaiau/deep-reinforcement
/orig-agent.py
2,750
3.546875
4
from frozenlakegame import frozenlakegame import numpy as np """agent.py: Implementation of random action agent for COSC470 Assignment 3. """ __author__ = "Lech Szymanski" __license__ = "GPL" __version__ = "1.0.0" __email__ = "lechszym@cs.otago.ac.nz" # Instantiate the game # You can change the reward value of...
8ef5bac8079d5f6082617be6d9f8321dd8722be2
Yobretaw/AlgorithmProblems
/EPI/Python/Heap/11_1_mergeSortedFiles.py
1,366
3.78125
4
import sys import os import math import imp from heapq import * """ Design an algorithm that takes a set of files each containing increasing integers, and writes a single file which contains the integers appear in all input files, in increasing order. Each file are of the order of 5 - 100 mega bytes. There...
f1dd2262b008c3ac4cde4967589d9dcf87560a36
mikellykels/coding_dojo_projects
/Python/mult_sums_avg/mult_sums_avg.py
586
4.5625
5
# Write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use a list to do this exercise. for odd in range(1, 1001, 2): print odd # Create another program that prints all the multiples of 5 from 5 to 1,000,000. for mult in range(5, 1000005, 5): print mult # Create a program tha...
8b04431e0a646ae91a24f1cd20c643009f3f3ea7
shura08g/Python
/HackerRank/20_UtopianTree.py
2,076
4.46875
4
''' The Utopian Tree goes through 2 cycles of growth every year. Each spring, it doubles in height. Each summer, its height increases by 1 meter. Laura plants a Utopian Tree sapling with a height of 1 meter at the onset of spring. How tall will her tree be after growth cycles? For example, if the number of grow...
75dfd10b8120b6cbbc893b43d586c70f5bd13eb6
aphougat/tensorexample
/normalization.py
337
3.75
4
from numpy import array from numpy.linalg import norm import numpy as np a = array([1, 2, 3]) print("vector is %s" % a) val = np.sqrt(np.power(a[0], 2) + np.power(a[1], 2) + np.power(a[2], 2)) print("l2 norm via calculation is %s" % val) l1 = norm(a, 1) l2 = norm(a) print("l1 norm via np is %s" % l1) print("l2 norm via...
331dec47b040749eb8d8ae24befd44cd818fff2f
hwang-m/leetcode
/Python/161-180/Fraction to Recurring Decimal.py
851
3.546875
4
class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: sign = [''] if numerator * denominator < 0: sign = ['-'] numerator, denominator = abs(numerator), abs(denominator) q, r = numerator // denominator, numerator % denominator ...
3e5a8bb04c4f791583daa4a1135e7efac6946c29
erizocosmico/Project-Euler-Solved-Problems
/Problem 23/euler23.py
852
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def get_divisors(num): return [i for i in xrange(1, num) if num % i == 0] def main(): abundants = {} sum_ = 0 for i in xrange(12, 28123): print "Search for %d" % i if sum(get_divisors(i)) > i: abundants[i] = i print ...
21c221e31371a6d804555fac98aecd1b6456c72f
i-aditya-kaushik/geeksforgeeks_DSA
/Matrix/Codes/beautiful_mat.py
1,891
4.1875
4
""" Make Matrix Beautiful Given a Square matrix mat[] of size NxN. Your task is to find minimum number of operation(s) that are required to make the matrix Beautiful. A Beautiful matrix is a matrix in which sum of elements in each row and column is equal. In one operation you can only increment any value of cell of mat...
37376a908bb2bd1fba00b7a8588a5d2ad4d702cd
tripletL/Jetbrain_Projects
/coffee1.py
676
4
4
a = int(input("Write how many ml of water the coffee machine has:")) b = int(input("Write how many ml of milk the coffee machine has:")) c = int(input("Write how many grams of coffee beans the coffee machine has:")) d = int(input("Write how many cups of coffee you will need:")) a1 = a//200 b1 = b//50 c1 = c//15 ...
5d65b5f8ea523b99fdc5d5fda465016096a07345
kvthr/NLP
/NMT/utils/language.py
1,135
3.828125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging class LanguageIndex(object): def __init__(self, language=None, word2idx=None): self.language = language if word2idx is not None: self.word2idx = word2idx else: self.word2idx = {} self.idx2word...
38bda8b96c4ccbf1978ac54bfb37a2bd3ce2711a
minhhoangbui/coding_exercise
/HuyenChip_LeetCode/stack.py
963
4.03125
4
''' An implementation of Stack data stucture ''' from __future__ import print_function class Stack(object): def __init__(self): self.stack = [] def size(self): return len(self.stack) def is_empty(self): return self.size() == 0 def pop(self): if self.is_em...
917c740e0596f4612fd2c92d4369fbdef56b4138
tfdetang/text_renderer
/textrenderer/noiser.py
4,689
3.515625
4
import numpy as np from PIL import Image import noise import cv2 # https://stackoverflow.com/questions/22937589/how-to-add-noise-gaussian-salt-and-pepper-etc-to-image-in-python-with-opencv class Noiser(object): def __init__(self, cfg): self.cfg = cfg def apply(self, img): """ :param i...
0688d7492f5f54ceda4a8c87f6f76e462f2ba110
ilkercig/metalheart_django
/metalheartapp/utility.py
347
3.546875
4
import re def remove_parenthesis(text): return re.sub(r"\(.+\)$", "", text) def remove_ellipsis(text): return re.sub(r"[\u2026\.]+$", "", text) def remove_redundant_chars(text): text = text.strip() text = remove_parenthesis(text) text = text.strip() text = remove_ellipsis(text) text = t...
162ff2daf8668241f3bf9458a864c8b4f3bf7f48
Pabitra-26/CSES-Set
/Introductory/Creating_Strings_1.py
377
4.03125
4
#Problem name: Creating Strings 1 # Description: Given a string, your task is to generate all different strings that can be created using its characters. # Strategy: use permutations method from itertools module from itertools import permutations string=input() ls=sorted(list(set(permutations(string)))) li=...
376b786f29a17bcf90cd69c17efb1214044af612
kimkcn/cannon
/src/lib/time_api.py
716
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def datetime_to_timestamp(date_time): import datetime timestamp = datetime.datetime.strptime(date_time, '%Y-%m-%d %H:%M:%S').timestamp() return time_stamp def timestamp_to_datetime(time_stamp): import time date_time = time.strftime("%Y-%m-%d %H:%M...
22b7b59a614d2d44115521921de4597847638d2b
EmandM/ladebug
/commandLine/exercises/mergesort.py
1,113
4.1875
4
def mergeSort(arr): if len(arr) <= 1: return arr # a//b is floor division mid = len(arr)//2 first = mergeSort(arr[:mid]) second = mergeSort(arr[mid:]) firstIterator = secondIterator = 0 result = [] while firstIterator < len(first) and secondIterator <= len(second): ...
9838ec3109b142831459ea826f3e1f854fcdc4c7
eduardopoleo/dl_udemy_project_1
/ann2.py
7,669
3.96875
4
# Classification template # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #################### Pre Processing ################################ # Importing the dataset dataset = pd.read_csv('Churn_Modelling.csv') X = dataset.iloc[:, 3:13].values y = dataset.iloc[:, 13]....
9b23da1614153c44375c9faf0658323d3a7cefd5
nachiketa-plutus/python_referenceAndAdv
/35_GeneratorFunForFibonacci.py
710
4.375
4
# This is a simple generator for Fibonacci Numbers def fibonacci(): # Initializinf first two Fibonacci Numbers a, b = 0, 1 # One by one yield next Fibonacci Number while True: #a < limit: yield a a, b = b, a + b # Create a generator object f = fibonacci() counter = 0 for x in f: ...
b12ded62e091ad7a944e586b1a3c69eabdb5bca5
TanishqSinghAnand/Correlation
/scatter2.py
194
3.5
4
import pandas as pd import csv import plotly.express as px with open("datas.csv") as f: df = csv.DictReader(f) fig = px.scatter(df, x="Coffee in ml", y="sleep in hours") fig.show()
1077347d1fd45d5f444283cd64c69d966f172219
reulan/spellblade_legacy
/player.py
11,313
3.875
4
#!/usr/bin/env python """ player.py - Default player class Author: mpmsimo Created: 1/7/2015 A player object with HP, name, level, exp, and basic stats. To-do: * Rename to character.py and change the imports neeeded. """ from tabulate import tabulate class Character(object): def __init__(self,...
659db5a7a6788957633e31ba8c5361d8fe79c117
hyejinHong0602/BOJ
/bronze3/[WEEK1] 2562 - 최댓값.py
456
3.859375
4
numbers=[] for i in range(9): numbers.append(int(input())) print(max(numbers)) print(numbers.index(max(numbers))+1) # ----------------------------------------# numbers=[] for i in range(9): numbers.append(int(input())) max_num=numbers[0] for j in range(9): if (max_num<numbers[j]): max_num=numbers...
246e4947bffcc59479a0fec80f94fe50e04ba0f2
sf1025/python-study
/test_demo/dict.py
1,683
3.546875
4
#coding:utf-8 #!usr/bin/env python if __name__ == "__main__": print("字典-dict")# dictionary字典 #创建字典 mudict = {} person = {"name":"aaa", "site":"reee", "lang":"gbk"} print(person) #字典可以原地修改 person['name2'] = "www" print(person) #利用元组构建字典 name = (["first","aa"], ["second", "bb"]) ...
0b2aa3db288c6798a82f0f169d6f7bcb0046e273
AndersonAngulo/T_10-Angulo-Damian
/damian/libreria.py
6,255
3.828125
4
#validar entero def validar_entero(numero_positivo): if(isinstance(numero_positivo,int)==True and isinstance(numero_positivo,bool)==False and numero_positivo>=0): return True else: return False #fin if #fin def #validar real def validar_real(numero_real): if(isinstance(numero_real,float...
b56aa7bf2ae50b98138b89e1d48637a33cf3915e
liutao-0811/flask_practice
/python基础/闭包.py
599
3.5625
4
def sum1( a ): def add1( c ): return a + c return add1 num1 = sum1(2) print(type(num1)) print(num1(4)) def counter(): cnt=[0] def add(): cnt[0]+=1 return cnt[0] return add num11=counter() print("33333") print(num11) print("1111") #a+b+x=y def fun1(a,b): def fun2(...
a271ae1c6f22fa69338c19e7ae7a7fe1c9d1a0e1
ddudon/google_it_automation
/Returning Values.py
993
3.96875
4
def triangle_area(base, height): return (base * height) / 2 area1 = triangle_area(5, 4) area2 = triangle_area(7, 3) sum1 = area1 + area2 print("The sum of two areas is:", sum1) print("The sum of two areas is: " + str(sum1)) # Use the get_seconds function to work out the amount of seconds in 2 hours and 30 minut...
2d34569b9078878b63637d57373466595a41e123
srmccray/project-euler
/solutions/2.py
789
3.90625
4
""" https://projecteuler.net/problem=2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find t...
ee0da4e62d9e49420499638befa40491773a743d
esernur/7.hafta-odevler
/tel defterı.py
2,150
3.75
4
print(''' TELEFON REHBERI UYGULAMASI Lutfen yapmak istediginiz islemi verilen yonergeden seciniz. Rehberi Listeleme--------------------------------------> 0 Rehbere Kisi Ekleme------------------------------------> 1 Rehberden Kisi Silme-----------------------------------> 2 Kisi Isim Guncelle...
822c5bc5bbcd7d0f570e7ba392bf1ff1d7c50ad1
Charith9/code1161
/week2/exercise1.py
1,410
4.6875
5
""" Commenting skills: TODO: above every line of code comment what you THINK the line below does. TODO: execute that line and write what actually happened next to it. See example for first print statement """ import platform # I think this will print "hello! Let's get started" by calling the print function. print("h...
24321bd92d853b37530006b018c216c482aff633
21saavage/21savage
/snake_and_ladder.py
1,451
3.890625
4
import random count=0 while (count<=100): roll=input('enter r to roll a dice') if(roll=='r'): r=random.randint(1,6) count=count+r print("random number",r) print(' in position',count) if count==8: count=37 print(' take the ladder my friend',count) ...
adfdd4e7af339da81c3478cdbf05331d2e0c91c1
Israelgd85/Pycharm
/excript/app-comerciais-kivy/Python(Udemy-Claudio Rogerio/Exe_lista_2/exe-1.py
284
4.09375
4
#1) Faça um algoritmo que leia um número e mostre se o mesmo é positivo, negativo ou zero. num = int(input("Informe um numero inteiro: ")) if (num > 0): print("O numero é positivo") elif(num < 0): print("O numero é negativo") else: print("O numero digitado é 0")
e28988333d8b29163fe4c2b904cd1df53f848aaf
o-alavi/tic_toe_game
/tic_toe.py
1,318
3.65625
4
""" The input for each player include two numbers separated with comma. Each number is 0, 1, or 2. For example, inputs: 0,0 2,2 1,0 0,2 """ game = ["-", "-", "-", "-", "-", "-", "-", "-", "-"] def display(): ...
3adc2bf01fea550835cf15de003256f74027eff0
ekatosha/EpamPython2019
/03-fp-decorator/hw/applydecorator_hw4.py
416
3.59375
4
def applydecorator(func): def wrapper1(f): def wrapper(*args, **kwargs): return func(f, *args, **kwargs) return wrapper return wrapper1 @applydecorator def saymyname(f, *args, **kwargs): print('Name is', f.__name__) return f(*args, **kwargs) # saymyname is n...
b36c30c5184a85b22d8878f7bb4c7ab0106d2446
ZachLevein/Di_Bootcamp
/Week5/Day2/Daily_Challenge.py
848
3.578125
4
import random class First(): def __init__(self, chromo=1, dna=1): self.chormo = chromo self.dna = dna self.genes = random.randint(0,1) def mutate(self): self.chromo = self.genes *10 self.dna = self.chromo *10 if random.randint(1,2) == 1: self.chro...
e692a249a1ea49fb3137d64dac1716a39cca7371
RMaturin/GB_python
/Les04/002.py
1,296
4.0625
4
# 2. Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента. # Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования списка использовать генератор. # Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]. ...
2fd88ea5091dafc024c9e5cd2ac8679f36d1dc3e
cn-uofbasel/PiCN
/PiCN/Simulations/MobilitySimulations/Model/MobileNode.py
3,498
3.734375
4
"""A model for simulating a mobile node which moves with certain speed and direction through the simulation""" from PiCN.Simulations.MobilitySimulations.Model.SimulationNode import SimulationNode from PiCN.ProgramLibs.Fetch import Fetch from PiCN.ProgramLibs.ICNForwarder import ICNForwarder from PiCN.Mgmt import MgmtC...
f6d8f641a4f434c0b608fad5482b9040599a8f28
bee1st/algorithm
/test.py
158
3.546875
4
N = int(input()) N = N - 2 r = N % 2 if r == 1: print('7', end='') else: print('1', end='') q = N // 2 for i in range(q): print('1', end='') print()
53fd05a165891ba09e577735ffeebe33269e75e8
zLordelo/pythonExercise
/ex093 - CADASTRO DE JOGADOR DE FUTEBOL.py
1,267
4
4
print('=' * 50) print(f'\033[1;31m{"CADASTRO DE JOGADOR DE FUTEBOL":^50}\033[m') print('=' * 50) '''Exercício Python 093: Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ler o nome do jogador e quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada ...
19764522005bfd6b019e287e99a59789ca6256aa
RIMPOFUNK/FirstLyceumCourse
/Lesson 10 (Строки. Индексация)/Homework/Какая-то там буква.py
135
3.921875
4
word = input() number = int(input()) if number > len(word) or number <= 0: print("ОШИБКА") else: print(word[number - 1])
a3f18d464a1c66146d1064969a4c701968475e59
michelejolie/PDX-Code-Guild
/bankaccount_3.py
421
3.796875
4
class BankAccount: def __init__(self, f_name, l_name, balance): self.f_name = f_name self.l_name = l_name self.full_name = self.f_name + ' ' + self.l_name self.balance = balance self.setup() def setup(self): print('You have create an account for {}.'.format(self....
06648452f975c4e9368348688dbfc2970a41da44
qyjoan/Hecate
/main.py
8,249
3.515625
4
#!/usr/bin/env python #-------------------------------------------------------- # File Name: main.py # Author: Simon Macarthur # Date: February 2016 # Version: 0.1 Initial Version # Purpose: This program is the main program for the Hecate program. #-------------------------------------------------------- import dateti...
dbc481f92496c5cc48ea23c1f5dae637b7623413
lalecsey/python_base
/lesson_003/00_bubbles.py
1,146
3.84375
4
# -*- coding: utf-8 -*- import random import simple_draw as sd sd.resolution = (1200, 600) # Нарисовать пузырек - три вложенных окружностей с шагом 5 пикселей # Написать функцию рисования пузырька, принммающую 2 (или более) параметра: точка рисовании и шаг point = sd.get_point(250, 250) def bubble(point, step): ...
f739e8121a9ce77eaa3a48b38414a079a40223f1
pallavigs9/python_codes
/CodeAndTest/Src/RockPaper.py
565
3.5625
4
def rock_paper_sci(p1, p2): if (p1 == 'scissors') and (p2 == 'paper'): print "Player 1 won!" elif (p1 == 'paper') and (p2 == 'rock'): print 'Player 1 won!' elif (p1 == 'rock') and (p2 == 'scissors'): print 'Player 1 won!' elif (p1 == 'paper') and (p2 == 'scissors'): print...
b4fa73b3cb29e71010d4c6c916dbaa0f4a05ca46
soyYaaG/tic-tac-toe
/main.py
5,763
3.828125
4
import os import random board_espacio = [' ' for x in range(9)] def main(): limpiar() bienvenido() board(board_espacio) while True: posicion = int(input("Por favor selecciona la posición entre 1 y 9 para insertar tu jugada (X): ")) posicion = posicion - 1 # validar si la posici...
bc8c2e2ea24b4264a3876e65934dd328f00400b6
wtomalves/exerciciopython
/ex067taboada.py
647
3.734375
4
taboada = int(input('Qual taboada você quer ver? ')) contador = 0 continuar = '' while True: if taboada < 0: print('Não imprimimos taboada com números negativos!') break if contador != 10: contador += 1 print(f'{taboada} x {contador} = {taboada * contador}') if contador == 10...
5a4befe5ef36d9256c868309306c68a4e57bcc36
sgyeong97/Baekjoon
/Python/For/10871.py
298
3.515625
4
count, num = input().split() minnum = int(num) result = [] num_list = [] temp = input() input_list = temp.split() for x in range(int(count)): num_list.append(int(input_list[x])) if num_list[x] < minnum : result.append(num_list[x]) for x in result: print(x, end=' ')
cf8434801e454f0ae8072873de3ec1d379fbba91
Anm-pinellia/PythonStudy
/testPrinter.py
489
3.640625
4
from tkinter import * root = Tk() w = Canvas(root, width=960, height=720) w.pack() #python不支持绘制点,但是可以绘制一个很小的圆形并填充来代替绘制点 def paint(event): x1, y1 = (event.x-1), (event.y - 1) x2, y2 = (event.x+1), (event.y + 1) w.create_oval(x1,y1,x2,y2,fill='red') #将鼠标左键与paint方法绑定 w.bind('<B1-Motion>', paint) Label(r...
9e12206c2f41209c9189d4b2ca68ec417b0b4812
DouglasParnoff/learning-python
/src/basic/loops.py
1,868
4.15625
4
# Python has 2 kinds: for and while print("--- For loop ---") # Write a for loop that iterates over the names list to create a userlogin list. # To create a userlogin for each name, make everything lowercase and replace # spaces with underscores. Running your for loop over the list: names = ["Tomas Delong", "Mark Hopp...
3b0c5eccf199e77e4ec4cef6688cd0160b63df62
Purushothaman56/learned-2021
/05232021/FA_CountingFunctionCall.py
708
3.75
4
# I am assigned to develop a logger module so there I wants to get number of time the logger called. # Functional approach occurances = 0 #1 # Funciton definition def logger(): global occurances #2 occurances += 1 #3 print('logged.') # Usage logger() print(f'Number of time logger got called {occurances}....
338e940b3dcab895042c014db857c0bdfd5f3f30
yutchmin/python_learn
/alien_invasion/setting.py
1,205
3.5625
4
class Settings(): '''存储外星人入侵所有设置的类''' def __init__(self): """初始化设置""" #屏幕设置 self.screen_width = 1300 self.screen_height = 900 self.bg_color = (230,230,230) # 飞船设置 self.ship_speed_factor = 1.5 self.ship_limit = 3 # 子弹设置 self.bullet_speed_factor = 1 self.bullet_width = 3 self.bullet_height = 1...
649dfb90694875ec695461187317ba44628a3b10
LenyPython/mini-games
/sudoku/sudoku.py
1,277
3.5625
4
import pygame as pg from game.constants import WIDTH, HEIGHT, WHITE, GREY from game.board import Board def mark_spot(board, x, y): if not board.board[y][x]: if not board.selected: board.select_spot(y, x) elif x == board.selected['x'] and y == board.selected['y']: board.unselect() else: board.select_sp...
f09a3bc9cbc1d37362f532be42e7044d84bb7c9f
haiou90/aid_python_core
/day04/homework_personal/04_homework.py
1,498
3.9375
4
""" 7. 赌大小游戏 玩家的身家初始10000,实现下列效果: 少侠请下注: 30000 超出了你的身家,请重新投注。 少侠请下注: 8000 你摇出了5点,庄家摇出了3点 恭喜啦,你赢了,继续赌下去早晚会输光的,身家还剩18000 少侠请下注: 18000 你摇出了6点,庄家摇出了6点 打平了,少侠,在来一局? 少侠请下注: 18000 你摇出了4点,庄家摇出了6点 少侠,你输了,身家还剩 0 哈哈哈,少侠你已经破产,无资格进行游...
6be04cffe65412915685ed0c88f56c48723d9867
lilaboc/hackerrank
/python2/py-the-captains-room.py
398
3.828125
4
# https://www.hackerrank.com/challenges/py-the-captains-room # Enter your code here. Read input from STDIN. Print output to STDOUT k = int(raw_input()) room_list = [int(i) for i in raw_input().split()] seen = set() first = set() for i in room_list: if not i in seen and i not in first: first.add(i) elif ...
9538afd1dcc6d8ca246122c99491ef4119c9dbc9
sarazhan/compiti_inf
/es14-vacanze.py
335
3.78125
4
# esercizio numero 14 pag. 72: Analizza se il numero inserito sia pari o dispari. a = int(input("Inserisci valore numerico a ")) b = int(input("Inserisci valore numerico b ")) prodotto = a*b if prodotto <= 10: risultato = a+b print("addizione =", risultato) else: risultato = a-b print("sottrazione ...
01511ba9dac3cfb5e4389cc6dd7bd5b97f0ef1d6
lebuingockhang123/L-p-tr-nh-python
/LeBuiNgocKhang_53157_CH05/Projects/page_165_exercise_07.py
526
4.1875
4
""" Author: Le Bui Ngoc Khang Date: 12/07/1997 Program: Write a program that inputs a text file. The program should print the unique words in the file in alphabetical order. Solution: Enter the input File Name: inName hello world """ inName = input("Enter the input File Name: ") inputFile = open(inName, 'r') unique...
0d3d7d3365d3ea2d35d88fa6e65747278fb613cf
sieczkah/Codewars_KATA
/7 kyu/Make a funcition that does arithmetic!.py
295
4
4
"""https://www.codewars.com/kata/583f158ea20cfcbeb400000a""" def arithmetic(a, b, op): if op == 'add': return a + b elif op == 'subtract': return a - b elif op == 'multiply': return a * b elif op == 'divide': return a / b else: pass
ebdcfbee9546117291ae7f831b30a0ef6fc66adb
barche/coolfluid3-benchmarks
/assembly/fenics-poisson_bench.py
1,201
3.625
4
""" FEniCS tutorial demo program: Poisson equation with Dirichlet conditions. Simplest example of computation and visualization with FEniCS. -Laplace(u) = f on the unit square. u = u0 on the boundary. u0 = u = 1 + x^2 + 2y^2, f = -6. """ from dolfin import * n = 64 set_log_level(DEBUG) # GNW: Use C++ optimisation ...
c4c5476680937586352c2f56ec559976bfcf30e4
jdef1028/Artificial_Intelligence_python
/assignment2/hzg972.py
14,322
3.546875
4
# File: hzg972.py # Author: He Zhao # netID: hzg972 # Date: Apr 16, 2015 # Defines a simple artificially intelligent player agent # You will define the alpha-beta pruning search algorithm # You will also define the score function in the MancalaPlayer class, # a subclass of the Player class. from random impo...
b1ace0b2cc6a8281d0d1582b17cc301cbeb347d4
Biju-vinoth/LPHW
/ex15.py
629
3.5
4
''' #============================================================================= # FileName: ex15.py # Desc: file modules # Author: Honglong Wu # Email: wuhonglong@genomics.cn # Version: 0.0.1 # Created: 05/03/2015 # History: #=================================================...
392cbcfb3471ff9809f5a8937a200c456622e6da
aguilerap-jc/OpenAI_WS
/getting_started/simple_examples.py
2,325
3.765625
4
import gym #https://gym.openai.com/docs/ ''' examples function: Start a specific example with random simulations samples and seeds ''' def examples(desired_example): env = gym.make(desired_example) env.reset() for i in range(10): for _ in range(1000): env.render() env.step(env.action_space.sample()) ...
2f65ffec246395e1e238fcc79b871da6e465cc0f
zilongxuan001/benpython
/ex05.py
2,804
3.859375
4
#--coding: utf-8 -- #Date:20170814 #Title:ex05 更多的变量和打印 my_name='Zed A. Shaw' my_age=35 #not a lie my_height=74 #inches my_weight=180 #lbs ,磅 my_eyes='Blue' my_teeth='White' my_hair='Brown' print('Let\'s talk about %s.' %my_name) print('He\'s %d inches tall.' %my_height) print('He\'s %d pounds heavy.' %my_weight) pri...
9bafc9b084d1c4376f00e913f56e887258b58315
VisargD/Problem-Solving
/Day-4/Leaf-Similar-Trees.py
1,975
4.15625
4
""" Problem Name: Leaf-Similar Trees Platform: Leetcode Difficulty: Easy Problem Link: https://leetcode.com/problems/leaf-similar-trees/ """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self....
f91bd49898886a93ff94326a7c7518359af73c71
Guan-Ling/20210125
/7-A.py
328
3.71875
4
# Given a list of numbers, count a number of pairs of equal elements. # Any two elements that are equal to each other should be counted exactly once. # 12323 2 # 11111 10 # 算重複幾次 a=[int(i) for i in input().split()] c=0 for i in range(len(a)): for j in range(i+1,len(a)): if a[i]==a[j]: c=c+1 print(c)
4a652539a6763ec9e4f47d11f964f108cfe33b27
Aasthaengg/IBMdataset
/Python_codes/p02392/s973781402.py
83
3.703125
4
ia=[int(i) for i in input().split(" ")] print("Yes" if ia[0]<ia[1]<ia[2] else "No")
583e669c7f0c3a0f5fc6a3279b9da713a676edb8
saurabhgrewal718/python-problems
/sort an array without using algorithms.py
1,204
3.6875
4
# sort an array of 0,1 and 2 without using any sorting algo # this approach will use o(n)+o(n) time i.e o{2n} time ! so thats why it is not efficeint enough! # ar=[0,0,1,2,1,1,1,1,2,2,0,0,0,0,1,1,1,2] # def sortinganarray(ar): # a=0 # b=0 # c=0 # for i in range(0,len(ar)): # if(ar[i]==0): # ...
a39fc8a845bae10f79a62a1edcbee1087b8148cc
PacktPublishing/Python-Essentials
/Chapter_6/ch06_ex1.py
7,138
3.875
4
#!/usr/bin/env python3 """Python Essentials Chapter 6, Example Set 1 """ list_example = """ >>> vred = (247, 83, 148) >>> vred[1] = 23 # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'tuple' object does not support item assignment >>> fib_list = [1, 1, 3, 5, 8] >>> fib_list.append(fib_list[-2] ...
2bd1c07f40ce25d2105ca65ceeefd5959ed53c66
DaveRoox/Interview-coding-challenges
/SortedRotatedArray.py
2,108
3.828125
4
# Brute-force approach: # Time complexity: O(n) # Space complexity: O(1) def linear_search(array, low, high, target): n = len(array) iterations = 1 for i in range(n): if array[i] == target: return True, i, iterations iterations += 1 return False, None, iterations # -----...
8b47f21353ac27e5865b668ddf777bd7824324ef
davelpat/Fundamentals_of_Python
/Ch9 exercises/student.py
3,784
4.34375
4
""" Instructions for programming Exercise 9.1 Add three methods to the Student class that compare twoStudent objects. One method (__eq__) should test for equality. A second method (__lt__) should test for less than. The third method (__ge__) should test for greater than or equal to. In each case, the method returns th...
385ad98bbbd3773fb2bf21b9300d5a0dc9b13ca8
Minari766/study_python
/Paiza/Rank_D/paizad062_ひな祭り.py
265
3.640625
4
# coding: utf-8 # 自分の得意な言語で # Let's チャレンジ!! h1, h2, h3 = input().split() dools = "ABCDEFGHIJ" s1 = dools[:int(h1)] s2 = dools[int(h1):int(h1)+int(h2)] s3 = dools[int(h1)+int(h2):int(h1)+int(h2)+int(h3)] print(s1) print(s2) print(s3)
282e8c5aaa79fbb2bd0d3ec313339d27e18e2cae
Eleanoryuyuyu/LeetCode
/剑指offer/29. 顺时针打印矩阵.py
1,055
3.625
4
# -*- coding:utf-8 -*- class Solution: # matrix类型为二维列表,需要返回列表 def printMatrix(self, matrix): # write code here if len(matrix) < 1: return [] low = 0 high = len(matrix) left = 0 right = len(matrix[0]) res = [] while low < high and left <...
48abd153af893b0f99bece86fb43029f042d1cda
daniel-reich/ubiquitous-fiesta
/Xkc2iAjwCap2z9N5D_15.py
242
3.953125
4
import datetime def has_friday_13(month, year): ans = datetime.datetime(year, month, 13) Weekday = ans.strftime("%A") Day_of_Month = ans.strftime("%d") if Weekday == "Friday" and Day_of_Month == "13": return True return False
da45c09ec80fff7517b34d291544b8e7048d2892
shohanurhossainsourav/python-learn
/program47.py
375
3.5625
4
# class and object with method class Student: roll = "" gpa = "" def set_value(self, roll, gpa): self.roll = roll self.gpa = gpa def display(self): print(f" Roll : {self.roll}, GPA : {self.gpa}") Sourav = Student() Sourav.set_value(1965, 3.81) Sourav.display() Sumaiya = Stu...
312f1f97e1f569ba3f5fbad5dde881e497fe2aa4
akcauser/Python
/education_07032020/015_if_else_elif.py
285
3.890625
4
a = 10 b = 10 if a < b: print("a küçüktür b") elif a == b: print("a eşittir b") else: print("a küçük değildir b") print("bitti") """ > büyüktür < küçüktür >= büyük eşittir <= küçük eşittir == eşittir != eşit değildir """
c4e5703535a825e2ae41ab0f60f25763931833ff
bapata/PYTHON
/gen_labels.py
278
3.65625
4
#!/usr/bin/env python3 # Set AxBxC countries=["egypt","croatia","kenya","canada"] fruits=["apple","orange","pear"] vegetables=["cucumber","tomato","radish","potato","garlic"] labels=[ c +"-" + f + "-" + v for c in countries for f in fruits for v in vegetables ] print(labels)
6c8aeaa7be5a417a1aab259e89cb2343b913a2e4
krowck/AG
/teste.py
1,653
3.859375
4
# Mathieu Blondel, February 2012 # License: BSD 3 clause # Port to Python of examples in chapter 5 of # "Introductory Statistics with R" by Peter Dalgaard import numpy as np from scipy.stats import ttest_1samp, wilcoxon, ttest_ind, mannwhitneyu group1 = np.array([ 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0....
993d9d90380f548e761514d922f5769d2b29b3a6
21lucasmessias/CursoEmVideo-Python
/ex067.py
282
3.640625
4
while True: print('-' * 40) valor = int(input('Quer ver a tabuada de qual valor? ')) if valor < 0: break mult = 0 while True: mult += 1 if mult == 11: break print(f'{valor:2} x {mult:2} = {valor * mult:2}')
7b368d6e8d7eeefdb20f46ad5c7cf487bc6aa3cd
tianyuchen/project-Euler
/022-Names_scores.py
1,139
3.96875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Using names.txt (right click and 'Save Link/Target As...'), a 46K text file # containing over five-thousand first names, begin by sorting it into # alphabetical order. Then working out the alphabetical value for each name, # multiply this value by its alphabetical positio...
4e1e3250c86e3134d696944447edc07cdb453257
mqondisi/transposer
/transposer/script/console_script.py
823
3.875
4
#!/usr/bin/python import argparse import transposer def parse_args(): parser = argparse.ArgumentParser( description="command line args to assist with development") parser.add_argument('-i', '--in', dest='file_in', default=None, required=True, help='file from which to read in...
205135514968a3ad86a857211687a0d4a026cde6
Gaurav-Pande/DataStructures
/leetcode/graphs/detect_and_show_cycle.py
385
3.890625
4
# # in a graph detect a cycle using degree of a vertex, and if exist print all the nodes existing in a cycle # import collections class Graph(object): def __init__(self, vertices): self.graph = collections.defaultdict(list) self.v = vertices def addEdge(self, u, v): self.graph[u].append(v) def getDic(self): ...
4fcfd182395c65db73597e953700296b93533a97
JasonOnes/py-library-reviews
/21.9-urllib.error.py
1,186
3.65625
4
"""urllib.error is an exception class raised bu urllib.request problems""" # URLError subclass of OSError as of 3.3 (instead of IOError) import webbrowser from urllib.error import HTTPError, URLError from urllib.request import urlopen from bs4 import BeautifulSoup def get_city_temp(city, country): # prints temp...
855c7dc1192870799c6956134a44562e97bec208
edinsonviveros/mision-tic-2021-ciclo_python
/G25/Unidad_1/Clase 2/variables.py
916
3.96875
4
""" PI = 3.14 GRAVEDAD = 9.8 var_1 = "nombre de variable" Carro = " tiene 4 ruedas" #Variable Numericas a = 10101 #Binaria b = 120 #Decimal c = 0x12c #Hexadecimal # Variables Decimales float_1 = 10.5 float_x = 1.5e2 #Variables Complejas r = 2 + 3.14j x = 25j print(a, b, c) print(float_1, float_x) print(r, r.real,...
384cf314643fba6640c36d34310b999160fc6141
z0k/CSC108
/lab1/doggie.py
663
4.125
4
age = 18 years_in_school = age - 5 print("Did you know you've been in school for about") print(years_in_school) print("years") retirement_age = 65 years_until_retirement = retirement_age - age print("and you have") print(years_until_retirement) print("years until you can retire?") # applying the rule that one human...
0e2cf1a499406171fe268a6e25c646dc9f738af0
younglilyhe/pythonBase
/hl_01_base/hl_05_dict.py
2,028
4.09375
4
"""字典中的CRUD""" """ lily_dict = {"name": "lily", "gender": False, "age": 25 } print(lily_dict) print(lily_dict.keys()) print(lily_dict.values()) print(lily_dict.items()) print(lily_dict["name"]) lily_dict["height"] = 160 lily_dict["long_hair"] = True lily_dict["name"] = "lilyhe" li...
cebc0af7bb41f68c24c73dbb7ae72065f21b2029
Ahmim88/bot
/monprenierbot.py
332
4.0625
4
#!/usr/bin/python3 #salutation = ['massil', 'ahmim', 'insim', 'bachelor', 'dev', 'web', 'python', 'juv', 'azul', 'amazigh', 'bay'] question = input("bonjour, je suis votre bot, veuillez donner un mot") if (question.lower() == "salut"): print("salut mon ami") elif (question.lower() == "bonjour"): print("salut...
098d4713ee74fb1a194304a52e9e700c9ed30d63
ii0/algorithms-6
/TargetOffer/字符流中第一个不重复的字符.py
813
3.84375
4
""" author: buppter datetime: 2019/8/19 12:43 题目描述 请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时, 第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。 输出描述: 如果当前字符流没有存在出现一次的字符,返回#字符。 """ class Solution: def __init__(self): self.first = [] def Insert(self, char): for i in char: ...
bbfccf41e5908ae971106cf8e9aa605a0ba37c00
bibongbong/pythonCookBook
/src/4.15.MergeTheSortedIterator.py
613
3.734375
4
''' 问题:如果有一系列排序序列,想将他们合并后得到一个排序序列,并在上面迭代遍历 方案:heapq.merge() 它不会马上读取所有序列,这意味着你可以在很长的序列中使用它,而不会有太大的开销 但heapq.merge()的所有输入,必须是排过序的。由于他不会预先读取所有序列 所以它在合并的时候,只是检查所有序列的开始部分,并返回最小的那个,知道所有输入序列遍历完 ''' import heapq a = [3, 4, 17, 10] b = [2, 5, 6, 11] for c in heapq.merge(a,b): print(c) ''' 1 2 4 5 6 7 10 11 '''
223801d2db5e0a53dc144551be1a4936a89939f4
zubkosergio/infa_2020_Zubko
/lab2.13.py
613
3.859375
4
import turtle as t def circle(x): for i in range(0, 360): t.forward(x) t.left(1) def arc(x): for i in range(0, 180): t.forward(x) t.right(1) t.speed(100) t.shape('turtle') t.color('yellow') t.begin_fill() circle(1) t.end_fill() t.penup() t.goto(30, 60) t.pendown() t.color('blu...
84c41134e2ca9322e5579234b0885332834487f2
edu-athensoft/ceit4101python_student
/tuit_200202/py200506_exam/exam_part_2_zeyueli_question_3.py
137
3.703125
4
# I will run through all the possibilities import itertools print(list(itertools.permutations(input("Please enter a string literal:"))))
c91257256b212092abcca1a58335c11d8b560966
davehuh/algorithms
/graph/week2/shortest_path_v2.py
2,342
4.15625
4
""" Copyright 2020 Dave Huh Shortest path using Dijkstra's algorithm """ import sys import threading from collections import defaultdict from heapq import heappop, heappush def read_file(file_name): """ build graph structure :param file_name: string file path :return: graph structure """ if l...
d86630da062f7c1a1c9766380ea43da971a90ba6
lukegriffith/CodeExamples
/Python/CBT Tutorials/animalLokup.py
418
3.6875
4
animals = ['bear', 'cat', 'dog', 'lion'] lookup = input('What animal are you looking for?') # This is outside the scope of the chatper I read, but the first entry in the list will return as a false item because 0 is false. Doh ! try: lookupResult = animals.index(lookup) except: lookupResult = False if lookupResu...
e0ea16edfcee4c25ce68e94b40263baf65031543
Xerazade/Coding-for-Beginners-Using-Python
/Dare you enter Castle Dragonsnax2.py
1,799
3.921875
4
import random print ("You are in a dark room in a mysterious castle.") print ("In front of you are four doors. You must choose one.") playerChoice = input("Choose, 1, 2, 3 or 4...") if playerChoice == "1": print ("You find a room full of treasure. You're rich!") print ("GAME OVER, YOU WIN!") elif playerC...
680001f4d800471e7fc33dcc4813a64b2f5bb4ce
gary391/CWH-PythonBeginner
/40_fStrings.py
278
4.375
4
# What is string formating # OPTION 1 - Using variables a = 'Gary' age = 50 # print("My name is %s. My age is %s"%(a, age)) # OPTION 2 - Using format # print("My name is {}. My age is {}".format(a, age)) # OPTION 3 - Using f string print (f"My name is {a}. My age is {2*25}")
a6aac16298b9655855916ddf17848634c273986f
kotavi/algorithms
/BubbleSortAlgorithm.py
784
4
4
import time import numpy as np rand_nums = np.random.randint(-100, 101, 20) start_time = time.time() # Algorithm's complexity - O(n^2) # In-place algorithm def bubble_sort_in_descending_order(array): threshold = len(array) - 1 while threshold > 0: for i in range(0, threshold): if array[i...
c378792c4c158a1253c04d369c4008cccda6f14b
firepenguindisopanda/Patient-Wait-time
/main.py
4,725
3.859375
4
#Definition of PatientData variables class PatientData: def __init__(self, key, value, value2): self.key = key self.value = value self.value2 = value2 def __repr__(self): return f'PatientData({self.key}, {self.value}, {self.value2})' #Definition of DoctorData variables class Doc...