blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
fa1c3a66e06d4a647d6085cdec7fe9b646d4cb01
Dengjiongshen/Python3Learning
/Python1_终止和跳出循环.py
625
3.9375
4
#终止循环和跳过循环 ''' a=True while a: b=input('type something') #input获得的是字符串 if b=='1': #后面的语句还会执行才会退出循环 a=False else: pass ''' ''' while True: b=input('Type something:') if b=='1': break #跳出循环 else: pass print('still in while') print('finish r...
5c34ac0552b3724dbd63a83a40ff45dae2882889
Broather/auto-math
/lin_algebra/matricas/gauss.py
1,263
3.640625
4
import copy mtx = [[1, 2, 0, -1], [3, 4, 2, 1], [-2, 1, 1, 1], [-1, -1, 2, 1]] def print_mtx(mtx): for x in mtx: print(x) def gauss(matrix): determinants = 1 matrix_copy = copy.deepcopy(matrix) # 1.sakārtot rindas lai galvenajā diagonālē nav nulles un pēc iespējas vairāk 1 ...
88d3c22dbbb48005fd2368c6ac76a7554840a10a
Irankundakanyamahoro/Refugees-low-society-portal
/object.py
430
4.0625
4
#class myclass: # x = 5 #p1 =myclass() #print(p1.x) #class Person: # def __init__(self,name,age): # self.name = name # self.age = age #p1 =Person("john", 36) #print(p1.name) #print(p1.age) class Person: def __init__(self,fname,lname): self.firstname = fname self.lastname = lname def...
fa5ca98d42624ecdc472c9b909f77bd8c393977e
joskid/machine-learning-5
/neural/neural.py
11,027
4.1875
4
# neural.py # CS321 Artificial Intelligence final project # ----------------------------------------------------------------------------------- # Implements a feed-forward artificial neural network with 1 hidden layer to classify # MNIST handwritten digits. The basic implementation uses ReLU activation functions, # a ...
a88e378b4111ab9d88b9cb4864b4be8bc07529be
whpeak/daily_demo
/com/pyjava/thread/threadingDemo.py
1,027
3.671875
4
#! /usr/bin/env python #-*-encoding:utf8-*- ''' Created on 2016年10月8日 @author: wangheng ''' import threading from time import sleep,ctime loops = [4,2] def loop(nloop,nesc): print 'start loop',nloop,'at:',ctime() sleep(nesc) print 'loop',nloop,'done at:',ctime() class ThreadFunc(object): '...
2e0c4cab2995c77a880452f2e5468f52462102e1
kyogesh/checkio_test
/home/long_repeat.py
797
4.03125
4
def long_repeat(line: str) -> int: """ length the longest substring that consists of the same char """ if not line: return 0 max_len = 0 char = '' counter = 0 for each in line: if char == each: counter += 1 elif char != each: char = eac...
e285a04a3d180379fd2ee626a403a5317222550f
dnng/interviews
/permutations/permutations.py
802
4.125
4
""" Find all permutations of a string """ # To be used in the easy answer import itertools # Simple solution def permutations(head, tail=''): if len(head) == 0: print tail else: for i in range(len(head)): permutations(head[0:i] + head[i+1:], tail+head[i]) # Create a generator so w...
074070a5c36cd30efde13f9db98eb621a9bbba29
thegrafico/dots-lines
/app.py
16,683
3.953125
4
""" Author: Raul Pichardo Avalo Date: August 2019 Dots and Box Game Take more boxes than your opponent. You move by connecting two dots with a line. When you place the last ‘wall’ of a single square (box), the box is yours. The players move in turn, but whenever a player takes a box (s)he must move again. The board ...
d3adea158ee00533c95767428ddedd7e973a27e8
9aa5/interview
/FlattenBinary_Pass.py
925
3.875
4
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return nothing, do it in place def flatten(self, root): self.flatternInt(root) ...
46c266cbd52ce72c570dfa7e803dc5ad8783dbda
brajaram/TitanicChallenge
/RandomForestTrial.py
6,513
3.5625
4
from __future__ import division import pandas as pd import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.learning_curve import learning_curve import matplotlib.pyplot as plt from sklearn.cross_validation import ShuffleSplit import csv as csv def plot_learning_curve(estimator, title, X, ...
e580a4f8776177f4cca7da56191a607f541fa279
aasshhiisshh/luser_python
/Message-Encryption-And-Decryption_done/encryption.py
1,247
4.09375
4
''' This example is for Cryptography, When you want to hide your original message with any random characters. ''' #Imports from Crypto.Cipher import AES #pycrypto packages import base64 import os #Functions #Function to write to a file. def fileWrite(filename,text): ''' @param Input: The filename in ...
36d41859ac3d390097a3333b66425122da78b609
SantrupthiKori/Python
/loops.py
229
3.671875
4
words = ['cat', 'window', 'defenestrate'] for w in words: print(w, len(w)) words = ['cat', 'window', 'defenestrate','evaluation'] for w in words[2:]: if len(w) > 6: words.insert(0, w) print(w, len(w))
0693195bc2adf89006da084bf33edeee15f95201
K-subin/Caesar-Cipher
/caesercipher_lib.py
1,756
3.734375
4
lower_alphabet = "abcdefghijklmnopqrstuvwxyz" upper_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # 시저암호 함수 def Caesar_encrypt(key, plain_msg): cipher_msg = '' for symbol in plain_msg: if symbol in upper_alphabet: symbol_idx = upper_alphabet.find(symbol) cipher_msg = cipher_m...
247fc33888b8f1538499673e80cddf469e6fc9a8
sylvieong/python-scratchpad
/sandbox/test_metaclasses.py
661
4.09375
4
class Funky: def __init__(self): self.x = 10 def __call__(self): print("Look at me, I work like a function!") self.y = 20 def print_fn(): print(f'__name__ is {__name__}') if __name__ == "__main__": print('In main') print_fn() f = Funky # f is a class print(f'f is: {f}') f_inited = f() # f_inited ...
ee3ffb0316e421c3efefdaf761dc5c46eca6c157
NikeNano/DailyCodingProblem
/piCalculator/algo.py
469
3.515625
4
import random import math def main(): inside = 0.0000001 count = 0.0000001 while True: a = random.uniform(0, 1) b = random.uniform(0, 1) distance_center = (a**2 + b**2)**0.5 if distance_center<1: inside +=1 count +=1 current_pi = (inside/count)/...
8175aee0279e72b82960f8561b45d3c4a9ca0c5a
heylch/Principles-of-Computing-Part1
/Week1/merge.py
884
3.703125
4
""" Merge function for 2048 game. """ def merge(line): """ Function that merges a single row or column in 2048. """ # replace with your code result = [] for item in range(0,len(line)): if line[item] !=0: result.append(line[item]) print result jerry =0 while jerry...
9ab526693d48d77ba9f6f7a6f18fbf1b79b7978e
skye25-11/python_Reptile-basics
/BeautifulSoup/查找文档元素.py
1,949
3.703125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/3/31 0031 12:28 # @Author : skye # @Site : # @File : 查找文档元素.py # @Software: PyCharm from bs4 import BeautifulSoup doc=''' <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p ...
7bbc11142784a364622cd98701760eed2bd83c91
sayahna22/sayahna
/22.7.2020/Heapsort .py
757
4.0625
4
def heapify(a,n,i): largest=i left=2*i+1 right=2*i+2 if(left<n and a[largest]<a[left]): largest=left if(right<n and a[largest]<a[right]): largest=right if(largest!=i): a[i],a[largest]=a[largest],a[i] heapify(a,n,largest) def heap_sort(arr): n=len(a)...
d58ac87c4e2434d4819a8ad29794c4a2ae6fcf3a
sayahna22/sayahna
/Stack in python/stackpush & pop.py
160
3.75
4
arr=[] num=(int(input("Ente the size of the stack"))) for i in range(num): ele=int(input()) arr.append(ele) while(len(arr)!=0): print(arr.pop())
e1ba0d4c48034e37f93781c70a1b7ebc6327c07a
sayahna22/sayahna
/23.7.2020/sum_tri.py
415
4
4
def sum_tri(arr:list,n:int): #b=range(n-1) if (n < 1): return b=[0]*(n-1)#initialize a list b for i in range(0,n-1): s=arr[i]+arr[i+1] b[i]=s sum_tri(b,n-1) print(arr) if __name__ == '__main__': num=int(input("Enter the size:")) a=[] fo...
2365461d9b43819fa2c6944030df1cf1dc6af88c
sayahna22/sayahna
/26.7.2020/reverse_double_linked_list.py
1,340
4.15625
4
class node: def __init__(self,data): self.data=data self.prev=None self.next=None class double_linkedlist: def __init__(self): self.start=None def insert_last(self,data): newnode=node(data) if(self.start is None): self.start=newnode ...
ba9eb7dd5f5f453be81062169196de5af9602b52
hustlrr/algorithm_assignments
/assignment3/linked_list_prior_queue.py
2,581
3.828125
4
# coding=utf-8 # Created by lruoran on 17-1-20 from Datautils import loadGraph # 使用链表实现优先队列 # 利用prior queue在dijkstra中的应用进行测试 class linkedList: def __init__(self, d=None, node=None): self.dist = d self.node = node self.next_ = None class priorQueue: def __init__(self): self....
79538b15cf645a8f1cdf9369daa02e70d903604b
rjm3q/Python-Py-Me-Up-Charlie
/main.py
1,819
3.578125
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 13 18:26:05 2019 @author: rober """ import os import csv #setfilepath csvpath= os.path.join("budget_data.csv") #lists months= [] profits_losses= [] changes= [] #opens the csv file to read with open(csvpath, newline='', encoding='utf8') as budget_data: csvreader = ...
88d8a52c2b3783153bc9639bd187f22f24783e41
Rysbaev/Python-Projects
/HomeWork #5.py
978
4.21875
4
class Study: def __init__(self,name , age, month): self.name = name self.age = age self.month = month def how_many_month_you_study(self): return f"{self.name} {self.age} {self.month}" while True: print("1) Your Name ") print("2) Your age") print("3) Month you've b...
b2f4ccfcc139c286f229f83b867861d2b421691c
mohamedjs/Square-Puzzles
/squarepuzzles (2).py
9,620
3.5
4
import pygame from colors import * import random import sys import time ################################################################# # Class represents playing desk class Desk(object): SHUFFLE_NUMBER = 60 # changing to 200 and higher ruins everything def __init__(self, width, height): self.mat...
f004d11929c3f91c198172735a903fdaedbd656e
Mohdyusuf786/Blurring-and-smoothening
/Smoothening.py
1,324
3.640625
4
import cv2 import numpy as np import matplotlib.pyplot as plt img= cv2.imread('apple.jpg') img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)#as i had told u earlier that in matplotlib we have to use RGB format img=cv2.resize(img,(700,700)) #lets try homogenious filter kernal=np.ones((5,5),np.float32)/25 homogenious=cv2.filter2D...
08162e569db5f28f2aa7f4eb32532bf1601049f6
joselynzhao/Python-data-structure-and-algorithm
/leecode/79.py
4,022
3.75
4
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @AUTHOR:Joselyn Zhao @CONTACT:zhaojing17@foxmail.com @HOME_PAGE:joselynzhao.top @SOFTWERE:PyCharm @FILE:79.py @TIME:2020/8/10 19:34 @DES: ''' class Solution: def exist(self, board,word): # import numpy as np # board = np.array(board) m = len(boar...
2b3887b3f4a7e90dea42b7075057d6657da1e9f8
joselynzhao/Python-data-structure-and-algorithm
/data_structure/tuple/youxianpy.py
1,095
4
4
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @AUTHOR:Joselyn Zhao @CONTACT:zhaojing17@foxmail.com @HOME_PAGE:joselynzhao.top @SOFTWERE:PyCharm @FILE:youxianpy.py @TIME:2020/4/25 20:22 @DES: ''' ''' 使用内置模块heapq可以实现一个简单的优先级队列。 ''' import heapq class PriorityQueue: def __init__(self): self._queue = [] ...
427a65ccd689b16c701706d495f007dbd72ffb59
joselynzhao/Python-data-structure-and-algorithm
/leecode/78.py
1,020
3.953125
4
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @AUTHOR:Joselyn Zhao @CONTACT:zhaojing17@foxmail.com @HOME_PAGE:joselynzhao.top @SOFTWERE:PyCharm @FILE:78.py @TIME:2020/8/9 19:58 @DES: ''' class Solution: def subsets(self, nums): # 先从小到大排序 # nums.sort() # print(nums) cur = [] ...
57f6f3c3d9b3f5636b9d55486ee9beb3f3674716
joselynzhao/Python-data-structure-and-algorithm
/leecode/20060401.py
1,485
3.703125
4
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @AUTHOR:Joselyn Zhao @CONTACT:zhaojing17@foxmail.com @HOME_PAGE:joselynzhao.top @SOFTWERE:PyCharm @FILE:20060401.py @TIME:2020/6/4 20:48 @DES: 回文数 : 已解除,但时间超出限制,需要动态规划 ''' def longestPalindrome( s: str) -> str: # 先考虑极端情况 lens = len(s) if lens == 1: re...
ba25b6a4c8399c16194f39ec86fbeb2f74564b4b
pazyko/final_task_pazyko
/main.py
1,017
3.53125
4
import argparse from custom_logger import * from input_menu import InputNameAndPosition def create_parser(): """Parse for optional argument: '-n' '--name' to get name '-p' '--position' to get position (variants are 'salesman', 'manager') if combination of name and position is not found in database, new...
322bf20d2ed075f207adc3495f726fd22b5e9638
YuxuanSu-Sean/learning
/learnpython/demo_alien_if.py
180
3.625
4
# alien_colors = ['green', 'yellow', 'red'] alien_color = 'green' if alien_color == 'green': print('The player A got 5 points!') else: print('The player A got 10 points!')
9da5706c34d9522527c2b20242c775d2224cb040
jim3g7/easypost-python
/easypost/easypost.py
4,900
3.640625
4
from __init__ import post, api_url api_key = '' class Address(object): """ A shipping address. Name is not required for most API calls. """ def __init__(self, name="", street1="", street2="", city="", state="", zip=""): self.name = name s...
62edc6a57b0577abfffc6c99e4f23993cbf2251f
ysyong/pyGrammar
/structure/print_tuple.py
113
3.53125
4
age=22 name='Swaroooop' print '%s is %d years old'%(name, age) print 'why is %s playing with that python?' %name
6538b15564ddae57f61e0a886d989af9880ac6cc
anixshi/CS-111-Python-PSETS
/ps09/shrinkingSquares.py
6,278
3.625
4
# Your name: Anika Shields # Your username: ashields # CS111 Spring 2018 PS09 # shrinkingSquares.py # Submission date: 4/24/18 from cs1graphics import * from printNice import printNice #------------------------------------------------------------------------------ # Subtask 3a def rotated(vals): """ Suppose...
666c2806a45e47cc62d55c49fd21e4907a52f50f
anixshi/CS-111-Python-PSETS
/ps10-recursion/picture.py
9,846
3.609375
4
"""Python code for Henderson-like picture language abstraction built on top of cs1graphics. In all cases, a "picture" is a drawable object that fits in a 200 x 200 square centered about the reference point (0,0) Lyn Turbak, Sep 2015, with edits by Sravana Reddy, Oct 2015.""" from cs1graphics import * # impor...
0d5c2092642299b5beed6d168a9b7f6cd34a3e6c
lbrett3/caesar-cypher
/cypher.py
4,029
4.03125
4
import string import random WORDLIST_FILENAME = "words.txt" def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." inFile ...
a716c9e68d2622262c958ada00c443a85d940a70
GonzaloGmv/calentamiento
/ejercicio6.py
359
3.9375
4
shipping_cost_per_kg = 1.20 customer_basket_cost = 34 customer_basket_weight = 44 if(customer_basket_cost >= 100): print('Free shipping!') else: shipping_cost = customer_basket_weight * shipping_cost_per_kg customer_basket_cost = customer_basket_cost + shipping_cost print("Total basket cost including shi...
eaf7cf6f930e125e4c4bfb1cc29228bb93465f5e
asingh611/ud256-proj3
/problem_2.py
3,798
4.34375
4
def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Provided assumption: no repeating number Args: input_list(list): Input array to search number(int): Target of search Returns: int: Index or -1 """ # Return -1 for th...
9709623c105232a04c6b91e074729c7889ab23c6
p-cap/dev4CTF
/Cyber-Apocalypse-2021/crypto/PhaseStream1/decode.py
1,020
4.125
4
# Assigned the ciphertext and the key to a constat ciphertext = "2e313f2702184c5a0b1e321205550e03261b094d5c171f56011904" key = "mykey" # temp is used to store the characters from the ciphertext that are equivalent to 2 characters or 8-bytes # Keep in mind, we have a hexadecimal encoded ciphertext temp = "" # flag is ...
6d938ab43215869b092edec1f9829dabc9bd1680
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/8_EXAM/3.py
1,275
3.59375
4
""" На обработку поступает последовательность из 4 целых чисел. Известно, что вводимые числа по абсолютной величине не превышают 10**6 Нужно написать программу, которая выводит на экран количество нечётных чисел в исходной последовательности и максимальное нечётное число. Если нечётных чисел нет, требуется на экран выв...
cf16b3d3d1aa3be65806d40ccaffafe77aad5940
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/11_list/11.3.append-extend-del/13.py
484
3.703125
4
""" На вход программе подается натуральное число n и n строк, а затем число k. Напишите программу, которая выводит k-ую букву из введенных строк на одной строке без пробелов. """ n = int(input()) data = [] for _ in range(n): data.append(input()) num = int(input()) for item in data: if len(item) >= num: ...
0bb11c07d7af5456b0a88ef3bacc34c1c8aedfeb
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/11_list/11.7/7.py
624
4.21875
4
""" На вход программе подается натуральное число nnn. Напишите программу, использующую списочное выражение, которая создает список содержащий квадраты чисел от 1 до n, а затем выводит его элементы построчно, то есть каждый на отдельной строке. Для вывода элементов списка используйте цикл for. """ n = int(input()) numbe...
0f85ad3c69cc8d24a996483533cfe0114c36829e
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/11_list/11.4/8.py
843
4.25
4
""" На вход программе подается натуральное число nn, а затем nn целых чисел. Напишите программу, которая сначала выводит все отрицательные числа, затем нули, а затем все положительные числа, каждое на отдельной строке. Числа должны быть выведены в том же порядке, в котором они были введены. """ negatives = [] zeros = ...
7aa0f2906fe2f7058edf9d626b41c5ad5d736046
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/11_list/11.3.append-extend-del/12.py
539
4.09375
4
""" На вход программе подается натуральное число nn, а затем nn целых чисел. Напишите программу, которая создает из указанных чисел список, затем удаляет все элементы стоящие по нечетным индексам, а затем выводит полученный список. """ n = int(input()) data = [] for _ in range(n): num = int(input()) data.appen...
ddd6a34436b8b85b52145c2104e49e868d52f0b8
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/12_EXAM/3.py
577
3.875
4
""" На вход программе подается строка текста, содержащая натуральные числа. Напишите программу, которая вставляет между каждым числом знак +, а затем вычисляет сумму полученных чисел. """ # 1 Вариант text = input().split() total = 0 for i in text: total += int(i) new_text = '+'.join(text) print(f'{new_text}={tot...
cfa94f91609096baa7828a92fd3ef5d2d6e3faf4
Sergey-Laznenko/Stepik
/Python Programming/1_Operators. Variables/1.12_Tasks_1st_week/2.py
509
4.125
4
""" Напишите программу, принимающую на вход целое число, которая выводит True, если переданное значение попадает в интервал (-15, 12] ∪ (14, 17) ∪ [19, +∞) и False в противном случае (регистр символов имеет значение). """ # put your python code here a = int(input()) if (-15 < a <= 12) or (14 < a < 17) or (19 <= a): ...
b429093eca87e0ed6bf02d01592bdd7a382f65f8
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/11_list/11.4/3.py
604
4.15625
4
""" На вход программе подается натуральное число nn, а затем nn целых чисел. Напишите программу, которая для каждого из введенного числа xx выводит значение функции f(x) = x**2 + 2x + 1, каждое на отдельной строке. """ n = int(input()) numbers = [] for _ in range(n): x = int(input()) numbers.append(x) print(*n...
200b90c23a228354e95557a1229d022ca960f169
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/7_loops_for-while/7.1.for_loop/2.py
197
3.703125
4
""" Напишите программу, которая выводит слова «Python is awesome!» (без кавычек) 10 раз. """ for _ in range(10): print('Python is awesome!')
3b24deb2c5dd33cc087c1c30ba82d1f69b1d9cee
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/2_input_print/2.4.arifmetica/7.py
338
4.34375
4
""" Напишите программу, вычисляющую объём куба и площадь его полной поверхности, по введённому значению длины ребра. """ x = int(input()) print('Объем =', x ** 3) print('Площадь полной поверхности =', 6 * x ** 2)
22e9807d01da213345f27ebcbce442d515f3e058
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/11_list/11.5.split_join/4.py
342
3.90625
4
""" На вход программе подается строка текста, содержащая имя, отчество и фамилию человека. Напишите программу, которая выводит инициалы человека. """ s = input().split() print('.'.join(s[0][0] + s[1][0] + s[2][0]) + '.')
36347a8d02a79ddd63fbdf57210fddf94264b536
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/14_EXAM/9.py
727
4.3125
4
""" Магическая дата – это дата, когда день, умноженный на месяц, равен числу образованному последними двумя цифрами года. Напишите функцию, is_magic(date) которая принимает в качестве аргумента строковое представление корректой даты и возвращает значение True если дата является магической и False в противном случае. "...
c40766110d1b0f30899f568841a85252cd3c513d
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/4_operators/4.2_and-or-not/12.py
406
4
4
""" Напишите программу, которая принимает три положительных числа и определяет, существует ли невырожденный треугольник с такими сторонами. """ a, b, c = int(input()), int(input()), int(input()) if (a < (b + c)) and (b < (c + a)) and (c < (a + b)): print('YES') else: print('NO')
32a5ffd18a15acdad8a6623e50e0957fe27dbd41
Sergey-Laznenko/Stepik
/Python: fundamentals and application /1st week/6 class inheritance/7.py
575
3.671875
4
classes = {} for i in range(int(input())): data = input().split(' : ') if len(data) == 1: data.append("") classes[data[0]] = data[1].split() for j in classes[data[0]]: if j not in classes: classes[j] = [] def is_parent(child, parent): if parent in classes[child] or ...
21029c78fd2b03cb2779b26368a879a51623c1a3
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/11_list/11.7/6.py
411
3.90625
4
""" Дополните приведенный код, используя списочное выражение, так чтобы получить список всех чисел палиндромов от 100 до 1000. """ # 1 palindromes = [i for i in range(100, 1000) if i // 100 == i % 10] print(palindromes) # 2 palindromes = [i for i in range(100, 1000) if str(i) == str(i)[::-1]] print(palindromes)
fd40857e1f30455da26aae1e954007adfdf2672c
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/9_String_data_type/9.6.ascii_unicode/5.py
327
3.59375
4
""" На вход программе подается строка текста. Напишите программу, которая переводит каждый ее символ в соответствующий ему код из таблицы символов Unicode. """ for i in input(): print(ord(i), end=' ')
174ed871211c20f253fea37b7d0497638e227f66
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/7_loops_for-while/7.1.for_loop/7.py
306
4.125
4
""" Напишите программу, которая считывает одну строку текста и выводит 10 строк, пронумерованных от 0 до 9, каждая с указанной строкой текста. """ x = input() for i in range(10): print(i, x)
0fbc7cdd779057517d18eac08696c49f649ba156
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/2_input_print/2.5.more_arifmetic/10.py
433
3.796875
4
""" В купейном вагоне имеется 99 купе с четырьмя местами для пассажиров в каждом. Напишите программу, которая определяет номер купе, в котором находится место с заданным номером (нумерация мест сквозная, начинается с 11). """ print((int(input()) + 3) // 4)
55e0bc0a5af2e2b0417469b750505ba92eb3f8b4
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/9_String_data_type/9.2.slices/14.py
490
3.9375
4
""" На вход программе подается строка текста. Напишите программу, которая разрежет ее на две равные части, переставит их местами и выведет на экран. """ s = input() if len(s) >= 2: if len(s) % 2 == 0: x = len(s) // 2 print(s[x:] + s[:x]) elif len(s) % 2 != 0: x = (len(s) - 1) // 2 ...
eee675a4998c73b706f7d0bce517fb9f02044f07
Sergey-Laznenko/Stepik
/Python Programming/1_Operators. Variables/1.8_Variables/8.py
570
3.8125
4
""" Катя узнала, что ей для сна надо X минут. В отличие от Коли, Катя ложится спать после полуночи в H часов и M минут. Помогите Кате определить, на какое время ей поставить будильник, чтобы он прозвенел ровно через X минут после того, как она ляжет спать. """ x = int(input()) h = int(input()) m = int(input()) h = (x ...
f7374a70da93abb74efce215ecb04234d2a78972
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/5_EXAM/7.py
468
3.953125
4
""" Даны две различные клетки шахматной доски. Напишите программу, которая определяет, может ли конь попасть с первой клетки на вторую одним ходом """ x1, y1 = int(input()), int(input()) x2, y2 = int(input()), int(input()) dx = abs(x1 - x2) dy = abs(y1 - y2) if dx == 1 and dy == 2 or dx == 2 and dy == 1: print(...
243eabfb4280b09bdf4d0819f02ba6e13c8e4869
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/6_data_types/6.2.math/2.py
339
4.09375
4
""" Напишите программу определяющую евклидово расстояние между двумя точками, координаты которых заданы. """ from math import * x1, y1, x2, y2 = float(input()), float(input()), float(input()), float(input()) print(sqrt((x1 - x2)**2 + (y1 - y2)**2))
ce36d1f306ab5d1461062cb9ae698a463b539ffd
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/12_EXAM/6.py
619
4.25
4
""" На вход программе подается строка текста. Напишите программу, использующую списочное выражение, которая преобразует каждое слово введенного текста в "молодежный жаргон" по следующему правилу: - первая буква каждого слова удаляется и ставится в конец слова; - затем в конец слова добавляется слог "ки". """ print(...
e52d8b15858c2d58fc9f840b6b8a51de654dea3c
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/6_data_types/6.2.math/6.py
300
4.09375
4
""" На вход программе подается одно вещественное число x. Программа должна вывести одно число – значение указанного выражения. """ from math import * a = float(input()) print(floor(a) + ceil(a))
d406b592517f756f106ae17cf9f1cacae0fe6841
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/7_loops_for-while/7.1.for_loop/3.py
334
4.15625
4
""" Дано предложение и количество раз которое его надо повторить. Напишите программу, которая повторяет данное предложение нужное количество раз. """ a, b, = input(), int(input()) for _ in range(b): print(a)
8887d168a1c063ba1aefc83e2bb0a06da6d7cebc
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/7_loops_for-while/7.7.code review/5.py
886
3.765625
4
""" На обработку поступает последовательность из 7 целых чисел. Известно, что вводимые числа по абсолютной величине не превышают 10**6 Нужно написать программу, которая подсчитывает и выводит сумму всех чётных чисел последовательности или 0, если чётных чисел в последовательности нет. Программист торопился и написал пр...
89517a106e848c64ad5272cbe7abd1db716fafab
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/11_list/11.5.split_join/10.py
778
4.15625
4
""" На вход программе подается строка текста, содержащая натуральные числа. Из данной строки формируется список чисел. Напишите программу, которая подсчитывает, сколько в полученном списке пар элементов, равных друг другу. Считается, что любые два элемента, равные друг другу образуют одну пару, которую необходимо посчи...
98e2f3e22f645bd98c7db0dec113937d6e9b4299
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/4_operators/4.2_and-or-not/11.py
582
3.90625
4
""" Назовем число красивым, если оно является четырехзначным и делится нацело на 77 или на 1717. Напишите программу, определяющую, является ли введённое число красивым. Программа должна вывести «YES», если число является красивым, или «NO» в противном случае. """ x = int(input()) if (1000 <= x <= 9999) and ((x % 7 == ...
d6ee6c527ebd1e7ac22302197f434739ea7183b9
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/6_data_types/6.1.int_float/7.py
364
3.90625
4
""" На вход программе подается число nn – количество собачьих лет. Напишите программу, которая вычисляет возраст собаки в человеческих годах. """ f = int(input()) if f <= 2: print(f * 10.5) else: if f > 2: print(21 + ((f - 2) * 4))
15f0badb0c2dcfbb19071b5ddb2bf8fe8f1d67c3
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/9_String_data_type/9.4.str_methods_v2/11.py
315
3.59375
4
""" На вход программе подается строка текста. Напишите программу, которая подсчитывает количество цифр в данной строке. """ s = input() score = 0 for _ in s: if _ in '0123456789': score += 1 print(score)
0c3feed5b9531d8271dbe6816ee3243864a8d306
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/10_EXAM/8.py
260
3.8125
4
""" На вход программе подается строка текста. Напишите программу, которая заменяет все вхождения цифры 1 на слово «one». """ s = input() print(s.replace('1', 'one'))
e76c88133f650691686d4e0455a1a3a1c106010e
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/6_data_types/6.1.int_float/15.py
451
3.515625
4
""" На вход программе подается пять действительных чисел a1, a_2, a3, a4, a5, каждое на отдельной строке. Программа должна вывести одно число – сумму модулей введёных чисел. """ a, b, c, d, e = float(input()), float(input()), float(input()), float(input()), float(input()) print(abs(a) + abs(b) + abs(c) + abs(d) + abs(...
7f8802ac9e507dcf0f894a7078dee49aeffbde3c
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/9_String_data_type/9.2.slices/12.py
725
4.53125
5
""" На вход программе подается одна строка. Напишите программу, которая выводит: - общее количество символов в строке; - исходную строку повторенную 3 раза; - первый символ строки; - первые три символа строки; - последние три символа строки; - строку в обратном порядке; - строку с удаленным первым и последний символом...
3dca7b0ffda3baec2487d3a2b13596b8093c8e35
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/9_String_data_type/9.1.index/8.py
293
4.125
4
""" На вход программе подается одна строка. Напишите программу, которая выводит в столбик элементы строки в обратном порядке. """ a = input() for i in range(1, len(a) + 1): print(a[-i])
e376e1ae574e1119f186de58e91618c1bb5647f2
Sergey-Laznenko/Stepik
/Python: fundamentals and application /1st week/5 Classes/9.py
346
3.5
4
class Buffer: def __init__(self): self.lst = list() def add(self, *a): for value in a: self.lst.append(value) while len(self.lst) >= 5: s = 0 for i in range(5): s += self.lst.pop(0) print(s) def get_current_part(self)...
ef76e8f3ca023b1e16a57b34c4cb7e3eddbfad1c
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/11_list/11.4/7.py
792
3.703125
4
""" На вход программе подается натуральное число n, затем n строк, затем число k — количество поисковых запросов, затем k строк — поисковые запросы. Напишите программу, которая выводит все введенные строки, в которых встречаются все поисковые запросы. """ data = [] for _ in range(int(input())): string = input() ...
8c3332bb5f4e93c4d2d97203b13a95be77e98464
KingHammer883/25.Generator
/25.Generator.py
4,621
4.15625
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 25, 2019 File: Generator.py Generates and displays sentences using simple gramma and vocabulary. Words are chosen at random. @author: Byen23 """ # Request """Write a program that generates sentences.""" # Analysts """Sentences in any language have a stru...
6cf0cd445bdfbeda6ff4a8eba4b27416ce89b978
caitouwww/probable-octo-doodle
/数据结构与算法/栈 stack/1047. 删除字符串中的所有相邻重复项/删除字符串中的所有相邻重复项.py
1,229
3.703125
4
""" СдĸɵַSظɾѡͬĸɾǡ S Ϸִظɾֱ޷ɾ ظɾ󷵻յַ𰸱֤Ψһ ʾ 룺"abbaca" "ca" ͣ 磬 "abbaca" Уǿɾ "bb" ĸͬǴʱΨһִɾظ֮ǵõַ "aaca"ֻ "aa" ִظɾַΪ "ca" ʾ 1 <= S.length <= 20000 S СдӢĸɡ ԴۣLeetCode ӣhttps://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string ȨСҵתϵٷȨҵתע """ class Solution: def removeDuplicates(self, S: str) ->...
97aee77d4f2fc8081cd5ddf0170374641e032a62
caitouwww/probable-octo-doodle
/数据结构与算法/栈 stack/0020. 有效的括号/有效的括号.py
1,326
3.96875
4
""" 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 有效字符串需满足: 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。 示例 1: 输入: "()" 输出: true 示例 2: 输入: "()[]{}" 输出: true 示例 3: 输入: "(]" 输出: false 示例 4: 输入: "([)]" 输出: false 示例 5: 输入: "{[]}" 输出: true 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/valid-parenthese...
044629bbfa5a03df13e6767572678f7aba099222
caitouwww/probable-octo-doodle
/数据结构与算法/动态规划 dynamic programming/0303. 区域和检索 - 数组不可变/区域和检索 - 数组不可变.py
1,361
3.578125
4
""" һ numsij(ij) ΧԪصܺͣi,j㡣 ʾ nums = [-2, 0, 3, -5, 2, -1]ͺΪ sumRange() sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 ˵: Լ鲻ɱ䡣 εsumRange ԴۣLeetCode ӣhttps://leetcode-cn.com/problems/range-sum-query-immutable ȨСҵתϵٷȨҵתע """ class NumArray: """ def __init__(self, nums: List[int]): if n...
483eb2d971e6443376c1478a38866cf68cafed51
caitouwww/probable-octo-doodle
/数据结构与算法/链表 linked list/0083. 删除排序链表中的重复元素/删除排序链表中的重复元素.py
1,677
3.859375
4
""" һɾظԪأʹÿԪֻһΡ ʾ1: : 1->1->2 : 1->2 ʾ2: : 1->1->2->3->3 : 1->2->3 ԴۣLeetCode ӣhttps://leetcode-cn.com/problems/remove-duplicates-from-sorted-list ȨСҵתϵٷȨҵתע """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: ...
a0d3b1cd3555c624a7b7c0fbbcb22edf4740378d
caitouwww/probable-octo-doodle
/位运算 bit manipulation/0401. 二进制手表/二进制手表.py
2,030
3.75
4
""" ֱ 4 LED Сʱ0-11ײ 6 LED ӣ0-59 ÿ LED һ 0 1λҲࡣ 磬Ķֱȡ 3:25 һǸ nǰ LED ŵпܵʱ䡣 : : n = 1 : ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] ע: ˳ûҪ Сʱ㿪ͷ 01:00DzģӦΪ 1:00 ӱλɣܻ㿪ͷ 10:2ЧģӦΪ 10:02 ԴۣLeetCode ӣhttps://leetcode-cn.com/problems/binary-watch ȨСҵתϵٷȨҵתע """ class Solution: ...
29d59203b2dc1dbaaf00d7e3a863742ce311d51f
caitouwww/probable-octo-doodle
/数据结构与算法/动态规划 dynamic programming/0198. 打家劫舍/打家劫舍.py
1,932
3.578125
4
""" һרҵС͵ƻ͵ؽֵķݡÿ䷿ڶһֽӰ͵ԵΨһԼؾڵķװ໥ͨķϵͳڵķͬһϱС͵룬ϵͳԶ һÿݴŽķǸ飬ڲװõ£ܹ͵Ե߽ ʾ 1: : [1,2,3,1] : 4 : ͵ 1 ŷ ( = 1) Ȼ͵ 3 ŷ ( = 3) ? ͵Ե߽ = 1 + 3 = 4 ʾ 2: : [2,7,9,3,1] : 12 : ͵ 1 ŷ ( = 2), ͵ 3 ŷ ( = 9)͵ 5 ŷ ( = 1) ? ͵Ե߽ = 2 + 9 + 1 = 12 ԴۣLeetCode ӣhttps://leetcode-cn.com/problems/house-robber ȨСҵתϵٷȨҵתע """ class Solution...
f545a79f10f96b204112e8e968248add432078a8
RaghavDadhwal007/Pytask
/PythonTask/FirstQues.py
116
3.5625
4
arr = [-2, 1, 3, -4, 5] def total(l): sm = 0 for i in l: sm += i return sm print(total(arr))
2a66f5eaddd322c935eeb856fb0ae5bafd54c18e
samkrimmel/unit5
/wordSort.py
164
3.96875
4
#Sam Krimmel #4/23/18 #wordSort.py - sorts list alphabetically words = input('Enter a bunch of heckin words: ').split(' ') for item in words.sort(): print(item)
2b45ffe8a3603b3c9747510508f1e3a08c16fa95
samkrimmel/unit5
/antsDemo.py
631
3.609375
4
#Sam Krimmel #4/30/18 #antsDemo.py - using lists with graphics from ggame import * from random import randint ANTS = 50 WIDTH = 900 HEIGHT = 600 #move each ant randomly up/down and left/right def step(): for ant in data['antList']: ant.x += randint(-11,10) ant.y += randint(-11,10) #putting fire...
baa5fa0b9121e258fb1a3c22b2d1be6ccfd7b388
wwjholmes/leetcode
/139.word-break.py
1,973
3.78125
4
# # @lc app=leetcode id=139 lang=python3 # # [139] Word Break # # https://leetcode.com/problems/word-break/description/ # # algorithms # Medium (41.68%) # Likes: 6395 # Dislikes: 304 # Total Accepted: 743.3K # Total Submissions: 1.8M # Testcase Example: '"leetcode"\n["leet","code"]' # # Given a string s and a di...
0815dbc32d243cd0f2b6bbcadf244685c2ef81ba
wwjholmes/leetcode
/1.two-sum.py
1,084
3.65625
4
# # @lc app=leetcode id=1 lang=python3 # # [1] Two Sum # # https://leetcode.com/problems/two-sum/description/ # # algorithms # Easy (45.57%) # Likes: 15912 # Dislikes: 578 # Total Accepted: 3.1M # Total Submissions: 6.8M # Testcase Example: '[2,7,11,15]\n9' # # Given an array of integers, return indices of the t...
15ae33f1371def2ac72eae04cab8bef1d322d188
wwjholmes/leetcode
/140.word-break-ii.py
2,173
3.734375
4
# # @lc app=leetcode id=140 lang=python3 # # [140] Word Break II # # https://leetcode.com/problems/word-break-ii/description/ # # algorithms # Hard (34.67%) # Likes: 3082 # Dislikes: 444 # Total Accepted: 318K # Total Submissions: 896.4K # Testcase Example: '"catsanddog"\n["cat","cats","and","sand","dog"]' # # G...
184289532d302d0cbda887b53c09b9eca7ff6aac
wwjholmes/leetcode
/223.rectangle-area.py
1,956
3.546875
4
# # @lc app=leetcode id=223 lang=python3 # # [223] Rectangle Area # # https://leetcode.com/problems/rectangle-area/description/ # # algorithms # Medium (38.21%) # Likes: 530 # Dislikes: 869 # Total Accepted: 118K # Total Submissions: 307.9K # Testcase Example: '-3\n0\n3\n4\n0\n-1\n9\n2' # # Given the coordinates...
1f06d77a6050a9de1e70893d904883f74c3e2597
wwjholmes/leetcode
/103.binary-tree-zigzag-level-order-traversal.py
1,873
3.859375
4
# # @lc app=leetcode id=103 lang=python3 # # [103] Binary Tree Zigzag Level Order Traversal # # https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/ # # algorithms # Medium (50.09%) # Likes: 3377 # Dislikes: 127 # Total Accepted: 506.2K # Total Submissions: 1M # Testcase Example: '...
c081beaedf74263c514b94959eff02f312ace0ee
wwjholmes/leetcode
/283.move-zeroes.py
1,465
3.671875
4
# # @lc app=leetcode id=283 lang=python3 # # [283] Move Zeroes # # https://leetcode.com/problems/move-zeroes/description/ # # algorithms # Easy (58.54%) # Likes: 5330 # Dislikes: 167 # Total Accepted: 1.1M # Total Submissions: 1.9M # Testcase Example: '[0,1,0,3,12]' # # Given an integer array nums, move all 0's ...
75773318bafef0f7f455d03e1792a8debb0fd687
wwjholmes/leetcode
/68.text-justification.py
4,966
3.53125
4
# # @lc app=leetcode id=68 lang=python3 # # [68] Text Justification # # https://leetcode.com/problems/text-justification/description/ # # algorithms # Hard (29.68%) # Likes: 939 # Dislikes: 1888 # Total Accepted: 162.1K # Total Submissions: 544.5K # Testcase Example: '["This", "is", "an", "example", "of", "text"...
6d28d867557207c71a57b85200ad5d8b516e98f7
human02/preparation_2021
/Trees/max_depth_binary_tree.py
1,092
3.890625
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def max_depth_bottom_up_recursive(self, root): if root is None: return 0 left_depth = self.max_depth_bottom_up_recursive(root...
983d7012fea8a20cb6eacc9f664128fbbf420fc7
arye97/Algorithms
/adjaceny_list.py
1,427
4.09375
4
from pprint import pprint # undirected graph in the textbook example """ Builds an Adjacency List from input in format shown below D (Node) 3 (Number of Nodes in Graph) W (Weighting of Edge) eg take first line D 3 W 0 1 7 Node 0 connects to Node 1 with a weighted edge of weight 7 ""...
53ba6256e7738b8b9a6ca45ca1ea4aa9d39af2bf
teeseng/ant
/m343l/hw5/phi.py
401
3.65625
4
#!usr/bin/env # Euler's phi function def gcd(x,y): if(x < 0 | y < 0): return -1 elif(x == 0 | y == 0): return 0 r = x % y while(r > 0): x = y y = r r = x % y return y n = 1 while(n != "q"): n = input("choose a number: ") count = 0 for i in range...
41906ee3e825d8e11541ac3584a369a1c38f3f00
mertyn88/python
/algorithm/bfs.py
764
3.859375
4
vertexList = ['0', '1', '2', '3', '4', '5', '6'] edgeList = [(0, 1), (0, 2), (1, 0), (1, 3), (2, 0), (2, 4), (2, 5), (3, 1), (4, 2), (4, 6), (5, 2), (6, 4)] # 0 # | \ # 1 2 # | | \ # 3 4 5 # | # 6 def bfs(vertexList, edgeList, start): visitedList = [] queue = [sta...
738acf6f67b8759b855d257b8e15efb81b9e1c3c
ismailinayat/bt_real_estate
/listings/views.py
28,048
3.6875
4
""" LISTINGS: In our terminal, from our project directory, we will write "python manage.py startapp listings". Our listings app will contain 3 pages including "listings" which will contain all the listings, "listing" which will contain single listing and "search" page. So we will create templates for t...
fdb697f33d4ef942b6cd8a3c32ce6bec5729afb7
stormcroe/AIForGames2018
/lab03_spike01/gob_simple.py
4,962
4.53125
5
'''Goal Oriented Behaviour Clinton Woodward, 2015, cwoodward@swin.edu.au Works with Python 3+ Please don't share this code without permission. Simple decision approach. * Choose the most pressing goal (highest insistence value) * Find the action that fulfills this "goal" the most (ideally?, completely?) Goal: Eat (...
208a0d660a847d09fd2f36469bf631fe55166554
GGRice/ToolBox-Unittest
/unit_test.py
1,022
3.9375
4
""" Explores unittest and it's functionality Author: Gretchen Rice Date: March 11, 2017 """ import unittest def remove_negs(num_list): """ Removes negative values from a list """ no_negs = [number for number in num_list if number >= 0] return no_negs class TestListMethods(uni...