blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
da275f6e143f10058c1e65bece861203cd76e043 | vaishvikmaisuria/Sorting-Python-Time | /sort-time.py | 2,941 | 4.125 | 4 | ############### Bubble Sort ###############
def bubble_sort(L):
'''(list) -> NoneType
Sort the items in L in non-descending order.
>>> L = [1, 4, 2, 5, 3, 6]
>>> bubble_sort(L)
>>> L
[1, 2, 3, 4, 5, 6]
'''
uns_index = len(L) - 1
while uns_index > 0:
for curr_in... |
d0297fd7ba9dbd5a5df3da0d294fe5a940c32ed7 | laowantong/paroxython | /examples/idioms/programs/099.2693-format-date-yyyy-mm-dd.py | 360 | 3.5625 | 4 | """Format date YYYY-MM-DD.
Assign to string _x the value of fields (year, month, day) of date _d, in format _YYYY-_MM-_DD.
Source: programming-idioms.org
"""
# Implementation author: jessedhillon
# Created on 2019-09-26T13:46:18.91621Z
# Last modified on 2019-09-26T13:46:18.91621Z
# Version 1
from datetime import d... |
8673ebbea8a9610e58382e5b91db2aabfedf0c83 | dataAlgorithms/dataStructure | /linkedList/sortedCircularLinkedList.py | 4,431 | 3.734375 | 4 | class CircularSortedLinkedList:
# Init
def __init__(self):
self._listRef = None
self._size = 0
# Length
def __len__(self):
return self._size
# Check whether the list is empty
def isEmpty(self):
return self._size == 0
# Check whether the item in the list
de... |
f20728989d03b52b2dcdaf33c846db166b9e7604 | Fattore/2-Semestre_Fattore | /16_09_19/Ex5.py | 234 | 3.875 | 4 | #coding: utf-8#
'''
Faça um programa que leia um número natural e calcule o seu fatorial
'''
n1 = int(input("Digite um número natural: "))
fat = 1
for i in range(2,n1+1):
fat = fat * i
print("%d! = %d" %(n1, fat))
|
d6a506ee13bb1ebc854e124ad25aa93e343dc4a4 | SummerBigData/SurenRepo | /Coursera.EX4/neuTrainerMNISTfast.py | 10,193 | 3.90625 | 4 | # Written by: Suren Gourapura
# Written on: May 25, 2018
# Purpose: To solve exercise 4 on Multi-class Classification and Neural Networks in Coursera
# Goal: Use backpropagation to find the best theta values
# Import the modules
import numpy as np
from math import exp, log
from scipy.optimize import minimize
impor... |
20aaf3f2d92a6c68635b31c55aaa48368fd05c89 | alblaszczyk/python | /codecademy/pmp10.py | 212 | 3.53125 | 4 | def censor(text, word):
lst = text.split()
new = []
for item in lst:
if item != word:
new.append(item)
else:
censored = "*" * len(item)
new.append(censored)
return " ".join(new)
|
3753f6c95c24cdef207706259943b633a513a895 | mrzhouyu/Automated_Test | /PishOTA/testone.py | 724 | 3.65625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2018/12/8 16:39
# @Author : YuChou
# @Site :
# @File : testone.py
# @Software: PyCharm
import multiprocessing
import time
import threading
class Demo:
def __init__(self, thread_num=5):
self.thread_num = thread_num
def productor(self, i):
print("th... |
cbfbce823f2ebbce9a622fbed4f2e73e0a01e211 | ProjectBWeb/Cosmosium | /js/MPO_data/csv2json.py | 537 | 3.59375 | 4 | import csv
import json
def csv2json(csvFile, headers=True):
# converts csv in fname csv to json @ json fname
# if headers==True, read them from file, else assume header is list of header strings.
csvfile = open(csvFile, 'r')
jsonfile = open(csvFile.split('.')[0]+'.json', 'w')
if headers!=True:
... |
5f583abd4b34305719072e2096ed693d2fe3f385 | esrefaltug/kutuphaneuyg | /ktphane uygulama.py | 1,739 | 3.9375 | 4 | import os
kitapListe=list()
menu="""
[1]Kitap Ekle
[2]Kitap Al
[3]Tümünü Listele
[Q]Çıkış
"""
def kitapEkle(kitap:tuple,liste:list):
liste.append(kitap)
print("Ekleme işlemi tamamlandı")
print("Ana menüye dönmek için enter'e basın.")
input()
def kontrol(kitap:tuple,liste:list):
... |
9c1d558865fc26efd9bef5401d1e5e476bb670a6 | AlexMarquez-coder/Beroepsopdracht-week-1-10 | /Tekstbased applicatie in Python.py | 2,906 | 3.59375 | 4 | import time
# hier worden de functions
def verhaalstukje1():
print("Hallo mijn naam Naya ik ben 11 jaar en woon in Syrië")
print ("A. Naar buiten gaan")
print ("B. Binnen blijven")
antwoord= input("Maak een keuze, A of B? ")
if antwoord=="A":
verhaalstukje2()
# naar buiten
eli... |
58e4ad602784651764a408058f0acb6cf90e501c | sandrahdezledesma/TIC2-SandraHernandez | /Concatenador.py | 290 | 3.640625 | 4 | def Concatenador():
nombre= raw_input ("Dime tu nombre")
apellido1= raw_input ("Dime tu primer apellido")
apellido2= raw_input ("Dime tu segundo apellido")
NombreCompleto= nombre+" "+apellido1+" "+apellido2
print "Te llamas" + NombreCompleto
Concatenador()
|
139c17056de0c7e08953b97658e1a603bc10ee6c | Pandalism/Advent_of_code | /day2/solution_day2.py | 2,716 | 4.09375 | 4 | # Advent of Code - Day 2
#
# Part 1: find number of passwords within text file that are valid
# format is:
# 1-3 a: abcde
# 1-3 b: cdefg
# 2-9 c: ccccccccc
# Where the password is after the colon and the password requirements are before.
# The letter before the colon is required to be in the pas... |
f401b3272d8cdf6c0e70cc8b34fb2170a6423354 | tsjamm/LPyTHW | /ex04.py | 622 | 3.71875 | 4 | bikes = 50
space_in_a_bike = 3.0
drivers = 30
passengers = 50
bikes_not_driven = bikes - drivers
bikes_driven = drivers
transport_capacity = bikes_driven * space_in_a_bike
average_passengers_per_bike = passengers / bikes_driven
print "There are", bikes, "bikes available."
print "There are only", drivers, "drivers ava... |
6def46475623fbd84687fa150530df67d48581f4 | haidfs/LeetCode | /Hot100/最长连续序列128.py | 1,774 | 3.515625 | 4 | # 给定一个未排序的整数数组,找出最长连续序列的长度。
#
# 要求算法的时间复杂度为 O(n)。
#
# 示例:
#
# 输入: [100, 4, 200, 1, 3, 2]
# 输出: 4
# 解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4
from collections import defaultdict
class Solution(object):
def longestConsecutive(self, nums):
if not nums:
return 0
nums = list(sorted(set(nums)))
... |
7c40a657bc5411f26a150cafc16063e8d0a38f36 | IvanWoo/coding-interview-questions | /puzzles/couples_holding_hands.py | 1,813 | 3.75 | 4 | # https://leetcode.com/problems/couples-holding-hands/
"""
N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats.
The people and seats ... |
07c7aedebff35f9dfe43c1321862209a7cbe80c6 | Niptlox/Phis | /Billiard.py | 10,619 | 3.578125 | 4 | import pygame
SX, SY = 1000, 1000
FPS = 30
def circle(screen, x, y, r, color=(255, 0, 0)):
cof = 10
x = x * cof + SX // 2
y = y * cof + SY // 2
r *= cof
pygame.draw.circle(screen,
color,
(int(x), int(y)),
... |
33ce45941c0a1c347d258f5ef0e7a66e70268ae7 | caihj/jbyte | /src/main/resources/class.py | 309 | 3.546875 | 4 | #coding:utf-8
class foo():
def __init__(self,a):
self.a=a
self.b=2
def show(self):
print self.a
class Too(foo):
def __init__(self,a):
foo.__init__(self,a)
f=foo(2)
d=foo(3)
f.show()
d.show()
q=Too(6)
q.show()
if q < f:
print "sss"
|
3a2714e1fe3f8a7845ddb76e1ef5f93ff5f29e48 | Hasthon/python-beginner-programming-exercises | /exercises/22-Bottles-Of-Milk/app.py | 1,374 | 3.9375 | 4 |
def number_of_bottles():
for i in range(99,-1,-1):
if i == 1:
print('1 bottle of milk on the wall, 1 bottle of milk.')
print('Take one down and pass it around, no more bottles of milk on the wall.')
elif i == 0:
print('No more bottles of milk on the wall, no more... |
e3237e0a3466ea238d3698db75d81f9304349f9d | JingzOoi/pygame_sudoku_solver | /main.py | 7,564 | 3.765625 | 4 | import pygame
import sudoku
class Grid(sudoku.Grid):
"""A space on a Sudoku board. Holds a value unique to row, column, and box."""
SIZE = 50
COLOR_BACKGROUND = (255, 255, 255)
COLOR_TEXT = (0, 0, 0)
def __init__(self, pos: tuple, value: int = None):
super().__init__(pos, value)
... |
09b3f5135c37cfdbbf3aa08bf393712c1b8469d0 | sunho-park/study1 | /numpy/indexing.py | 367 | 3.578125 | 4 | import numpy as np
array1d = np.arange(start=1, stop=10)
print(array1d)
print(array1d>5)
array3d=array1d[array1d>5]
print(array3d)
boolean_indexes = np.array([False, False, False, False, False, True, True, True, True])
# True 에 해당하는 인덱스의 값을 저장
array3 = array1d[boolean_indexes]
print('불린 인덱스로 필터링 결과 : ', array3)
|
f6be3854a04c09b4199d2776a2a7d9272b899136 | jamesthekee/password-manager | /Client/lib/clientconfig.py | 673 | 3.796875 | 4 | import configparser
"""
This module is just for extracting the variables from the config file,
converting them to their correct data type and returning them to the main program.
"""
config = configparser.ConfigParser()
config.read("clientconfig.ini")
def is_int_string(s):
try:
int(s)
... |
e4964b57defd22d44d4866fe7e1d9281d11c4b92 | annusabu/Task | /P1.py | 271 | 3.625 | 4 | def star(words):
size = max(len(word) for word in words)
print('*' * (size + 4))
for word in words:
print('* {:<{}} *'.format(word, size))
print('*' * (size + 4))
f = open(r"E:\file1.txt")
for line in f:
s=line.split()
star(s)
|
b50cdba4fec9c0faf4813c0651e22ea4ec0f1e1e | ArnoutAllaert/Informatica5 | /08-Functies/Ave Caesar.py | 944 | 3.640625 | 4 | def is_letter(n):
if n in 'abcdefghijklmnopqrstuvwxyz' or n in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
waarheid = True
else:
waarheid = False
return waarheid
def roteer_letter(n, k):
if is_letter(n) == True:
if n in 'abcdefghijklmnopqrstuvwxyz':
if ord(n) + k > 122:
... |
1e3f2491b3d011451f1c8b031c9e1943ab63e849 | wllmwng1/CMPUT366_Assignment3 | /A_3_Code/mc_agent.py | 2,946 | 3.625 | 4 | #!/usr/bin/env python
"""
Author: Adam White, Matthew Schlegel, Mohammad M. Ajallooeian, Sina Ghiassian
Purpose: Skeleton code for Monte Carlo Exploring Starts Control Agent
for use on A3 of Reinforcement learning course University of Alberta Fall 2017
"""
from utils import rand_in_range, rand_un
impo... |
7d2f253eee14961a59163144a71465cba144c126 | Gemisheresy/DungeonCrawl | /grid2.py | 2,078 | 3.703125 | 4 | import curses
from curses import wrapper
from grid import *
stdscr = curses.initscr()
stdscr.keypad(True)
def start():
# starts game by creating to loops
done = False
while True:
try:
wide = int(input("How wide do you want the room? "))
break
except ValueError:
... |
e48f523d3b1bed4d82dc11760a7803782b3b7ace | nikkisora/cses_problemset | /10 Advanced Techniques/10 Necessary Cities.py | 993 | 3.828125 | 4 | '''
CSES - Necessary Cities
Time limit: 1.00 s
Memory limit: 512 MB
There are n cities and m roads between them. There is a route between any two cities.
A city is called necessary if there is no route between some other two cities after removing that city (and adjacent roads). Your task is to find al... |
2ec409f18f8144ef3b575933497fe389451a118b | iamthedkr/AIVN-Course-2019 | /Week1/2. Bài tập lý thuyết/bai1.py | 317 | 4.09375 | 4 | #Chuyen goc tu do sang radian
import math
degree = float(input("Input Degree: "))
#tinh goc theo radian
radian = degree * math.pi / 180
print("Radian: ", radian)
#Chuyen goc tu radian -> do
radian_change = float(input("Input Radian: "))
degree_change = radian * 180 / math.pi
print("Degree: ", degree_change)
|
9e59992966b164875b6da721b0f1554a4f34d13d | sejun09/sejun | /E-oN 4주차 과제.py | 646 | 3.890625 | 4 | a = list(map(int, input("오름차순으로 정렬할 숫자를 입력하세요: ").split()))
def bubble_sort(bubble):
for i in range(1, len(bubble), 1): # list에 입력된 숫자의 갯수만큼 반복
for j in range(1, len(bubble), 1 ): # list의 첫번 째 자리부터 list의 마지막 자리까지 1씩 더해가며 정렬
if bubble[j-1] > bubble[j]:
bubble[j-1], bub... |
f7a9aeb77884dc1e0650201dc938afd6b6354134 | ParkinWu/leetcode | /python/leetcode/209.py | 1,488 | 3.5625 | 4 | # 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组。如果不存在符合条件的连续子数组,返回 0。
#
# 示例:
#
# 输入: s = 7, nums = [2,3,1,2,4,3]
# 输出: 2
# 解释: 子数组 [4,3] 是该条件下的长度最小的连续子数组。
# 进阶:
#
# 如果你已经完成了O(n) 时间复杂度的解法, 请尝试 O(n log n) 时间复杂度的解法。
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/minimum-size-subarray-sum
# 著作权归领扣网络所有。商... |
4a4ebe06465a7dc45c746e15f0aeb23f4abd55b9 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/difference-of-squares/64253a2e99094e2f9e5e03adb295f1bf.py | 275 | 3.984375 | 4 | def square_of_sum(n):
sum = 0
for k in range(0,n+1):
sum += k
return sum**2
def sum_of_squares(n):
sum = 0
for k in range(0,n+1):
sum += k**2
return sum
def difference(n):
return square_of_sum(n) - sum_of_squares(n)
|
bbd3c7e878116923f0d011ce6b6ccd547b69be82 | Neczy/tech_task | /json_file/json_open.py | 1,172 | 3.59375 | 4 | #ещё не до конца, нужен валидатор и счетчик
# -*- coding: utf-8 -*-
import os
import sys
import json
#статические переменные
errors = list()
user_input = input('Введите имя файла: ')
#счетчик ошибок
def ercount():
errors.append()
# основная функция, потом в класс
def open_json():
try:
with ope... |
cb61b3d57fef83ce2bbb13997552fd1af600e0f8 | awscott/teachingpythontokwan | /solutions/.sum_even_odd.py | 882 | 4.3125 | 4 | import sys
# given a number return the sum of all the even numbers
# the only point is to use your previously created methods in python and use them here
def sum_even(number):
"""
sum up all the the even numbers between 0 and number inclusive
return the result when you are finished
"""
total = 0
for i in range... |
02c81afc6cdc2986c9216571ade30f951b9d0315 | madRebellion/Software-Development | /Python/PythonCourse/Day2/Operators_fStrings.py | 1,300 | 4.21875 | 4 | #-----------------------------------------------------------------
# String indices and conversions
#digit = input("Type in a two digit number: ")
#firstDigit = int(digit[0])
#secondDigit = int(digit[1])
#print(firstDigit + secondDigit)
#-----------------------------------------------------------------
# BMI Calc 1.0... |
4202325b897f0383f40bb946a924d5b2c4b962c4 | jamolinav/Python-Spanish | /python/fundamentals/underscore.py | 1,389 | 3.84375 | 4 | import functools
class Underscore:
def map(self, iterable, callback):
# tu código aqui
lista = list(map(callback , iterable))
return lista
def find(self, iterable, callback):
# tu código aqui
lista = list(map(lambda x: x if callback(x) else None , iterable))
li... |
7a40df755c658a5ed3c158fd94ba2ada08fd8e04 | joaoo-vittor/estudo-python | /revisao/aula1.py | 281 | 3.96875 | 4 | """
Tipos de dados
str -> string
int -> inteiro
float -> real/ponto flutuante
bool -> boolean
"""
print('João', type('João'))
print('10', type('10'))
print(10, type(10))
print(10.79, type(10.79))
print(True, type(True))
"""
Operadores Artmeticos
+, -, *, /, //, **, %, ()
"""
|
b3b61fe51fee23d1d536bd2536b4ffce4281d3e2 | emyhr/smoking_vis_data | /tobacco_sales.py | 1,792 | 3.828125 | 4 | import altair as alt
import streamlit as st
import pandas as pd
import numpy as np
sales_data = pd.read_csv('data/sales-of-cigarettes-per-adult-per-day.csv',
header=0,
names=[
'Country',
'Code',
'Year',
... |
f4f758b327e013706e74b2f1ec0f5982982f6704 | aseldan/aseldan.github.io | /primes.py | 299 | 3.84375 | 4 | def is_prime(n):
if n<=1:
return False
else:
for i in range(2,n):
if n%i==0:
return False
else:
return True
def primes_below(n):
l=[]
for i in range (2,n):
if is_prime(i):
l.append(i)
return l
|
d93aa4e748e31f984ee651fd9d68cc418fd3214b | gowentgonemax/InnovationPython_ravishah | /Task_7.py | 3,322 | 4 | 4 | '''1. Write a program that calculates and prints the value according to the given formula:
Q= Square root of [(2*C*D)/H]
Following are the fixed values of C and H:
C is 50.
H is 30.
D is a variable whose values should be input to your program in a comma-separated sequence.'''
C = 50.
H = 30.
import math
d_value = list... |
a61dab2324121e5e9b9e194f50b3a216fae7b731 | lagachea/expert-system | /tool.py | 1,638 | 3.546875 | 4 | def remove_charset(string, charset):
'''
return a copy of string without chars from charset
'''
copy = ''
for i in range(len(string)):
if not string[i] in charset:
copy = copy + string[i]
return(copy)
def get_query(lines):
'''
take the lines of the files and return t... |
5d7a55a04b8e75bf510c4253a81a3a9c71c0d01f | shovan99/snakeWaterGame | /helloWorld.py | 2,841 | 3.90625 | 4 | import random
total_limit=10
current_limit=0
computer_point=0
your_point=0
while(current_limit<total_limit):
print("press 's' for snake, press 'w' for water and press 'g' for gun")
userInput=input()
list=["s","w","g"]
s=random.choice(list)
if userInput==s:
... |
c84559f65e1580a4a633233e30719c20720bb790 | dev-junseo/Python | /prime_num_checker.py.py | 561 | 3.828125 | 4 | num = int(input("소수 검사를 할 정수를 입력하시오 : "))
num_list = []
def make_num_list(number):
if number == 2:
num_list.append(number)
return num_list
elif number > 2:
for i in range(2, number):
num_list.append(i)
return num_list
count = 0
make_num_list(num)
for i i... |
c5051f6c71737b3ef21bacfc3114d227d5e40f68 | MakeSchool-17/twitter-bot-python-beingadrian | /2_dictionary_words/vocab_game.py | 683 | 3.984375 | 4 | import random
import os
dict_file = open("/usr/share/dict/words", "r").readlines()
def generate_random_word():
random_word = random.choice(dict_file).rstrip("\n")
return random_word
def print_with_style(word):
print("="*len(word))
print(word.upper())
print("="*len(word))
if __name__ == "__mai... |
5841080e3dada4db30b4a3a41b98215c0a554f96 | jslhost/scrabble | /scrabble.py | 1,762 | 3.90625 | 4 | def scrabble() :
import urllib
#A text file containing French words
liste = []
url = "http://jph.durand.free.fr/scrabble.txt"
file = urllib.request.urlopen(url)
for line in file:
liste.append(line)
mots_francais = set()
for elt in liste[1:] :
mots_francais.add... |
05d5cb86ed4401440abe1afd31e6ee761f376060 | pyomeca/bioptim | /bioptim/examples/getting_started/example_cyclic_movement.py | 4,709 | 3.578125 | 4 | """
This example is a trivial box that must superimpose one of its corner to a marker at the beginning of the movement
and superimpose the same corner to a different marker at the end. Moreover, the movement must be cyclic, meaning
that the states at the end and at the beginning are equal. It is designed to provide a c... |
812952260efa794766b8806c1ebcfe46c7169125 | jaiswalIT02/pythonprograms | /Chapter-3 Loop/ifelse.py | 172 | 3.734375 | 4 | option=int(input("Enter 0 for 1 to 10 & 1 for 10 to 1 == "))
for i in range(1,11):
if option==0:
print(i)
else:
print(11-i)
|
503b7a75ee7915305ad9cb3e423c07198bd7f2e5 | fluxgame/ALGS200x | /inversions.py | 1,483 | 3.515625 | 4 | # Uses python3
import sys
def get_number_of_inversions_naive(a):
count = 0
for i in range(0, len(a)):
for j in range (0, len(a)):
if i < j and a[i] > a[j]:
count += 1
return count
def merge(l, r, a):
number_of_inversions = i = j = k = 0
# print(f"pre-merge: {... |
baba8c39f58a588edeeffa32e760e0f5b008fab0 | jiwon73/lecture_4_1 | /lecture_4/try_except_zerodiv.py | 325 | 3.5 | 4 | try:
a,b=input('두수를 넣으세요').split()
result=(int(a)/int(b))
print(result)
except ZeroDivisionError:
print('0으로는 나눌 수 없습니다')
except TypeError:
print("지원하지 않는 연산자 입니다.")
except Exception as e:
print('오류 종류; {}'.format(e))
print('Test') |
b6874fb47f4f173b235fb34838c2dd1fa6fb71e2 | UnSi/2_GeekBrains_courses_algorithms | /Lesson 3/hw/task6.py | 998 | 4.09375 | 4 | # 6. В одномерном массиве найти сумму элементов, находящихся между минимальным и максимальным элементами.
# Сами минимальный и максимальный элементы в сумму не включать.
from random import randint
min_value = 1
max_value = 100
rand_array = [randint(min_value, max_value) for _ in range(10)]
print(rand_array)
max_value, ... |
424031acc6fd3816f8b020226c8d190755dfb583 | monlie/LeetCode | /173.py | 835 | 3.859375 | 4 | # Definition for a binary tree node
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def bst(root, l):
if root:
bst(root.left, l)
l.append(root.val)
bst(root.right, l)
class BSTIterator(object):
d... |
f95cace1d6f2a82110bd14b69f541b5bcedd0da0 | bheki-maenetja/small-projects-py | /courses/python_data_structures_queues/Exercise Files/Ch03/03_03/End/queues.py | 591 | 4.3125 | 4 | class Queue:
def __init__(self):
self.items = []
def enqueue(self, item):
"""Takes in an item and inserts that item into the 0th index of the list
that is representing the Queue.
The runtime is O(n), or linear time, because inserting into the 0th
index of a list forces... |
d49e32dfb391de090ea4e79e13c10498666efe60 | mysilver/COMP9321-Data-Services | /Week2_DataAccess/activity_3.py | 2,256 | 3.859375 | 4 | import json
import pandas as pd
from pymongo import MongoClient
def read_csv(csv_file):
"""
:param csv_file: the path of csv file
:return: A dataframe out of the csv file
"""
return pd.read_csv(csv_file)
def print_dataframe(dataframe, print_column=True, print_rows=True):
# print column names... |
cf22a711febb18730bb37da217883aa67910570b | Tomolo997/Fri-mag | /programiranje/Chapter_Two.py | 2,193 | 4.21875 | 4 | #Data structures
# collection of data elements, that is structured in some way
# 6 types of sequences
# tuples
# list
# ..
# tuples => cannot change it
# list => can change it
#e Python has a basic notion of a kind of data structure called a container, which is basically any object
#that can contain other objects
#... |
2ef3eeba8a596cc80488a1ee34e7c021a3602b5e | yoonwoolee/efp | /3-13.py | 673 | 4 | 4 | #!/usr/bin/env python
if __name__ == '__main__':
principal = input('What is the principal amount? ')
rate = input('What is the rate: ')
number_of_years = input('What is the number of years: ')
number_of_times = input('What is the number of times the interest\nis compounded per year: ')
money = ... |
9227870c394ceb9683aed545141cb8cb3a44ae67 | dubeamit/Daily_Coding | /comp_num_strings.py | 604 | 4.03125 | 4 | #compare two strings(s1,s2) as numbers and return True if s1>s2 else return False (cannot convert to int)
#eg: larger_than('334', '333')--> True
#eg: larger_than('525','6666')--> False
#eg: larger_than('11','0') --> True
#eg: larger_than('10','10') --> False
def larger_than(s1, s2):
if len(s1) > len(s2):
r... |
46bc6f63bff375cda10e82b48e730613ac77619d | zzeleznick/zzeleznick.github.io | /python-practice/test.py | 2,894 | 4.1875 | 4 | #!/usr/bin/env python3
import os
import sys
def parse_file(path):
"""
Parses the text file in the given path and returns space, tab & new line
details.
:arg path: Path of the text file to parse
:return: A tuple with count of spacaes, tabs and lines.
"""
fd = open(path)
i = 0
spa... |
7d48a259074c2284cb04fceacca1bb1e34d3e68e | LMMilewski/learn_python | /metaclasses.py | 2,650 | 3.5625 | 4 | #!/usr/bin/python2.7
import logging
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
######################################## simple class
class Car(object):
brand = "audi"
def __init__(self, model, doors_count=5):
self.model = model
self.doors_count = doors_count
def go(s... |
ddaf922da8a981b54d066f7c9adafb0e18be2b16 | c0fec0de/anytree | /anytree/search.py | 7,330 | 3.59375 | 4 | """
Node Searching.
.. note:: You can speed-up node searching, by installing https://pypi.org/project/fastcache/ and
using :any:`cachedsearch`.
"""
from anytree.iterators import PreOrderIter
def findall(node, filter_=None, stop=None, maxlevel=None, mincount=None, maxcount=None):
"""
Search nodes m... |
15cfbabbd993274f6233b0766fed1f4c9831d9e2 | strozzi1/cs325-Algorithms | /assign3/closest_unsorted.py | 1,239 | 3.625 | 4 | import random
from random import randint
def find(a, x, k): ##params: array, comparison number, number of near numbers
diffarray = [abs(y-x) for y in a] #array of the difference between each element and x
ksmallest = quickselect(k, diffarray)
#print("k: ", ksmallest)
#return pivot
index ... |
f1aa094f568d8d8e5b09d2a476b26911a3256691 | Anaa29/Python-codes | /Rangoli(turtle).py | 215 | 3.6875 | 4 | from turtle import *
bgcolor("black")
speed(0)
for i in range(8):
for col in ('red','cyan','white','magenta','yellow'):
color(col)
circle(100)
right(10)
hideturtle()
|
4fee3f2529c5d12558fbe2cea660b6ee6d57c57e | pascalmouret/nand2tetris | /06/assembler/symbols.py | 485 | 3.53125 | 4 | from typing import Dict, Optional
class SymbolTable():
def __init__(self, defaults: Dict[str, int]) -> None:
self.next_variable = 16
self.table = defaults
def address_for_symbol(self, symbol: str) -> int:
if symbol not in self.table:
self.table[symbol] = self.next_variable
... |
6c8832b62d67e7762e2f53d327159e53409cf381 | Mnandala1/rajab-kassim | /TRIAL.py | 4,336 | 4.28125 | 4 | '''
#EXCERCISE 1
message = 'hi my name is Rajab learning python'
print(message)
print('\n')
mylist = message.split()
print(mylist)
mylist.sort()
print(mylist)
print('\n')
message = 'I hope I can master it'
print(message.title())
name = "Ada Lovelace"
print(name.upper())
print(name.lower())
first_name = 'Rajab'
seco... |
522602478a00c80c619341bcfa2d532ef5619f44 | namth2015/python | /1.DataScience/2.BigO/Green18/lec11_ascending_sort.py | 620 | 3.65625 | 4 | def insertionAsc(a,n,x):
j = n
a.append(x)
while j >= 0:
if j == 0:
break
if a[j-1] <= x:
break
a[j] = a[j-1]
j -= 1
a[j] = x
return a
def insertionSort(a):
m = len(a)
if m == 1:
return a[0]
for i in range(1,len(a)):
... |
20f0004c76d606ab9c632f57620e33554679d5e7 | melthewarrior12/.spyder-py3 | /proj04.py | 10,997 | 4.3125 | 4 | ''' Project 4 play the game of "Craps"
player is promted for inputs to play the game
which is computed within the functions
main function plays the game calling other functions to shorten the main
main will play through first roll - win, loss or point
if the first roll results in point, the dice ar... |
ec660ce11461e8748f50fecfeae5e53a582230fa | QPromise/DataStructure-UsingPython | /7.图形结构/CH07_05.py | 2,734 | 3.8125 | 4 | MAXSIZE=10 #定义队列的最大容量
front=-1 #指向队列的前端
rear=-1 #指向队列的末尾
class Node:
def __init__(self,x):
self.x=x #顶点数据
self.next=None #指向下一个顶点的指针
class GraphLink:
def __init__(self):
self.first=None
self.last=None
def my_print(self):
... |
e4ce1ea0a3a39c6b01044283ec4a1b13c228408b | Juaquigm/Pruebita | /Prueba.py | 256 | 3.65625 | 4 | print("Esto es una prueba para ver si funciona: ")
input("Introduzca un numero: ")
#Supongamos un ejemplo que esto es editado en la pagina web
print("Esto es de la página web")
#Esto esta hecho en el Visual Studio
print("Esto es del editor visual Studio") |
0cd98062fad1f4f8671a1ae40666a71cb4c546c0 | tommparekh/Py.WebCrawler | /webcrawler.py | 2,706 | 3.546875 | 4 | #Create a web crawler example from Udacity course.
import requests
from bs4 import BeautifulSoup
import time
import urllib
#Open an article
start_url = "https://en.wikipedia.org/wiki/Special:Random"
end_url = "https://en.wikipedia.org/wiki/Philosophy"
def continue_crawl(search_history, target_url, max_step=25):
#i... |
d5162b2eeb4763a7b22da4ef3a79b50e95beff2e | ATLS1300-CoFo1/Examples | /FINAL-nextPiece.py | 2,288 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 26 12:01:00 2020
@author: Dr. Z
Keypress refresh for GENERATIVE ART GALLERIES
When creating your art, this will allow a keystroke to be added in that will clear your screen.
In the code following, you can generate the next piece.
I recommend organi... |
2577468e47b8bb52274532b33afd097916490a3d | eunjungchoi/algorithm | /leetcode/most_liked/49_group_anagrams.py | 1,160 | 3.984375 | 4 | # Given an array of strings strs, group the anagrams together. You can return the answer in any order.
#
# An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
#
#
#
# Example 1:
#
# Input: strs = ["eat","tea","tan","ate",... |
897e78f9178aa37a0fd28ca166f1bc727c56588f | leohujx/leetCode | /397.py | 889 | 3.890625 | 4 | # coding:utf-8
# 397. Integer Replacement
# https://leetcode.com/problems/integer-replacement/description/
'''
在n向1的转变过程中,如果n为偶数,那一定是/2;当n为奇数的时候,n+1或者n-1,这两个都有可能.
所以我们用dfs来进行搜索,搜索过程中取n+1和n-1小的那个.注意用记忆化搜索,这样可以节省大量的时间.
'''
class Solution(object):
def integerReplacement(self, n):
"""
:type n: int
... |
96b16d3f976c5a87d55935b3da36cdd953aeada7 | alexsks65536/Python-base | /lesson08/lesson8-1.py | 1,490 | 3.625 | 4 | '''
1. Написать функцию email_parse(<email_address>), которая при помощи регулярного выражения извлекает имя пользователя
и почтовый домен из email адреса и возвращает их в виде словаря. Если адрес не валиден, выбросить исключение ValueError
#>>> email_parse('someone@geekbrains.ru')
{'username': 'someone', 'domain': ... |
866697cbf17faa2752a36b29578f5d093fb8196b | wantwantwant/tutorial | /L3函数(重要)/作业2---4.py | 417 | 4.0625 | 4 | # 输出斐波拉切数列(1, 1, 2, 3, 5, 8, 13, 21, ...)
print('1、','1、',end='')
def fibs(num):
print
def fibs(num):
result = [0, 1]
for i in range(2, num):
result.append(result[-2] + result[-1])
return result
print(fibs(9))
def fibs(num):
if num == 1:
return 1
else:
return ... |
20bde4f3178844c32dc7521ce36dbd91eb7f6390 | kristinhelps/Kal_Academy | /Homework_2_Classification_Challenge.py | 8,614 | 3.84375 | 4 | # Classification template
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
# sklearn preprocessing for dealing with categorical variables
from sklearn.preprocessing import LabelEncoder
# Importing the dataset - only using
dataset = pd.read_csv('ap... |
3751e938ae0ebbfa7ced14dc001055f4feb9a7c0 | boknowswiki/mytraning | /lintcode/python/1512_minimum_cost_to_hire_k_works.py | 1,556 | 3.53125 | 4 | #!/usr/bin/python -t
# heap
# 对每一组的quality和wage计算时薪,按照时薪排序。
# 对于合法的k个数,为了满足条件,每个人的工资都大于初始工资,且成比例,所以每个人的时薪一定是这k个人中最高的那个人的时薪(否则最高的人不满足初始工资)。
# 所以对每个人的时薪找k个quality和最小的且时薪低于这个人的即可。
# 利用优先队列即可完成上述操作。
import heapq
class Solution:
"""
@param quality: an array
@param wage: an array
@param K: an integer
... |
ccbd8516f1f473129b1ab6c749b45d8ab2df4c79 | SkarletA/ejercicios | /raiz_digital.py | 670 | 3.9375 | 4 | """ Ejercicios 20.- Dado un número natural N, se calcula la raíz digital de N sumando los dígitos que
lo componen. El proceso se repite sobre el nuevo número hasta que el resultado
obtenido tiene un sólo dígito. Este último número es la raíz digital del número N.
Ejemplo: 347 ->3 + 4 + 7 = 14 -> 1 + 4 -> 5 -> Raíz digi... |
0652955a435b72fbbe93a73e863ab309f1fa3c0a | sumitsk1/Old-Python-Codes | /guess the name and age.py | 199 | 3.890625 | 4 | name=input("Enter your name")
age=int(input("How old you are"))
if (name=="sumit") and 16<age<30:
print("Welcome to you for 6 days holidays")
else:
print("Sorrry your not allowed")
|
6b0c5f93f58b93e425032dd64bc523de14a8f24b | DoxMeister/TileTraveller | /tile_traveller.py | 2,296 | 3.96875 | 4 | #Define the grid 3*3
def can_go(n,s,e,w):
counter = 0
ret = "You can travel: "
if n :
ret += "(N) orth"
counter += 1
if s:
if counter == 1 or 2 or 3 or 4:
ret += " or "
ret += "(S) outh"
counter += 1
if e:
if counter == 1 or 2 or 3 or ... |
cfd119ab152c7b50d87d2a5430bda810972523de | ikeshou/Kyoupuro_library_python | /src/mypkg/basic_algorithms/around_quick_sort.py | 5,568 | 3.5 | 4 | """
(参考) <Algorithm Introduction vol.1 p.24-35, p.140-152, 177-180>
クイックソートテク関連の基本的な関数の詰め合わせ (命名は C++ STL algorithm による)
randomized_select(seq, k, begin, end):
O(n)
E = seq[k] とする
特定の要素 E よりも小さい全ての要素が E よりも前になり、 E 以上の全ての要素がEよりも後になるように seq[begin:end] を並び替える (破壊、不安定)
nth_element(seq, i, begin, end):
... |
e730b539643d37b303182e2f463cf6b9751d754b | Lstanislao/Proyecto-Indexing | /tables.py | 3,809 | 3.640625 | 4 | from funciones import pedirPelicula
peliculas = [
]
titulos = [
]
codigos = [
]
def agregarPelicula():
global peliculas
peli = pedirPelicula()
peliculas.append(peli)
index = peliculas.index(peli)
titulo = peli[2].lower()
codigo = peli[1]
agregarTitulo(titulo, index)
insertarCodigo(c... |
2b017f6f993a63460f63a6b1712df3ca648d8f81 | SujeethJinesh/Computational-Physics-Python | /In Class/jan_19.py | 189 | 4.0625 | 4 | def ask_for_input():
odd = int(input("Enter an odd number: "))
even = int(input("Enter an even number: "))
if odd%2 == 1 and even%2 == 0:
print "Nice job!"
else:
print "You suck." |
1f09596ea5b2f7076f2e87d66086663f5ac847b3 | Taburetkastol/PythonLabs | /Lab3/main.py | 1,614 | 3.59375 | 4 | # 4 задание
def count(number):
k = 0
for i in range(1, number):
if number % i == 0:
k = k + 1
return k
def biggest_number(a, b):
k = 0
l = list()
m = list()
for i in range(a, b - 1):
if k < count(i):
k = count(i)
for i in range(a,... |
87bc2075b57a6eba9f00321e7244f74e40365e42 | AlvaroLopez-Jurado/python_template | /sample/strings_example.py | 764 | 3.875 | 4 | class StringsExamples(object):
"""A class to play with the strings"""
@staticmethod
def concat_strings(strings):
if(len(strings)< 2 or len(strings)>10 ):
raise TypeError("Maximo numero de strings 10 y minimo 2")
for x in range(len(strings)):
if(type(strings... |
c0b88f692f1b8bd4bc5284e1c3015093e5ca7bdf | sanath777/Python | /perfectSquare.py | 158 | 4 | 4 | import math
n=int(input("Enter a number"))
a=int(math.sqrt(n))
if (a**2==n):
print("Perfect Square")
else:
print("Not Perfect Square")
|
5185d78b2060db631367ddd66c3159e00d6e6609 | DrDoobie/python | /python intro/calculator/calc.py | 932 | 3.9375 | 4 | result = float
success = bool
def mainFunc ():
var1 = input("Input First Number: ")
var2 = input("Input Second Number: ")
calcType = input("What do you want to calculate for? ")
if calcType != "sum" and calcType != "product" and calcType != "difference" and calcType != "quotient":
print("Try u... |
e14b119af11e15de775b922d1c5ec9d43e6be7e1 | MikeOcc/MyProjectEulerFiles | /Euler_4_157d.py | 913 | 3.515625 | 4 |
#
# Problem 157
#
from time import time
from math import floor
from math import ceil
from Functions import RetFact
def diophantine(a,b,P,n):
#10**n*b = a * (b*P - 10**n)
# a = 10**n*b/(b*P - 10**n)
return 10**n*( b + a)==a*b*P
#for i in xrange(1,10):
st = time()
n= 1
a,b =0,0
N = 9
ctr = 0
for n in xrange(... |
2cb69131a49cf7a7868f29a146ac59aa4ca6939b | BoredPotatoDev/PLD-40-Programs | /Exercise_17_Pie_Eating_Contest.py | 122 | 3.609375 | 4 | x = int(input("Input weight in pounds: "))
if x in range(30,250):
print("Accepted!")
else:
print("Denied!") |
dcba69a83322ce8d8ddc00b38c38fc493d56dc9e | Marciodm/check-bad-words | /check_file.py | 659 | 3.84375 | 4 | def read_file():
"""Abre o arquivo .txt a ser verificado."""
with open(r'files\text_file.txt') as file:
contents = file.read()
# print(contents)
check_file(contents)
def check_file(text_check):
"""Abre o arquivo contendo as palavras a serem procuradas"""
with open(r'files/bad_file.txt'... |
bcf39cdcb5840be298dce57bf45fe6e44d7c7c04 | insigh/Practical-ReinforcemntLearning | /windows/toutiao4/3.py | 4,483 | 3.6875 | 4 |
"""
5 5 3
hello help high
p a b h m
f h e c p
o i l l h
b g h o n
h x c m l
"""
# from collections import defaultdict
#
#
# class Cell():
# def __init__(self, value):
# self.value = value
# self.visited = False
#
# def __str__(self):
# return '{},{}'.format(self.value, self.visited)
#... |
471937550451a925ca51bcba63acb172964c58ae | Yash-barot25/DataStructresInPython | /Sets/setchallenge.py | 433 | 3.96875 | 4 | text = input("Enter something:\n").upper()
# text_char = list(text)
# consonants = set()
#
# for i in text:
# if i not in 'AEIOU ':
# consonants.add(i)
# print(sorted(text_char))
# print(sorted(consonants))
# set_value = set("a", "e", "i", "o", "u")
set_value = {"a", "e", "i", "o", "u", "A", "E"... |
e2a1b92f5aa9a8bb02bf9f2299e7c0ba11bb8e21 | muralimohanreddy319/Competitive-Programming | /week4_exam/consecutive.py | 431 | 3.59375 | 4 | def consecutive(num):
if(num==0):
return 0
binary = bin(num)[2:].strip()
# print binary
if num < 0:
limit = len('{0:b}'.format(num))
binary = ('{0:b}'.format(num + (1 << 32)))[-limit:]
res = binary.split('1')[:-2]
if(res==[]):
return 0
return max(len(str)+1 for str in res)
print consecutive(55)
pr... |
1f930cf89f9e1574ed19affc18c499dacef5a3a1 | gohan-1/speech-to-wave | /Documents/python itern/extra works/search/search.py | 160 | 3.828125 | 4 |
n=raw_input("enter the whole string")
b=raw_input("enter the word you want to search")
l1=n.split()
for i in range(len(l1)):
if l1[i]==b:
print i+1
|
30ba44ef2e9c7715e1f711f48c3e9e8cdc3ba689 | ZacharyRanes/30-Days-Of-Python | /day_11/day11_exercises.py | 662 | 3.796875 | 4 | # Write a function which checks if all the items of the list are of the same data type.
def same_type(list):
last_type = type(list[0])
for i in list:
if type(i) != last_type and type(i) is not None:
return False
last_type = type(i)
return True
print(same_type([3, 4, 5]))
print(... |
63a94d9cd97349533d038354d9398227cab3c8c5 | homo-sapiens94/Bites_of_py | /158/int_list.py | 790 | 3.5 | 4 | from statistics import mean, median
class IntList(list):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@property
def mean(self):
return mean(self)
@property
def median(self):
return median(self)
def _check_int(self, num):
try:
... |
1ccc8629a29844fa51a231bb023f52910229949a | kfisc88-lsc-repos/chapter_8 | /ch8_p3_kfischer.py | 1,998 | 4.03125 | 4 | """
Author: Kelley Fischer
File: ch8_p3_kfischer.py
This is a simple text editor that allows a user to
open, create, edit, and save text documents.
"""
from breezypythongui import EasyFrame
import tkinter.filedialog
class TextEdit(EasyFrame):
def __init__(self):
EasyFrame.__init__(self, title = "Tex... |
0a1f063bb1b724432f477cc449e94d720001c050 | lilaboc/leetcode | /2068.py | 605 | 3.828125 | 4 | # https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/
from collections import Counter
class Solution:
def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
c1, c2 = Counter(word1), Counter(word2)
cs = set(c1.keys()).union(set(c2.keys()))
for i in cs:
... |
784e0806f5e102cc4efaa1ea9af16cd795cf43c3 | yanyanrunninggithub/Leetcode-Python | /heap.py | 3,763 | 3.703125 | 4 | #minheap--->k largest, heapq is min heap
#maxheap--->k smallest
#703. Kth Largest Element in a Stream
#approach1: using heapq
class KthLargest(object):
def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
self.k = k
self.heap = nums
heapq.h... |
655cc9466d07ed8746ecf6143226e52ba116200f | lnrd/testedogit | /dados.py | 788 | 3.59375 | 4 | lista = [1,2,3,4,5,6,7,8,9,10]
dic1 = {"Jack":"Elasticidade", "Fiona": "Fogo", "Finn":"Heroi"}
dic2 = {"Princesa Bubblegun":"Inteligencia", "Marceline": "Voo", "Jack":"Faz bons sanduiches"}
dic1.update(dic2) #atualiza o dicionario
print(dic1)
#Verifica se os dicionarios compartilham copias em comum
def mergeWithou... |
1303f42c28ac2f87d81c27c9574c66b34b07d0a2 | buyi823/learn_python | /learn_python/loop.py | 143 | 3.65625 | 4 | names=['michael','kobe','james']
for name in names:
print(name)
sum = 0
for x in[1,2,3,4,5,6,7,8,9,10]:
sum = sum+x
print(sum)
|
a02aa6df9274c4a8270a8714148b9df5a6aab4f1 | Vovchik22/Python_test | /carloop.py | 576 | 3.765625 | 4 | cars = 100
space_in_a_car = 4
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capasity = cars_driven * space_in_a_car
average_passenger_per_car = passengers / cars_driven
print ("There are", cars, "cars availeble")
print ("There are only", drivers, "drivers availab... |
436005b7fbec19aba89649bfc9ab5ae5adb03dd2 | YaserMarey/algos_catalog | /dynamic_programming/minimum_number_of_modifications.py | 1,777 | 3.671875 | 4 | # Given strings s1 and s2, we need to transform s1 into s2 by deleting and inserting characters.
# Write a function to calculate the count of the minimum number of deletion and insertion operations.
# Solution: We can finding the length of the Longest common subsequence and subtracting that form the the total length
... |
cf29b7f50472f6f5a9229c7f2ac198041f2e1d47 | rafaelmakaha/competition-programming | /codeforces/tep/contest/04contest/a.py | 248 | 3.75 | 4 | f = input()
s = input()
st = input()
ans = ""
for c in st:
i = f.find(c.lower())
if c.isnumeric():
ans = ans + c
elif c.isupper():
ans = ans + s[i].upper()
else:
ans = ans + s[i].lower()
print(ans) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.