blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
0356949de94e8f3f2ee4df73b5061ac4ac2ff373
conejo1995/pythonLabs
/join.py
98
3.8125
4
print("Enter two strings.") string1 = input() string2 = input() print(str.join(string1, string2))
502ec7abbd3d176e3d2b4747c94f62f10a044948
caul1flower/alg
/sorting_algorithms.py
1,833
4.09375
4
def selection_sort(arr): comparisons = 1 for i in range(len(arr)): comparisons += 1 min_idx = i comparisons += 1 for j in range(i + 1, len(arr)): comparisons += 2 if arr[min_idx] > arr[j]: min_idx = j arr[i], arr[min_idx] = arr[min_...
6a826557463d4d9561317d308f8e3aa0eb751884
rodrigoContreras/git-hello-world
/udemy/19_herencia.py
802
3.953125
4
class Operacion(): def __init__(self): self.valor1=0 self.valor2=0 self.resultado=0 def cargar(self): self.valor1=int(input("VAlor 1: ")) self.valor2=int(input("VAlor 2: ")) def mostrarResultado(self): return self.resultado class Suma(Operacion): # ...
81f056fb61a2e7816b2fc2138f8ed70de8378b87
odinfor/leetcode
/pythonCode/No251-300/no334.py
1,039
3.828125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2022/1/12 4:10 下午 # @Site : # @File : no334.py # @desc : 给你一个整数数组 nums ,判断这个数组中是否存在长度为 3 的递增子序列。 # 如果存在这样的三元组下标 (i, j, k) 且满足 i < j < k ,使得 nums[i] < nums[j] < nums[k] ,返回 true ;否则,返回 false 。 class Solution: def increasingTriplet(self, nums: list...
c613da93863e17c4aa8f709724f26919fc7670af
alex-dukhno/python-tdd-katas
/persistent_list_kata/day_1.py
2,423
3.703125
4
import unittest class List(object): def append(self, item): return Node(item, self) def head(self): pass def tail(self): pass def __repr__(self): return '' def __add__(self, other): return other class EmptyList(List): def head(self): return...
a432b8ddf376f5afcc1507c72e3582c758fe2f13
mejasiu/Python
/RocketGame12_3/rocketgame.py
1,993
3.8125
4
import sys import pygame from rocket import Rocket from actions import update def run_game(): """This will start the game play""" pygame.init() screen = pygame.display.set_mode((600,800)) pygame.display.set_caption("Rocket game") bg_color = (255, 255, 255) rocket = Rocket(screen) ...
683acabef95365418ab031237fe57588a1c243ec
Hoverbear/SPARCS
/week8/sequence.py
453
4.03125
4
# Number sequences so_far = [1, 1] while len(so_far) < 20: next_number = so_far[-1] + so_far[-2] # Last two numbers added together. so_far.append(next_number) # Add to the last spot of the list. print(so_far) # Can you make a function that returns a list with a size the user specifies? # For example: # sequen...
c0252f78d998566ab38dc90915c9fa5a45ffc1d2
Thalisson01/Python
/Exercício Python #068 - Jogo do Par ou Ímpar.py
697
3.75
4
import random vezes = 0 while True: n = int(input('Diga um valor: ')) es = str(input('Você que PAR ou ÍMPAR? [P/I]: ')) while es not in 'PpIi': print('Escolha inválida.') es = str(input('Você que PAR ou ÍMPAR? [P/I]: ')) sorteio = random.randint(1, 10) es.upper() print(sorte...
d0139a5b99917a8c950197293a309b3d70349460
rumitpatel9/rolling_dice_task
/game.py
540
3.5
4
import tkinter as tk from PIL import ImageTk, Image import random app = tk.Tk() app.title("Dice Rolling.") app.geometry("500x500") img = ImageTk.PhotoImage(Image.open(f"die{random.randint(1,6)}.PNG")) panel = tk.Label(image = img) panel.pack(side = "top", fill = "both", expand = "yes") def rolling_dice(): img = Im...
0ce0c53118ac3807f7b00c1f3145038671cd9a6e
LouisPerrott/Bright-Networks-Internship-Google-Software-challenge
/Bright Internship Software Development/google-code-sample-main/google-code-sample-main/python/src/video_player.py
11,630
3.84375
4
"""A video player class.""" from .video_library import VideoLibrary """There is something wrong with the module loading I was unable to fix this problem.""" class VideoPlayer: """A class used to represent a Video Player.""" def __init__(self): self._video_library = VideoLibrary() def number_of_...
1244ed54d5cfcc0774047a7d6f0cdc56c68dc3de
pmduc2012/test
/BT4 - Mutiplication Table.py
591
3.71875
4
'''print('\t\t\t\tMultipication Table') for i in range(1,10): print('%5d' % i,end="") print() print('-'*45) for j in range(1,10): for k in range(1,10): print ('%5d' % (j*k),end='') print() ''' def table(rows, columns): print('\t\tMultiplication Table') i = '' for column in range(1,column...
91f4f7258f9d434be751346a40d6af88cc7c1ff7
CoderWZW/leetcode
/排序算法/插入排序.py
952
3.671875
4
# -*- coding: utf-8 -*- l = [2, 15, 5, 9, 7, 6, 4, 12, 5, 4, 2, 64, 5, 6, 4, 2, 3, 54, 45, 4, 44] l_out = [2, 2, 2, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 7, 9, 12, 15, 44, 45, 54, 64] ''' 思想: 升序 不断的按顺序遍历,将当前值与前面的值依次比较,插入该值所在位置 ''' # 直接插入排序 # 思路:依次遍历,倒序遍历已经排好序的list,比较后如果目标值大于遍历值,则插入在该遍历值index+1的位置 def insert_sort(l): l_...
675e26fb1c3e9b504a22d4e825f7ef3e95c7a5fe
Aasthaengg/IBMdataset
/Python_codes/p03738/s573451867.py
215
3.828125
4
import math def calc(A, B) : a = math.log(A) b = math.log(B) if a > b : print('GREATER') elif b > a : print('LESS') else : print('EQUAL') A = int(input()) B = int(input()) calc(A, B)
2756c37078f1ad2f3e3de281133e38ea47d6f4da
Ivanpaun/qa_first_group
/my_notepad/mainWindow.py
1,820
3.578125
4
import tkinter as tk import tkinter.scrolledtext as tkst import tkinter.font as tkFont from tkinter import messagebox class App: def __init__(self): self.win = tk.Tk() self.customFont = tkFont.Font( family="Helvetica", size=14 ) frame1 = tk.Frame( master=sel...
3cf88f244b057415c6fdd409999c97f7cef857c5
icculp/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/0-square_matrix_simple.py
214
3.609375
4
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): new_matrix = [None] * len(matrix) for i in range(len(matrix)): new_matrix[i] = list(map(lambda x: (x ** 2), matrix[i])) return new_matrix
0219e70ccc08682ce0b54675c2b4d96b3d5a5ea7
hustqb/NNLearningLog
/example/LearnCNN/cifar_10_cnn.py
3,707
3.625
4
# coding=utf-8 """ Train a simple deep CNN on the CIFAR10 small images dataset. """ from __future__ import print_function import keras from keras.layers import Conv2D, MaxPooling2D from keras.layers import Dense, Dropout, Flatten, Input from keras.models import Model from keras.preprocessing.image import ImageDataGener...
91fadbb3415fa9af79b647fa70f9d1aba3321a15
Esmaaa/cis024c_springi2021
/classwork/test_cmdline.py
387
3.765625
4
import sys if len(sys.argv) != 3: print("Please use the following syntax:") print("python test_cmdline.py <number1> <number2>") sys.exit(-1) try: n1 = float(sys.argv[1]) n2 = float(sys.argv[2]) except ValueError as error: print("Please enter numerical values for the numbers") sys.exit...
cda5b08e7f04e2bbf9427b0287b7a577fb1b172e
Samkiroko/python_100_days
/.history/3_of_100_20210409165424.py
1,786
4.5
4
# Write a program that works out whether if a given year is a leap year. # A normal year has 365 days, leap years have 366, with an extra day in February. # The reason why we have leap years is really fascinating, # this video does it more justice: # 🚨 Don't change the code below 👇 year = int(input("Which year do y...
4100a4db6fe04d9305f0d559716d929c25243782
KU-ALPS-15/minhyeok
/4949_균형잡힌세상.py
1,319
3.59375
4
#!/usr/bin/env python # coding: utf-8 # In[6]: class stack: def __init__(self): self.items = [] def empty(self): return not self.items def push(self, item): self.items.append(item) def pop(self): if not self.items: return -1 else: retur...
f4b146857e56224c068844105b3848dca70bc6d5
rajeshsvv/Lenovo_Back
/1 PYTHON/7 PROGRAMMING KNOWLEDGE/38_Raising_Exceptions.py
461
3.984375
4
class CoffeeCup: def __init__(self,temperature): self.__temperature=temperature def DrinkCoffe(self): if self.__temperature>85: # print("Coffee is too hot") raise Exception("Coffee is too hot") elif self.__temperature<65: # print("Coffee is too cold") ...
17d74cc432607277ee74ed8d60ad00810e8d2e2a
Gp32Prog66/Python-Projects
/Python Projects/Starting Out With Python Projects/Chapter 2/Mass And Weight/Mass_And_Weight.py
446
4.3125
4
print('This Program Calculates Weight and Mass') #Ask For mass = int(input('What is the mass of the object?')) #Calculate Mass of The Object weight = mass * 9.8 #Determining The Weight of the Object if weight >= 500: print('This Object is too Heavy') print(weight) elif weight <= 100: print...
7ccb3ddd02966ab7a2735be1705e66bd0ef56bdb
Davidxswang/leetcode
/medium/150-Evaluate Reverse Polish Notation.py
1,992
4.03125
4
""" https://leetcode.com/problems/evaluate-reverse-polish-notation/ Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Note: Division between two integers should truncate toward zero. The given RPN expressio...
dff19684d6e91cf2d431b675df9160b678b58c18
DanJamRod/assignment-1-DanJamRod
/q5.py
2,177
4.09375
4
def awesome_word(word): """ Finds if word is an awesome word (at least one identical non-overlapping word couplet and one xyx type substring) """ flag = False # Sets flag initially to False for i in range (len(word)-2): # Runs the program for every letter except the last two (last two letters have no pa...
4772d38c27610f6d84564b74c3403dbff9b09a3d
DurbekRaxmonqulovich/begin
/13-пример.py
135
3.703125
4
pi=3.14 r1=int(input()) r2=int(input()) s1=pi*r1**2 s2=pi*r2**2 s3=pi*(s1-s2) print('S1=',s1) print('S2=',s2) print('S3=',s3)
faeff6ef2cd57af785bf24ceb1a2e93ff3e6a9ef
deladan/moocpython
/corriges2rst/fichiers/toc_convertRST.py
2,672
3.609375
4
#!/usr/bin/env python3 #!python3 """ Script adapté à partir d'un modèle mis à dispo sur le Mooc Python 3 Script de départ à compléter et à optimiser... Commentaires sur le script en cours et toutes suggestions bienvenues ;) Permet de regrouper les fichiers txt des corrigés par semaine sur un seul fichier rst Hypothèse...
04a18ec873f60d8fd8a971a6c3c248ef1a40da71
manas3789/Hacktoberfest
/Beginner/03. Python/LensSlice.py
722
4.5
4
""" Len's Slice You work at Len’s Slice, a new pizza joint in the neighborhood. You are going to use your knowledge of Python lists to organize some of your sales data. Concepts tested here are List SLicing,Sorting and Zipping. """ toppings=['pepperoni', 'pineapple', 'cheese', 'sausage', 'olives', 'anchovies', 'mushro...
3498c21480ac6ef46e8a096edfb52566364454f6
JaD33Z/ExercismIO-solutions
/python/word-count/word_count.py
195
3.859375
4
import re def count_words(sentence): str = re.findall(r"[a-zA-Z0-9]+(?:'\w+)?", sentence.lower()) freq = [str.count(word) for word in str] return dict(zip(str, freq)) return str
e8dbc16833a37225f5ad7361efecff3c09c10209
Gumbeat/test_tasks
/9/main.py
829
3.875
4
def biggest_substr(s1, s2): if len(s1) > len(s2): s1, s2 = s2, s1 i = 0 max_substr = '' while i < len(s1): i2 = 0 while i2 < len(s2): if s1[i] == s2[i2]: j = i substr = '' while j < len(s1) and i2 < len(s2) and s1[j] == ...
d5ff290c9445ddcea0f68ad9df67fe49fa23b642
isakss/Forritun1_Python
/employee.py
1,240
3.78125
4
class Employee(object): def __init__(self, employee_name = ""): self._employee_name = employee_name def get_name(self): return self._employee_name class HourlyEmployee(Employee): EXCESS_RATE = 1.5 def __init__(self, employee_name = "", hourly_wages = 0.0): super().__init...
89988b28733a7ddb21a5ecc19fc3d59c7279cb32
GuiRodriguero/pythonFIAP
/2 Semestre/Aula17/Assassinato.py
1,215
4.09375
4
#Lista de Perguntas perguntas = ["Telefonou para a vítima? ", "Esteve no local do crime? ", "Mora perto da vítima? ", "Devia para a vítima? ", "Já trabalhou com a vítima? "] def perguntar(perguntas): respostas_positivas = 0 #Passa por todas as perguntas for x in range(len(perguntas)): ...
b5fb13c1999c5cb6546c35e9a5b99a5cf21ffe89
toroleyson/data-prework
/1.-Python/6.-Rock–Paper–Scissors/Problem 6 - Arnoldo Leyson.py
4,826
4.6875
5
Python 3.6.8 (v3.6.8:3c6b436a57, Dec 24 2018, 02:04:31) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license()" for more information. >>> ##1. Import the choice function of the random module. >>> import random >>> >>> ##2. Create a list that includes the 3 p...
b6381e04f959ffcbe3d9b6db904e868bf12d376f
raoulsuli/Computer-Architecture
/Python-Parallel-Marketplace/tema/marketplace.py
5,599
4.21875
4
""" This module represents the Marketplace. Computer Systems Architecture Course Assignment 1 March 2021 """ from threading import Lock, currentThread class Marketplace: """ Class that represents the Marketplace. It's the central part of the implementation. The producers and consumers use its methods con...
4972e1b64a19b150ed65d258151bf76a96e3eac0
daniel-reich/ubiquitous-fiesta
/p94KFBXAzJ3ZxmFmw_19.py
106
3.71875
4
def ascii_capitalize(txt): return ''.join(i.upper() if ord(i) % 2 == 0 else i.lower() for i in txt)
a9d862d5a0de13bd4c4b9eb5550afa8ec9ab88b3
imji0319/myProject
/pro1/course1/for_ex01.py
744
3.90625
4
''' Created on 2017. 9. 29. @author: jihye ''' # 별 그리기 # -*-coding : utf-8 -*- import turtle def draw_star(x,y,size=50, pencolor='black'): mypen=turtle.Turtle() mypen.showturtle() mypen.color(pencolor) mypen.penup() mypen.goto(x,y) mypen.pendown() mypen.begin_fill() for...
c85ebc0cf242d3b61b75f621eb328f394ef18152
analaura09/pythongame
/p8.py
171
3.859375
4
medida = float(input(' Digite uma distancia em metros: ')) cm = medida * 100 mm = medida * 1000 print(' A medida de {}m corresponde a {}cm e {}mm'.format(medida,cm,mm))
70654e9efc3f9c4b8ac55b45657c4d145cb6815f
nivethida/TextMining
/RegularExperssions/regularexp.py
7,238
4.40625
4
# -*- coding: utf-8 -*- ''' Identifiers: \d = any number \D = anything but a number \s = space \S = anything but a space \w = any letter \W = anything but a letter . = any character, except for a new line \b = space around whole words \. = period. must use backslash, because . normally means any character. Modifiers: ...
9aebfa0aba8a6b2c519f7ebb5bfefb8fe0a6d8dc
raytwelve/LeetCode
/Medium/Find the Duplicate Number.py
1,201
3.859375
4
''' https://leetcode.com/problems/find-the-duplicate-number/ Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. Note: You must not modify the array...
c2481e4b9f73ba61ba32518f359ac12e551fb82b
jakebaz/Python-Library-Sytem
/source_code.py
15,824
3.921875
4
import random class Books(): #Initialize - create book details def __init__(self, title, author, year, copies, publisher, pub_date): try: #error handling to ensure the user enters the correct details and data types self.title = title self.author = author self.year = ...
c33e7e341130d67149fa86c7c66d0aa5c1d2fa58
zingzheng/LeetCode_py
/26Remove Duplicates from Sorted Array.py
658
3.59375
4
##Remove Duplicates from Sorted Array ##Given a sorted array, remove the duplicates in place such that ##each element appear only once and return the new length. ##Do not allocate extra space for another array, ##you must do this in place with constant memory. ## ##2015年6月30日 AC ##zss class Solution: # @param {in...
f7e2042c9fe30af15948a609d10d06b56dcd1bff
40205331/algorithmsCW
/pythonCW.py
28,085
3.640625
4
import sys # set colours for pieces Black = '\033[94m' Red = '\033[91m' End = '\033[0m' # create classes for pieces on the board class hashtag(object): def __repr__(self): return hashtag() def __str__(self): return Black + "| # |" + End class atsign(object): def __repr__(self): return atsign() def __str...
024a53ff5f24fc6c59229372e343f8b98d0eafc3
forstupidityonly/holbertonschool-higher_level_programming
/0x06-python-classes/5-square.py
933
4.21875
4
#!/usr/bin/python3 """my square mod""" class Square: """define a square""" def __init__(self, size=0): """ make a square make a area use propery to get size use setter to set value raise int and 0 check """ self.__size = size...
1c3cd2ea993d898ad7732b9104dec906516b9b44
UX404/Leetcode-Exercises
/#762 Prime Number of Set Bits in Binary Representation.py
1,367
3.96875
4
''' Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation. (Recall that the number of set bits an integer has is the number of 1s present when written in binary. For example, 21 written in binary is 10101 which has 3 se...
368797e4e617ab2275bd6f2c318557e4e9a8f194
RionelxSlovesky/learning-python
/CODE/Loops/ForLoopWithMultipleLists.py
122
3.765625
4
names = ["Ahmed","Omar","Salim","Adnan"] email = ["gmail","hotmail","yahoo"] for i,j in zip(names,email): print(i,j)
5fdc0a7346ce727d9be9fa85f23f3ea624a9a674
zsmountain/lintcode
/python/dfs/1637_tree_problem.py
2,328
3.828125
4
''' Given a tree of n nodes. The ith node's father is fa[i-1] and the value of the ith node is val[i-1]. Especially, 1 represents the root, 2 represents the second node and so on. We gurantee that -1 is the father of root(the first node) which means that fa[0] = -1. The average value of a subtree is the result of the s...
f9a7cca7c091edfe1231db8026b104c55657a574
dpaklin/Python_basic
/lesson05/dz02.py
562
4.125
4
# 2. Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк, # количества слов в каждой строке. with open('txt/file5_2.txt') as f: text = f.read().splitlines() for index, value in enumerate(text): number_of_words = len(value.split()) print('В ст...
8a64c9f59aa787fa15f2aa526651a4c78eede862
febel/Python
/transposition_cipher_encryption.py
381
3.71875
4
def main(): monMessage= 'Bienvenue en CDAISI' maCle=8 ciphertext = encryptMessage(maCle,monMessage) print ciphertext + '|' def encryptMessage(key, message): ciphertext = ['']*key for col in range(key): pointer = col while pointer < len(message): ciphertext[col] += message[pointer] pointer += key ret...
7e739ca99b41bf2097499ee6715009062e816013
tatiaris/random-python-scripts
/free_folk.py
1,467
3.703125
4
import time from math import factorial def print_grid(g): for r in g: print(r) print() def to_tuple(g): return tuple([tuple(r) for r in g]) def flip(g): temp = [['']*len(g[0]) for i in range(len(g))] temp2 = [['']*len(g[0]) for i in range(len(g))] temp3 = [['']*len(g[0]) for i in rang...
7960f64d9be277e07ba5bec60e33cd2dffb5c3da
brianchiang-tw/HackerRank
/Python/Regex and Parsing/Validate Hex Color Code/validate_hex_color_code.py
788
3.640625
4
import re def print_color_code( line_str ): if '{' in line_str or '}' in line_str: return regex = r'#(?:[0-9a-fA-F]{3}){1,2}' pattern = re.compile(regex) colors = re.findall( pattern, line_str ) if colors is not None: for color_code in colors: print( str(colo...
58058d47558c9154b8a2633258e2f7f85ed03ee5
XinyiF/Algorithms
/Python/Math/Reverse_Integer.py
385
3.6875
4
class Solution(object): def reverse(self, x): flag=False if x<0: flag=True x=str(x) if flag: x=x[1:] res=x[::-1] if flag: res=-int(res) else: res=int(res) if -2 ** 31 < res < 2 ** 31 - 1: retu...
9f9aa4b4aa4cc6b293043e036b2a8a73ab2ec07b
qzhou0/SoftDevSpr19WS
/temp/util/dbOperator.py
1,237
3.859375
4
import sqlite3 #enable control of an sqlite database import csv #facilitates CSV I/O #========================================================== DB_FILE="./data/<intended_name>" #<SUBSTITUTE FILE NAME> db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create c = db.cursor() ...
44aaacbaee50704a22c757f4a4f7935f7ecbe477
hasnain-khan1/pandas_project
/most_freq_words.py
1,078
3.765625
4
from collections import Counter while True: print("Available Years and Registrar Name \n1974,1976,1980,1983,1987,1991 \nschmidt , kohl\n") x = input("Enter the Registrar Name or Year: ") years = ['1974', '1976', '1980', '1983', '1987', '1991'] registrar_name = ['schmidt', 'kohl'] if x in...
05fc706f408b218e160ebd840369c6b62a1ff89b
yoliskdeveloper/basic_python
/if_statement.py
1,444
4.0625
4
a = 33 b = 209 if b > a: print('b lebih besar dari a') a = 33 b = 33 if b > a: print('b lebih besar dari a') elif a == b: print('a dan b nilainya sama') a = 200 b = 33 if b > a: print('b lebih besar dari a') elif a == b: print('a dan b nilainya sama') else: print('a lebih besar dari b') a ...
6e6a4b8b275ab90703cbff6d2154c695c59c3259
136772/MyPython
/Mycode/learn/2.py
1,506
3.859375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' @author:JaNG @email:136772@163.com ''' # def show(*args,**kwargs): # print(args,type(args)) # print(kwargs,type(kwargs)) # # l = [11,22,33,44] # d = {'k1':'v1','k2':'v2'} # # show(*l,**d) # s1 = '{} is {}' # l = ['alex','sb'] # result = s1.format(*l) #如果传入列...
662fac9793b71fd687f22af38c31aa40eb6b0873
nileshmahale03/Python
/Python/PythonProject/6 TypeConversion.py
569
3.875
4
""" Type conversion is Python: Implicit boolean automatically upgrades to integer integer automatically upgrades to float Explicit """ #1. a = True b = 1 c = a + b print(c) #2. a = 135 b = 10.5 c = a + b print(c) print(type(c)) #3. a = "123" b = 5 c = int(a) + b print(c) #4. str = "NILESH MAHALE" l = list...
b8bdaa29b675f40f8b8bf9d74247fcc92e6ff664
fvargaso174/CEvidenciasICCSO
/linear_reg.py
579
3.578125
4
import pandas as pd from sklearn.cross_validation import train_test_split from sklearn.linear_model import LinearRegression import Matplotlib.pyplot as plt dataset = pd.read_csv(’Salary_Data.csv’) X = dataset.iloc[:,:-1].values Y = dataset.iloc[’:,1].values X_train, X_test, y_train, y_test = train test split(x, y, test...
20d2d1e869e663722c1c34d430de0fa019b174d8
Waynezhai/03_python_hm
/03_循环语句/hm_11_printFunction_littleStar.py
429
3.796875
4
#!/usr/bin/python #coding=utf-8 """ 1、输入十行小星星,第一行一个,第二行2个,第三行三个…… 2、小星星居中显示 3、使用循环嵌套处理 4、python2的print后不换行不空格的方法参考:https://segmentfault.com/q/1010000000095970 """ from __future__ import print_function row = 1 while row <= 10: col = 1 while col <= row: print("*", end = "") col += 1 print() row += 1
561d244f9473d7801c52ee4116ea32c9c2211d94
da-ferreira/uri-online-judge
/uri/1221.py
356
3.921875
4
from math import sqrt, floor casos = int(input()) for i in range(casos): numero = int(input()) piso_sqrt = floor(sqrt(numero)) divisores = 0 for j in range(1, piso_sqrt+1): if numero % j == 0: divisores += 1 if divisores == 1: print('Prime') ...
296883e22e1b1112a8942cb64b654fab9120ac13
jack-mars/selemium_webdriver
/stringmethodspart1.py
361
4.28125
4
""" Accessing characters in a string Index starts from zero """ first = "nyc"[0] print(first) city = "sfo" ft = city[0] print(ft) """ len() lower() upper() str() """ print("***********") stri = "This is a Mixed CASE" print(stri.lower()) print(stri.upper()) print(len(stri)) print(stri + "2") print(stri + str(2)) #Conca...
d5f0ff064265d39cf182dad2dbaeadc2e4b3fe7a
Nikita-bsu/Something
/Python/Book Projects/Square_for_turtle.py
460
3.65625
4
import turtle bob = turtle.Turtle() # # def square(t, length): # for i in range(4): # t.fd(length) # t.lt(90) # print(square(bob, 100)) # def polygon(t, length, n): # for i in range(4): # t.fd(length) # t.lt(360 / n) # # print(polygon(bob, 100, 4)) def polygon(t, length, n)...
bf5b896f0ae198a4f78f6a1199596f437922e3a8
nemzutkovic/Carleton-University-CS-Guide
/COMP 1405/Assignment 3 (100)/prime.py
171
3.796875
4
def isprime(x): if x == 1: return False for i in range(2, x): if x % i == 0: return False return True for p in range(1,101): if isprime(p) == True: print(p)
9c9558a86c63ec6c01a986c2a69464d05c559603
VishalDeoPrasad/HackerRank-Python
/Mini-Max Sum.py
131
3.59375
4
def miniMaxSum(arr): arr.sort() #print(arr) print(sum(arr[:4]), sum(arr[-4:])) arr = [1,5, 10, 3,5,7,9] miniMaxSum(arr)
f92820421da56840a10094e0b2615b3a74f9301e
emmy-kech/Day-4--Home
/binary_search.py
1,054
3.640625
4
class BinarySearch(list): def __init__(self, a, b, *args): list.__init__(self, *args) self.list_length = a self.step = b end = self.list_length * self.step for i in range(self.step, end+1, self.step): self.append(i) @property def lengt...
455cb39957e4298eff5cff30196fabbd54d4c6b8
astral-sh/ruff
/crates/ruff/resources/test/fixtures/flake8_future_annotations/no_future_import_uses_union_inner.py
184
3.5
4
def main() -> None: a_list: list[str | None] = [] a_list.append("hello") def hello(y: dict[str | None, int]) -> None: z: tuple[str, str | None, str] = tuple(y) del z
654cdb68d7728faaf52e4e903e96f92eab947d3f
llwsykll/leetCode
/palindromeNumber/paNu.py
300
3.5625
4
class Solution: def isPalindrome(self, x: 'int') -> 'bool': if x<0: return False re = 0 num = x while(num>0): re = re*10 + num%10 num = int(num/10) if re==x: return True else: return False
885e8d1b693ff90a11425c1e5eb2c23bc3e144f8
Evaldo-comp/Python_Teoria-e-Pratica
/Livros_Cursos/Udemy/funcoes/funcoes_parametros.py
3,153
4.0625
4
# Algumas funções precisam de dados para executar as operações presentes no seu corpo # Esses dados são fornecidos pelo usuário quando chamamos essa função e são chamados de argumentos #Exemplo de função com processamento fixo def impar_par(): for i in range (1, 11): if i %2 == 0 : print(f' O...
89a8b976b36d6690ee320128f0f4360a0731260a
Terry-Xiang/XZY
/exchange rate.py
957
3.546875
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ 编者:XZY 日期:2020.2.15 功能:实现美元与人民币汇率转换 """ #提示用户输入基本信息 print('美元货币单位是USD,人民币的货币单位是CNY') print('汇率为直接标价法,CNY/USD,其含义为 1 美元 = ?人民币') print('汇率查询参考网站:https://www.boc.cn/sourcedb/whpj/') print('请注意大小写') exchange_rate = input('请输入今日汇率:') #汇率标价为 CNY/USD currency = in...
6a4afa47685b85557c463c988beeedd7d87606f0
tauCourses/ML_hw4
/network.py
8,094
3.796875
4
""" network.py """ import random import numpy as np import math import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import os import sys dir_path = repr(os.path.dirname(os.path.realpath(sys.argv[0]))).strip("'") class Network(object): def __init__(self, sizes): ""...
3a0a91539adce320648554b196702283b186c937
AlexeyZavar/informatics_solutions
/4 раздел/Задача I.py
793
3.859375
4
# Напишите программу, которая по данному числу n от 1 до 9 выводит на экран n флагов. Изображение одного флага # имеет размер 4×4 символов, между двумя соседними флагами также имеется пустой (из пробелов) столбец. Разрешается # вывести пустой столбец после последнего флага. Внутри каждого флага должен быть записан его ...
d6ae9bb82f577c0a4235f2fbffdb082f79f5b98c
MasterSlavein/Test_task
/Advanced_6.py
2,878
3.921875
4
# К реализованному классу Matrix в Домашнем задании 3 добавить следующее: # 1. __add__ принимающий второй экземпляр класса Matrix и возвращающий сумму матриц, если передалась на вход матрица # другого размера - поднимать исключение MatrixSizeError (по желанию реализовать так, чтобы текст ошибки содержал # размерность 1...
f0dcf08ab9eac3c3353aaaf60b66148701208be6
doga44/Group-Project-Python
/pythongroupproject.py
10,349
3.765625
4
#In this program, we use yahoo finance. To run yahoo finance, #you need to install the tool in terminal/command. #Install fix_yahoo_finance using pip: # $ pip install fix_yahoo_finance --upgrade --no-cache-dir import pandas as pd from pandas_datareader import data as pdr import fix_yahoo_finance as yf yf.pdr_override...
b29d367d152aa069e86a80d403972672b2dd518c
amreyesp/ProgrammingExercises
/sorting/bubbleSort.py
1,706
4.28125
4
"""Sorting: Bubble Sort""" """ Considering the Bubble sort algorithm, given an array of integers, sort the array in ascending order using it. Once sorted, print the following three lines: 1.Array is sorted in numSwaps swaps., where numSwaps is the number of swaps that took place. 2.First Element: firstElement, where f...
594ce006134ac13b65b5dd65b4a410a7c652e06d
DidiMilikina/DataCamp
/Data Scientist with Python - Career Track /24. Machine Learning with Tree-Based Models in Python/03. Bagging and Random Forests 0%/02. Evaluate Bagging performance.py
911
3.640625
4
''' Evaluate Bagging performance Now that you instantiated the bagging classifier, it's time to train it and evaluate its test set accuracy. The Indian Liver Patient dataset is processed for you and split into 80% train and 20% test. The feature matrices X_train and X_test, as well as the arrays of labels y_train and ...
7164bbff0d08adc744d5fb0ce166ec1885b122cc
jorzel/codefights
/arcade/intro/absoluteValuesSumMinimalization.py
542
3.671875
4
""" Given a sorted array of integers a, find an integer x from a such that the value of abs(a[0] - x) + abs(a[1] - x) + ... + abs(a[a.length - 1] - x) is the smallest possible (here abs denotes the absolute value). If there are several possible answers, output the smallest one. Example For a = [2, 4, 7], the output ...
b8fa2494b1e3e057110b4b96bf0beca1a233a1a9
rahulyhg/MultilingualSourceCode
/猜你心中字母/demo.py
1,603
3.671875
4
#使用python语言来开发 猜你心中字母 print('Content-type: text/html\n') import cgi def showSelectHtml(zm,action): s1="";s2="";s3="";sData="";c=""; for i in range(0,len(zm)): s=zm[i:i+1] if (i+1)%3==1: s1=s1 + s; elif (i+1)%3==2: s2=s2 + s; else: s3=s3 + s; sData="&s1="+s1+"&s2="+s2+"&s3="+s3; c='第'+ str(action) ...
1ab91a728501ce8e6d43c16caf7fbbc5b1cfb563
DheerajMandvi9/Python-programs-new
/menu driven readfile.py
1,113
3.875
4
ch='Y' while (ch=='Y' or ch=='y'): print("Enter 1 : count words:") print("Enter 2 : count line:") print("Enter 3 : count alphabets:") print("Enter 4 : exit:") opt=int(input('enter your choice:')) if opt==1: f=open("Atoms.txt","r") linesList=f.readlines() count=0 f...
7dd3b0b494e5d769c9412f0c595527e9fa7b86d5
psssolo/Python
/2.py
494
3.875
4
""" This program takes a Tic-Tac-Toe game pattern (9 chars of [xo.]), and checks if there is a winner. """ import re def is_winner(game_pattern): return (re.search(r'^(.{3})*(x{3}|o{3})', game_pattern) or re.search(r'^.{0,2}([xo])..\1..\1', game_pattern) or re.search(r'^([xo])...\1...\1|....
2707d1df73ddc2d26832fe1b5065edecb900cbf1
FreedomFrog/pdxcodeguild
/python/guess_the_number.py
3,134
3.734375
4
import random def get_user_guess(): while True: guess = input('guess the number: ') if guess.isdigit(): break return guess def towards_target(cor_num, usr_num, last_guess): guess_diff = abs(cor_num - usr_num) last_guess_diff = abs(cor_num - last_guess) if guess_diff ...
60b311d139d10942596baf9c9c067d50453bbab0
vsdrun/lc_public
/co_fb/844_Backspace_String_Compare.py
1,398
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ https://leetcode.com/problems/backspace-string-compare/ Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. Example 1: Input: S = "ab#c", T = "ad#c" Output: true Explanation: Both S and T b...
adde802146d98612b2efded9793f157e8093ed51
DenisPecherin/Lab-2-
/1.py
1,915
3.953125
4
import timeit # Сравните время вычисления 35-го числа Фибоначчи при помощи формулы Бине, # итерационной формулы, метода «разделяй и властвуй», метода нисходящего динамического программирования, # метода восходящего динамического программирования. # Формула Бине code_to_test1 = """ from pervoe_zadanie1 import f1 """ p...
a2ce35d9754d48be36973e811b051ea2524178cb
sbezas/AdventOfCode2020
/Day 02/Day02.py
1,544
3.875
4
from sys import argv script, input_file = argv passwordlist = [] validcount = 0 i=0 with open(input_file, "r") as f: passwordlist = [current_place.rstrip() for current_place in f.readlines()] for i in passwordlist: #Locate positions ## Minimum value position if i[1] == "-": MinEndPos = 0 MinLength = 1 MinV...
9a10a6b8a563dc09a41541d54ec5a3a2162516d1
KULDEEPMALIKM41/Practices
/Python/Single Py Programms/count_substr_diffrent_maner.py
250
3.71875
4
a = 'bcacacacacac' def count_substring(string,substr): count1 = 0 for i in range(len(string)-len(substr)+1): if string[i:i+len(substr)] == substr: count1+=1 count2 = string.count(substr) return count1,count2 print(count_substring(a,'aca'))
bb25603e22ada6aa76a5f9ee979100afdc63671e
Varasekie/Py_homework_proj
/src/learning_1/add_plus.py
1,994
3.796875
4
class Changed(int): def __add__(self, other): ####继承了int类里面的sub方法,因此不会无限递归 return int.__sub__(self, other) def __sub__(self, other): return int.__add__(self, other) a = Changed(3) b = Changed(4) print(a - b) a = [1, 2, 3, 4] c = {'key1': 'value1'} d = 'Varasekie' b = iter(a) print(ne...
b1d686e61cb21dedd5a2d662809ad98658c89f55
Emmetttt/euler
/python/30.py
291
3.546875
4
def powers(n): n = str(n) i=0 k=0 while i < len(n): k = k + int(n[i])**5 i+=1 if k == int(n): return True else: return False i=2 fifth = [] while i < 999999: if powers(i) == True: fifth.append(i) i+=1 print(sum(fifth))
10daeee093c90f6dfb797e820bd1227edb5f4816
MisaelAugusto/computer-science
/programming-laboratory-I/vdwb/bubble.py
339
3.75
4
# coding: utf-8 # Aluno: Misael Augusto # Matrícula: 117110525 # Problema: Bubblesort def bubblesort(dados): update = True j = 0 while j < len(dados) - 1 and update: update = False for i in range(len(dados) - 1): if dados[i] > dados[i + 1]: dados[i], dados[i + 1] = dados[i + 1], dados[i] update = Tr...
587ec05bd899fda23b5cd09346a1f754804aaf2b
smilejay/python
/py2013/rename_files.py
669
3.59375
4
# -*- coding: gb2312 -*- ''' Created on 2013-1-27 @author: Jay Ren @module: rename_files @note: rename files in a Windows system. ''' import os import re path = "C:\\Users\\yren9\\Documents\\temp" def rename_files(): prefix = "\[电影天堂-www\.dygod\.com\]" for file in os.listdir(path): if os.path.isfi...
dfa746dfd6410142c039d219f5f99def723ddb22
mipmo/pricecal
/pricecal.py
3,305
4
4
# Import things import sys import os # Begin the KeyboardInterrupt loop try: # Introduction os.system('clear') print('PRICE CALCULATOR') print('Enter the prices and weights or amounts of products that need to be compared. Enter as many values as necessary.') print('If you are done, enter 0 as the ...
644a43bcc71edf13627ec75b8fbd9f0cba530e37
mishrakeshav/Competitive-Programming
/binarysearch.io/321_level_order_binary_search_tree_to_linked_list.py
753
3.578125
4
# class Tree: # def __init__(self, val, left=None, right=None): # self.val = val # self.left = left # self.right = right # class LLNode: # def __init__(self, val, next=None): # self.val = val # self.next = next class Solution: def solve(self, root): stack = [...
32e33b8d3172e126dc808024bbc9bf8c1525bbea
Gitus-Maximus/Skills
/regex/ex13.py
247
4.15625
4
import re """ Match any word followed by a comma. The example below is not the same as re.compile(r"\w+,") For this will result in [ 'me,' , 'myself,' ] """ pattern = re.compile(r"\w+(?=,)") res = pattern.findall("me, myself, adn I") print(res)
afc75b7e6e0087ef9b79f90a629227bb4556c71a
mtfgqd/PythonDemo
/pythonFundation/BasicLearn/DataType.py
2,480
4.21875
4
# 字符串 字符串是以单引号'或双引号"括起来的任意文本 # 如果字符串内部既包含'又包含" 可以用转义字符\来标识 string = 'I\'m \"OK\"!' print(string) # 转义字符\可以转义很多字符,比如\n表示换行,\t表示制表符,字符\本身也要转义,所以\\表示的字符就是\ print('I\'m ok.') print('I\'m learning\nPython.') # 如果字符串内部有很多换行,用\n写在一行里不好阅读,为了简化,Python允许用'''...'''的格式表示多行内容 print('''line1 line2 line3''') # 多行字符串'''...'''还可以在前面...
2cb8b272c051b1471063aaa1312f7f45dc5c20b0
jyosh30/Python
/Python_Day3_Project1.py
610
4.4375
4
# BMI Calculation Weight = int(input("Enter the weight : ")) # weight in Kgs Height = int(input("Enter the Height in cms :")) # Height in centimeters Height = Height / 100 # converting cms into metres BMI = Weight / (Height * Height) print(float(BMI)) if BMI < 16.0: print("Severly Underweight") elif BMI >= 16.0...
684faec1bfb2df0e9ca13e10574d030e5529327a
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/79_2.py
1,723
3.984375
4
hashlib.sha3_384() in Python With the help of **hashlib.sha3_384()** method, we can convert the normal string in byte format is converted to an encrypted form. Passwords and important files can be converted into hash to protect them with the help of hashlib.sha3_384() method. > **Syntax :** hashlib.sha3_3...
08a75211bce72c9e10800aaf79bdd2e8108de3ee
yurimalheiros/IP-2019-2
/lista1/marcosvinicius/questao2.py
175
3.75
4
base= float ( input ("digite a largura do retangulo")) altura = float (input ("digite a altura do retangulo")) area = base * altura print (" a area do retangulo e",area)
d8f78ad4b3e1500420ef1eef5039f06d972a0af8
pyplusplusMF/202110_68
/_68semana06clase19POOEjemplo2.py
1,944
4.09375
4
# Clase del jueves 19 de Junio # Ejemplo de la clase círculo # Realizar una clase circulo que tenga como atributos el radio # los métodos serán el perimetro y el area import math class Circulo: # definir el constructor def __init__ (self, radio = 1): self.radio = radio # Método para obtener el...
8d40af814e242f449abd93efe151b3351ecd060f
tt66/LintCode
/K个最近的点-612-2.py
517
3.609375
4
import heapq '''def s(point,origin): return ((point[0]-origin[0])**2+(point[1]-point[1])**2,point[0],point[1])''' '''import heapq nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] print(heapq.nlargest(3, nums)) # Prints [42, 37, 23] print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]''' def ksorted(points,origin,...
b5570fb148d0631725e3bc2aa35b2375f2198a0d
malaga95/magazyn
/command/commands.py
4,040
3.515625
4
import sys class Account: def __init__(self): self.account = [] # self.add_line() #def add_line(self): # value = sys.argv[1] # comment = sys.argv[2] # self.account.append(value) # self.account.append(comment) def add_to_file(self, value, comment): with open...
1a39b843dae5da536da1cb6672d36e4788b2a491
VaskarNath/ml-projects
/Assignment 3/q3_1.py
9,992
3.59375
4
''' Question 3.1 Skeleton Code Here you should implement and evaluate the k-NN classifier. ''' import data import numpy as np # Import pyplot - plt.imshow is useful! import matplotlib.pyplot as plt from statistics import mode from sklearn.model_selection import KFold from scipy import stats as s from skl...
ba8d6b83b805237207c631e63e757c029530e506
Yojanpardo/python
/while_loop.py
495
3.890625
4
# -*- coding: utf-8 -*- import random def main(): number_found = False random_number = random.randint(0,20) while not number_found: number_try = int(raw_input('cual crees que es el numero?')) if number_try==random_number: print('felicidades, encontró el numero') number_found=True elif number_try<rando...
b48d95ae029befef251784fa9c0d660f129dea6a
LounissartHK/pdsnd_github
/bikeshare.py
9,310
4.40625
4
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name o...
9f3fe0782f0f316b207f36ffcaa0d3bc48fbaf9d
Frann2807/Mi-primer-programa
/adivina_numero/Adivina el numero ganador.py
167
3.875
4
numero_ganador = 35 numero_usuario = int(input("Adivina el numero: ")) if numero_ganador == numero_usuario: print("Has adivinado") else: print("Has perdido")
449bba69ba31628fd749c3949240293273687bd0
green-fox-academy/fehersanyi
/python/expressionsandcontrollflow/animal-legs.py
162
3.859375
4
chicken = input('how many chickens live in the farm? ' ) pigs = input('how any pigs live in the farm? ' ) print'there are ', chicken * 2 + pigs * 4, 'legs total'