blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
cbb2fde8488094dc64bec7d85d9d7190fd40ade8 | Haroldov/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/100-print_tebahpla.py | 128 | 3.6875 | 4 | #!/usr/bin/python3
for i in range(25, -1, -1):
if (i % 2 == 0):
i -= 32
print("{}".format(chr(i + 97)), end="")
|
55226d9380b4ba5cd0443751989462c98b7746ab | amirsaleem1990/python-practice-and-assignments | /area calculator.py | 937 | 4.09375 | 4 | # area calculator
a = True
while a:
print('\n***************************\nWelcome to Area Calculator\n***************************')
b = input('\nwhich shape you want to calulate? \n[sq]:\t for square\n[rec]:\t for rectriangle\n[cir]:\t for circle\n')
if b == 'sq':
d = int(input('\nEnter one side len... |
06c68836ebe35c6d909bbebd97c41887fb8d950e | CraneJen/Python-Learning | /Sort/InsertSort.py | 385 | 3.90625 | 4 | def insertsort(seq):
n = len(seq)
count = 0
for i in range(1, n):
key = seq[i]
j = i - 1
while j >= 0 and key < seq[j]:
seq[j + 1] = seq[j]
j -= 1
count += 1
seq[j + 1] = key
print(count)
return seq
if __name__ == '__main__':
... |
4ffdd4f05f9fb9b7d9b0bd018b7a96cd99a73474 | PatrikoPy/MIW | /wprowadzenie02/cw5.py | 997 | 3.90625 | 4 | __all__ = ['Calculator']
class Calculator:
def add(self, *args):
current = 0
try:
for num in args:
current += float(num)
return current
except:
print("error")
def difference(self, a=0, b=0):
try:
return float(a) -... |
bd7dae154e92bb54eabec1528b9042bda5260241 | vijaykanth1729/python_material | /decorators/generators/gen.py | 264 | 3.921875 | 4 | def my_gen():
n=1
print("This is printed first:")
yield n
n+=1
print("This is printed second")
yield n
n+=1
print("This is printed third: ")
yield n
it = my_gen()
print(next(it))
print(next(it))
print(next(it))
print(next(it))
|
40086ce76a749680f8a203ea6bac439cca0c0fbf | Voolodimer/DevOps3_python | /hw5.py | 855 | 3.796875 | 4 | #!/usr/bin/python3
# 1. После запуска предлагает пользователю ввести неотрицательные целые числа,
# разделенные через пробел и ожидает ввода от пользователя.
# 2. Находит наименьшее положительное число, не входящее в данный пользователем
# список чисел и печатает его.
def hw5():
print('Введите список чисел: ')
... |
20ce0ba6316450e7aee1e4a972f9e37787b4c5f7 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_199/1373.py | 1,241 | 3.5 | 4 | # -*- coding: utf-8 -*-
import sys
import os
import math
#input_text_path = __file__.replace('.py', '.txt')
#fd = os.open(input_text_path, os.O_RDONLY)
#os.dup2(fd, sys.stdin.fileno())
def flip(A, start_i, K):
for i in range(start_i, start_i + K):
if A[i] == '+':
A[i] = '-'
else:
... |
ac0c3b1deb09163b99b68c7d57940fcd93feac29 | Biorrith/Software-Teknologi | /Older versions/Python server/client.py | 1,002 | 3.828125 | 4 | # Import socket module
import socket
# Create a socket object
s = socket.socket()
# Define the port on which you want to connect
port = 25
# connect to the server on local computer
s.connect(('127.0.0.1', port))
# receive data from the server
print (s.recv(102... |
de1aafdb2d37bff0630db9e539bcf80508756640 | raulmercadox/curso_python | /longestRun.py | 1,081 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 25 12:57:23 2019
@author: ezmerra
"""
def longestRun(L):
ancho = len(L)
if ancho == 0 or ancho == 1:
return ancho
anterior = None
contador = 0
maximo_ancho = 0
for i in L:
if anterior == None:
anterior = i
... |
635e7fb013185aa53b44b6e8d16d63b91b97e858 | jogubaba/PythonScripts | /22sed.py | 594 | 3.6875 | 4 | file = open('/home/jogubaba/Downloads/My List', 'r')
f_contents = file.readlines()
sn = open('/home/jogubaba/Downloads/servervmname', 'r')
contents = sn.readlines()
for f_contents in contents:
print(contents)
else:
print("Not in List")
#another
keywords = input("Please Enter keywords path as c:/example/ \n... |
8aa6c344747ebffdde38cdfe610a30d0075cc0d7 | TareqHasa/python_stack | /_python/python_fundamentals/functions_basic_II.py | 825 | 3.8125 | 4 | def count_down (num):
x=list()
for i in range(num,-1,-1):
x.append(i)
return x
print(count_down(5)) # 1
def print_and_return (arr):
print (arr[0])
return arr[1]
print_and_return([1,2])
def first_plus_length(arr):
return arr[0]+len(arr)
print (first_plus_length([1,2,3,4,5]))
def... |
35891cca608d2ad6cd6da859fdc245163c20cfc9 | StraMil/Sorting-Algorithm-Visualization | /visualization.py | 5,267 | 3.65625 | 4 | import pygame
import sys
import random
import time
WIDTH = 1280
HEIGHT = 400
BLACK = pygame.Color(0, 0, 0)
num_bars = 20
bar_witdh = 800/num_bars
space = 400/num_bars
sorting = False
array = []
bars = []
cycles = 0
BLUE = (0, 0, 255)
# Initialize the pygame
pygame.init()
font = pygame.font.SysFont("Arial", 30)
clo... |
ae123cd90ab8496f41452da98a30a0d935870ba9 | jgartsu12/my_python_learning | /python_data_structures/lists/sorted_fn.py | 490 | 4.1875 | 4 | # Guide to the sorted Function in Python
# using sorted() method
#sorted() allows u to store that new value in a new variable that stores that list and keeps original list stored
sale_prices = [
100,
83,
220,
40,
100,
400,
10,
1,
3
]
sorted_list = sorted(sale_prices, reverse=Tru... |
90fc5450b0c74dd0e006aad3dedb900e396a2ee6 | ivo-bass/SoftUni-Solutions | /programming_fundamentals/mid_exam_preparation/3_last_stop.py | 1,424 | 3.71875 | 4 | class Gallery:
def __init__(self, seq):
self.sequence = seq
def change(self, old, new):
if old in self.sequence:
index = self.sequence.index(old)
self.sequence[index] = new
def hide(self, num):
if num in self.sequence:
self.sequence.remove(num)
def switch(self, num1, num2):
if num1 in self.seque... |
b2423910fd63360cbebbbbe88fa157a3567f2c16 | HIT-GH/EPN-CEC-Python | /Lab01-v03-20210625.py | 1,308 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 24 00:04:03 2021
@author: HendersonIturralde
Crear un código en el editor que asigna un valor flotante, lo coloca en
una variable llamada "x", e imprime el valor de la variable llamada "y".
Su tarea es completar el código para evaluar la siguiente expresión:
... |
c632c57f8fe4fcd0502bd65119b6150c88550a74 | ScarletMcLearn/student_data_facebook | /collocation.py | 1,155 | 3.8125 | 4 | import nltk
from nltk.collocations import *
#count single word frequency
f = open('aamir.txt')
raw = f.read()
tokens = nltk.word_tokenize(raw)
#Create your bigrams
#bgs = nltk.bigrams(tokens)
#compute frequency distribution for all the words in the text
fdist = nltk.FreqDist(tokens)
for k,v in fdist.items():
if... |
eb977e6ec1c57016fd533839d883bb50bd624c34 | WeslySantos07/QUEST-ES-OBI | /areadacircuferencia.py | 79 | 4 | 4 | r = float(input())
pi = 3.1416
res = (r**2)*pi
print("{:.2f}".format(res))
|
3a60dfbf0c81af500067303ca10e4306eb7d1556 | LiamTyler/AStarTesting | /src/AStar.py | 3,592 | 3.703125 | 4 | import math
class Cell:
def __init__(self, r = 0, c = 0):
self.f = 0
self.g = 0
self.h = 0
self.row = r
self.col = c
self.parent = None
def __eq__(self, other):
return self.row == other.row and self.col == other.col
def __str__(self):
return... |
547380b3a0fdf94205010cbd5325c091db82e0e6 | Vampirskiy/helloworld | /venv/Scripts/Урок3/step2_input.py | 1,215 | 3.703125 | 4 | import random
number = random.randint(1, 100)
#print(number)
user_number = None
levels = {1 : 10, 2 : 5, 3 : 3}
level = int(input('Введите уровень сложности от 1 до 3'))
count = 0
max_count = levels[level]
user_count = int(input('Введите количество пользователей'))
users = []
for i in range(user_count):
user_name =... |
70a9a1f6d75cbf949fccb3054ba5a912b58fcd33 | juriansluiman/AdventOfCode2019 | /3.py | 1,760 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
### Advent of Code 2019, Day 3
f = open('3.txt', 'r')
c = f.readlines()
wire1 = c[0].rstrip('\n').split(',')
wire2 = c[1].split(',')
def createPath(wire):
path = []
pos = (0,0)
for i in wire:
direction = i[0]
steps = int(i[1:])
if ... |
033f42f6352769d21c80e20d5f9bbd6f7557b146 | SensenLiu123/Lintcode | /223.py | 1,313 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: sensenliu
"""
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: A ListNode.
@return: A boolean.
"""
def isPalind... |
e33dfb6488fbd637355a5308b2ed2c04bb280329 | mattryanharris/CIS7---Discrete-Structures | /Assignments/Due 09-25-2017/Assignment 8 Answers.py | 1,071 | 4.03125 | 4 | import math
def squareChecker(number):
status = False
simplifiedN = math.sqrt(number)
if (number % simplifiedN) == 0 :
return True
else:
return False
def guessGame(number):
test = 0
for x in xrange(1, number + 1):
if squareChecker(x) == True:
test = test + 1
return test
def guessPrompt(number):
... |
a696d12cb940545d3348ed2bd9ac74cc7006776d | sunfinite/siri | /getwords.py | 3,221 | 3.578125 | 4 | #!/usr/bin/python
#Filename:check.py
from BeautifulSoup import BeautifulSoup
import codecs
from strip import gettext
import HTMLParser
import os
import pickle
#Function for cases where the punctuations and the words are not separated by spaces.
def checkpunct(string):
if(len(string)!=0):
j=-1#for punctuation... |
0f1ef240e3e58a530379029e4adfb6ec977bc594 | Luis-Otavio-Araujo/Curso-de-Python | /PhythonExercicios/ex031.py | 269 | 3.828125 | 4 | distancia = float(input('São quantos Km de viagem? :'))
if distancia <= 200:
distancia = distancia * 0.50
print('Você deverá pagar R${:.2f}'.format(distancia))
else:
distancia = distancia * 0.45
print('Você deverá pagar R${:.2f}'.format(distancia)) |
f45f52a39101e0446c0f32f8bc8ea9aac33efd47 | nagkom/MathWithPython | /chapter3_statistics/readingdata/reading_csv_corr_scatter.py | 1,767 | 3.546875 | 4 | # data based on:
# https://www.google.com/trends/correlate/search?e=summer&e=swimming+lessons&t=weekly&p=us
import matplotlib.pyplot as plt
import csv
def read_csv(filename):
with open(filename) as f:
reader =csv.reader(f)
next(reader)
summer = []
highest_correlate... |
dbb1d47756bdd222cb8a056b0125c623bf0a545e | JMosqueraM/algoritmos_y_programacion | /taller_estructuras_de_control_selectivas/ejercicio_6.py | 1,167 | 3.859375 | 4 | # Segun el numero de 4 digitos (entero y positivo) conformado por A, B, C, y D (de la forma ABCD).
# Redondee el numero a la centecima mas cercana
A = int(input("digite el valor A: "))
B = int(input("digite el valor B: "))
C = int(input("digite el valor C: "))
D = int(input("digite el valor D: "))
# Redondear el valo... |
d643ebc986e97e453175ef14130356bc994f2003 | CatharticPotatoz/python-projects | /mudd/functions/testpg3.py | 1,639 | 3.609375 | 4 |
last_in = ""
health = 20
fortitude = 5
intellect = 7
agillity = 7
charisma = 7
armor = 5
##########################################################################################
grassy_noll = ("your surouded by thickets of grass that stretch out as far as you can see in any direction. out in the distance you can... |
4fd9d34c89cbbae4c5ee25fa0d9262644246805e | Sevendeadlys/leetcode | /321/maxNumber.py | 2,322 | 4.1875 | 4 | '''
To create the max number from num1 and nums2 with k elements,
we assume the final result combined by i numbers (denotes as left)
from num1 and j numbers (denotes as right) from nums2, where i+j==k.
Obviously, left and right must be the maximum possible number in num1 and num2 respectively.
i.e. num1 = [6,5,7,1] an... |
a8e70ab881a45bbae1462cd26a0611bb6ceb2a26 | AndyTian-Devops/PythonSample | /FunctionAndParameter.py | 1,290 | 4 | 4 | # Chapter Six: Function and parameter
##def lookup(data,lable,name):
## return data[lable].get(name)
##
##def store(data, full_name):
## names = full_name.split()
## if len(names) == 2: names.insert(1,'')
## labels = 'first', 'middle', 'last'
##for label, name in zip(labels, names):
## people = lookup(da... |
28d96881b4accbce52f985ecb61a59b043cd656a | ebegeti/LeetCode-problems | /question1_7.py | 812 | 3.875 | 4 | #Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.
from chapter1_arrays_strings import AssortedMethods
def setZeros(matrix):
rows=[0 for i in range(0,len(matrix))]
cols=[0 for i in range(0,len(matrix[0]))]
for row in range(0,len(matrix)):
for... |
582b8217362a026537300c472b6d451f6cc586a5 | JiazaiWu/ForPython | /hello/object.py | 1,120 | 3.5625 | 4 | # hello.py
# -*- coding: utf-8 -*-
import types
#stduent is extended from object
class student(object):
def __init__(self, name, score):
#__member can not be seen out of class
self.__name = name
self.score = score
def print_stu_score(self):
print '%s get %s' %(self.__name, self.score)
bart = student('jiaza... |
4c7a3c5a134547e26998ad588eebf6d2470fa6ba | krytech/holbertonschool-higher_level_programming | /0x0A-python-inheritance/10-square.py | 448 | 3.78125 | 4 | #!/usr/bin/python3
"""
A suqare class which inherits properties from the subclass
rectangle and the parent class BaseGeometry
"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
""" New square class that inherits properties from Rectangle """
def __init__(self, size):
""" in... |
fdca639463e3d522bac478521cd633cb3a57dc28 | Kalo7o/VUTP-Python | /exercise_02/08.Positive_negative_zero.py | 177 | 4.21875 | 4 | n = int(input('Enter a number: '))
if n > 0:
print('The number is positive.')
if n < 0:
print('The number is negative.')
if n == 0:
print('The number is zero.')
|
138fffc8f6ac1f065a1799f45bb8bfbeed9b9ade | knightrohit/monthly_challenges | /leetcode_aug_2020/12_pascal_triangle.py | 602 | 3.71875 | 4 | """
Time/Space Complexity = O(K**2)
"""
# Dynamic Programming
# Bottom Up Approach
from functools import lru_cache
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
out = [1]
if rowIndex == 0:
return out
@lru_cache(None)
def search(... |
df3f06459e1043e8cc5510005c20f4dd7cb3f799 | sharondevs/DL | /Image_Denoising/image_denoising.py | 4,134 | 3.625 | 4 | ## Denoising gray scale images using Auto Encoders
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import random
import seaborn as snb
""" The label translation is as follows:
0 - T-Shirt
1 - Trouser
2 - Pullover
3 - Dress
4 - Coat
5 - Sandal
... |
d58851b7f1a1a6c06f1af44c87dbc419171dbb5e | l33tdaima/l33tdaima | /p328m/odd_even_list.py | 1,071 | 3.90625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
from typing import Optional
from local_packages.list import ListNode
class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
... |
64cabb119e5afe63c6be42a59f8a3d547fb9ad4d | Nimisha-V-Arun/Interview-Prep | /Arrays/Python/countLetter.py | 500 | 4.0625 | 4 | def countLetter(string):
count = list()
cnt = 1
for x in range(len(string)):
# if you reach the last char of the string or if the adj char are different
if(x+1 == len(string) or string[x] != string[x+1]):
count.append(string[x])
count.append(str(cnt))
cnt... |
98f7f140cfdba8c10d8e34913afae995568c5a93 | DominikaJastrzebska/Kurs_Python | /05_christmas_tree/zad_calendar.py | 1,038 | 4.21875 | 4 | '''
https://stackoverflow.com/questions/33624221/make-a-yearly-calendar-without-importing-a-calendar
'''
data = [
('January', range(31)),
('February', range(28)),
('March', range(31)),
('April', range(30)),
('May', range(31)),
('June', range(30)),
('July', range(31)),
('August', range(... |
c30b610ab597f90c3a6de88cf42b62eeab13ecb5 | helixstring/introduction-helixstring | /Xiaoyu-excercise-4.py | 292 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 18 17:25:12 2017
@author: xchen
"""
#Calculate all coordinates of the line x=y with x < 100.
#Note: This is the sequence (0, 0), (1, 1), ... (99, 99)
coord={0:0}
for i in range(101):
coord.update ({i:i})
print coord.items()
|
711973b736b80f666eac3a4f09ecba217182a7b6 | pingguosanjiantao/Elements-of-Programming-Interviews | /11-Heaps/11.1-Merge sorted files.py | 1,325 | 3.546875 | 4 | class MinHeap:
def __init__(self):
self.data = []
def add(self, x):
k = len(self.data)
if k == 0:
self.data += [x]
else:
self.data += [float("inf")]
while k > 0:
idx = (k - 1) >> 1
parent = self.data[idx]
... |
f1f311c1fec85e050ac513bb9e3222cd6672ac90 | techknowledgist/techknowledgist | /ontology/maturity/count_terms.py | 1,000 | 3.796875 | 4 | """
Takes a couple of usage files and creates a file with terms that occur 25 times or more.
Usage:
python count_terms.py data/usage-*.txt
Output is written to terms-0025.txt.
"""
import sys, codecs
TERMS = {}
def collect_term_counts(fnames):
for fname in fnames:
print fname,
fh = c... |
5c011ea768ef962d012890b791e71e6840aeffad | dParikesit/TubesDaspro | /login.py | 832 | 3.921875 | 4 | from hash import hash
def login(users):
username = input('Masukan username: ')
password = hash(input('Masukan password: '))
id = -1
role = ''
name = ''
for user in users:
if user[1]==username:
id = user[0]
name = user[2]
if user[4]==password:
role = user[5]
while id == -1:... |
8462a4ff0552a1a366040ad72a6204bac2ccacb6 | mahendraprateik/DataStructures | /problem6_union_intersection.py | 4,447 | 4.15625 | 4 | class Node(object):
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class LinkedList(object):
def __init__(self):
self.head = None
def __str__(self):
if self.head is None:
return
n... |
cae50539c58a816ed7a7249d09474a40b38a5cf4 | bitcs231n/nasty | /数据挖掘/作业1/dissimilarity.py | 1,627 | 3.578125 | 4 | from homework1.pre_processing import data_array
import numpy as np
from math import sqrt
import pickle
def num_similarity(array, a, b):
a1 = list(array[a, [4, 5, 6, 16, 19, 20, 22]])
a2 = list(array[b, [4, 5, 6, 16, 19, 20, 22]])
i = len(a1) - 1
while i >= 0:
if a1[i] == '?' or a2[i... |
8c09b2821d45bf59a78d6d37d882a50d878abed0 | gavrilmihai/python_challenges | /python_challenge4_sol4.py | 164 | 3.796875 | 4 |
import random
num_list = range(1, random.randint(10,500))
odd, even = [x for x in num_list if x%2], [x for x in num_list if not x%2]
print(f'{odd} \n\n {even}')
|
d2721e95ec6243fd486de610460b8ff01d00fd69 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2397/60791/306420.py | 170 | 3.796875 | 4 | n = int(input())
if n == 7 or n == 12:
print(15)
pass
elif n == 17:
print(32)
pass
elif n == 3:
print(17)
pass
else:
print('n')
print(n) |
8357073d255501e80709983f17046fdd5720112a | pi-2021-2-db6/lecture-code | /aula22-24-listas-ii/percursos.py | 782 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Demonstra as diferentes tecnicas classicas para percorrer
(visitar todos os elementos) de uma matriz.
@author: Prof. Diogo SM
"""
import matrizes
def percorre_por_linhas(m: [[]]):
for i in range(len(m)):
for j in range(len(m[i])):
print(f"m[{... |
7b1bcfa1fa069bf14d3c86a1e973b1a07ea70b23 | bigpussy/pythontestarea | /mapandreduce.py | 1,067 | 4 | 4 | # -*- coding: utf-8 -*-
print u"map函数"
def f(x):
return x * x
print map(f , [1, 2, 3, 4, 5, 6, 7, 8, 9])
print map(f , range(10))
print u"reduce函数"
def add(x , y):
return x + y
print reduce(add , [1 , 2 , 3 , 4 , 5, 6])
def fn(x , y):
return x * 10 + y
print reduce(fn , [1, 3, 5, 7, 9])
def char2num(s):
retur... |
fe7fff4cdda7d57431a313f6a2531cec04239ee4 | ARBUCHELI/LIST-COMPREHENSIONS | /list_comprehensions.py | 379 | 4.03125 | 4 | scores = {
"Rick Sanchez": 70, #dictionary
"Morty Smith": 35,
"Summer Smith": 82,
"Jerry Smith": 23,
"Beth Smith": 98
}
#Creation of the list that retrieves the names of the people with score >= 65
passed = [name for name, score in sco... |
e331ab1255f19afffb314b9380485a266bae557f | rodrigocruz13/holbertonschool-machine_learning | /supervised_learning/0x00-binary_classification/9-neural_network.py | 2,996 | 4.03125 | 4 | #!/usr/bin/env python3
"""
Class NeuralNetwork
"""
import numpy as np
class NeuralNetwork:
""" Class """
def __init__(self, nx, nodes):
"""
Initialize NeuralNetwork
Args:
- nx: is the number of input features to the neuron
- Nodes: is the number of nodes found... |
db65068c3bc649aad7b5f9a12a1ba856f4c82482 | Daviderose/Whiteboard-excercises | /Fibonacci/Fibonacci.py | 289 | 3.84375 | 4 |
def fib(n):
if n == 1 or n == 2:
return 1
fib_array = [None] * (n + 1)
fib_array[1] = 1
fib_array[2] = 1
for i in range(3,n + 1):
fib_array[i] = fib_array[i - 1] + fib_array[i - 2]
return fib_array[n]
if __name__ == '__main__':
print(fib(100)) |
c5346058b3ec8ce30caa7b8eec1a63be34fafc00 | gabriellaec/desoft-analise-exercicios | /backup/user_294/ch16_2020_04_12_21_31_06_341008.py | 136 | 3.703125 | 4 | programa = float(input('qual o valor da sua conta ? '))
final = programa*1.1
print ('Valor da conta com 10%: R$ {0:.2f}' .format(final)) |
1a90cc52744885e50a5ee9481f2fc1471e62b7d3 | vikasnarwaria/CtCI_PYTHON_SOLUTIONS | /SORTING_AND_SEARCHING/basics.py | 10,560 | 4.5625 | 5 | from random import randint
'''
This script illustrates the implementation of the following sorting algorithms.
1. merge_sort.
2. Quick_sort.
3. Heap_sort.
4. Bubble/Insertion sort.
5. Selection sort.
'''
def merge_sort(arr):
'''
Merge Sort is a very basic and efficient Sorting algorithm... |
a982243fa67db7b92d6f233ec019f37ceb7383e6 | opussf/Masyu | /test/TestSolveMasyu.py | 21,301 | 3.515625 | 4 | import unittest
from MasyuBoard import *
from SolveMasyu import *
class TestSolveMasyu( unittest.TestCase ):
Masyu = SolveMasyu( MasyuBoard.MasyuBoard(), True )
def setUp( self ):
""" setUp """
self.Masyu.board.loadFromFile( "puzzles/puzzle_0.txt" )
def test_Masyu_hasBoard( self ):
self.assertTrue( self.Masyu... |
4a9a487bbf4fb4bf2f8501dc9dd19dd5a9c9aa00 | sealire/algorithm-py | /sort/shell_sort.py | 905 | 3.796875 | 4 | # -*-coding:utf-8 -*-
def shellSort(input_list):
'''
函数说明:希尔排序(升序)
Parameters:
input_list - 待排序列表
Returns:
sorted_list - 升序排序好的列表
'''
length = len(input_list)
if length <= 1:
return input_list
sorted_list = input_list
gap = length // 2
while ... |
7e7aca4f2c7fa28fa2e1522c7d89e94915d44b0d | noelz8/trabajos-intro | /clase 8 alv.py | 2,442 | 3.8125 | 4 | #lista verificacion positivo
def listap(lista):
if isinstance (lista, list) and lista != []:
return listap_aux(lista)
else: return "Error"
def listap_aux(lista):
if lista ==[]:
return True
elif (lista[0] < 0):
return False
else: return listap_aux(lista[1:])
#####... |
e61abe676bc8d0c2d2271c959b2e09e348d29318 | Vampiro20111/prueba2 | /listas.py | 3,999 | 4.28125 | 4 | #LISTAS: conjunto de elementos preferiblemente del mismo
#tipo. Los elementos se encuentran ordenados por indice.
#es una estructura de datos.
#sintaxis
#se define el identificador, seguido del operador de
#asignacion =, y entre corchetes [] se ponen los elementos
#separados por ,
#arreglo que contiene numeros
numeros... |
693b5293405e04d0c0f567e5c355b335d6270e90 | mfranklin128/interview-prep | /linked_lists/node.py | 537 | 3.875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
def append(head, data):
if not head:
return Node(data)
curr = head
while curr.next:
curr = curr.next
new_node = Node(data)
curr.next = new_node
return head
def make_test_list(l):
... |
ca23c39962c81dc6020fb57e4d4f70c54bf33ed1 | balassit/improved-potato | /microsoft/Largest-Integer.py | 333 | 4.1875 | 4 | def largestInt(arr):
"""
Time Complexity - O(n)
Space Complexity - O(n)
"""
found = set()
res = 0
for num in arr:
# if found opposite
if -1 * num in found:
res = max(abs(num), res)
else:
found.add(num)
return res
print(largestInt([3, 2, ... |
5a84db125f0597b6769b03199bbe72b1bc09a5c5 | luojianbiao/Python-100 | /Days/Day04/Circulate.py | 986 | 3.515625 | 4 | #!/usr/bin/python
#coding:utf-8#
"""
@author: Luo-Jianbiao
@contact: 1037487025@qq.com
@software: PyCharm
@file: Circulate.py
@time: 2020/5/25 15:18
"""
# 求1-100之间的偶数和
sum = 0
# 如果for循环中没有这样的{}块,我们如何知道for循环中的哪个代码块--那就是靠缩进来判别
for x in range(2,101,2):
sum += x
print(sum)
index = 0
for x in range(1,101,1):
if x % ... |
218e5f7a4e3f2bf5fccc4b7ed60480ef633e01b7 | ravi4all/PythonReg2_30_2020 | /AdvPythonReg/01-OOPS/Descriptors.py | 535 | 3.71875 | 4 | # class Emp:
#
# def __init__(self):
# self.__name = ""
#
# def __get__(self, instance, owner):
# name = self.__name
# print("Name is",name)
# return name
#
# def __set__(self, instance, value):
# self.__name = value
# print("Setter called for",sel... |
aac4843151cc3376977bcac4f3501d76eb29104a | ignaciomgy/python | /Tests/test.py | 1,330 | 3.90625 | 4 | # \n Salto de linea
# \t TAb
# Con strings myString[inicio:fin:paso].
myString = "hola como estas, que tal estuvo el asado"
#print(myString[::-1])
#en valores negativos el indice lo toma desde el final hacia el inicio
#print("tinker"[1:4])
#result = 100 / 88
#print("El resultado es {r:1.3f}".format(r=result))
#otra fo... |
6edd8da05ba792262433ecf6a57941f787c64514 | UCSB-dataScience-ProjectGroup/movie_rating_prediction | /src/dataCall_example.py | 211 | 3.5625 | 4 | import json
from dataCall import dataCall as DC
movie = "0"
while movie != "":
print(" ")
movie = input("Enter a movie name! \n")
print(" ")
if movie != "":
print(DC.findMovie(movie))
|
c670b1bd1ba089fa44383028f80f23b133b2e749 | kajott/adventofcode | /2020/18/aoc2020_18_part2_nogolf.py | 1,943 | 3.671875 | 4 | #!/usr/bin/env python3
import re
V = 0
def my_eval(expr):
tokens = re.findall(r'\d+|[+*()]', expr)
if V >= 2:
print("expr:", repr(expr))
print("tokens:", ' '.join(tokens))
# phase 1: use Shunting Yard Algorithm to convert infix into RPN
ops = []
rpn = []
for token in tokens:
... |
e4086b5ea10abba405eb65e8ecd312f7fab30746 | cocka/py4e | /2_python_data_structures/3week/7.2.alt.py | 752 | 3.765625 | 4 | filename = input("Enter the file name: ")
count = 0
dspam = 0
sumdspam = 0
try:
if filename == 'na na boo boo':
print("NA NA BOO BOO TO YOU - You have been punk'd!")
else:
file = open(filename)
except:
print("File cannot be opened:", filename)
for line in file:
if line.startswith('X-DS... |
dfc0437afbe93a5649b2ba1ae2bf9da7ba49f80d | infinite-Joy/programming-languages | /python-projects/algo_and_ds/best_time_to_buy_and_sell_stocks_kadanes_leetcode121.py | 1,386 | 3.765625 | 4 | """
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
another way of doing this is using the kadanes algo... |
f84b2afc6c35b0a0bf3a5a8568e686db7475bc80 | tanvirraihan142/CtCi-in-python | /Chap 1/1.2.2 Check Permutation.py | 379 | 3.59375 | 4 | def permutation(str1, str2):
if len(str1) != len(str2):
return False
letters = [0 for i in range(128)]
str1_array = list(str1)
for i in str1_array:
letters[ord(i)] += 1
for i in range(len(str2)):
c = str2[i]
letters[ord(c)] -= 1
for i in letters:
if i!... |
4000b94cb2f8ace418792e7de40789092aa9cb72 | devs-nest/python-primer | /Day4/dictionaries.py | 516 | 4.0625 | 4 | my_dict = {"A": "Apple",
"B": "Boy",
"E": "No, not an elephant.",
"C": "Cat",
"D": "Devsnest!!"}
# my_dict["F"] = "Fox"
# my_dict["C"] = "Cow"
# print(my_dict)
# del my_dict["C"]
# my_dict.clear()
# print(my_dict)
# print(my_dict["G"])
# print(my_dict.get("G"))
# print(my_dict)
w... |
b3cfe1ba6b28715f0f2bccff2599412d406fd342 | n001ce/python-control-flow-lab | /exercise-5.py | 670 | 4.40625 | 4 | # exercise-05 Fibonacci sequence for first 50 terms
# Write the code that:
# 1. Calculates and prints the first 50 terms of the fibonacci sequence.
# 2. Print each term and number as follows:
# term: 0 / number: 0
# term: 1 / number: 1
# term: 2 / number: 1
# term: 3 / number: 2
# term: 4 / nu... |
5cfa9a263c7c9ddd18c8ff561be9e9b07801aada | advinstai/python | /solucoes/Duan-Python/Lista1-Python/problem12.py | 180 | 3.828125 | 4 | def count_digits(num):
if(type(num)!=type(1)):
print("Seu input nao eh inteiro")
else:
i=0
while num>=1:
num = num/10
i+=1
return print(i)
count_digits(123456789)
|
7e1d87b492ac42b4d383309e87a644758224f3d2 | lauren-lopez/learning_python | /translate_mRNA.py | 5,330 | 3.515625 | 4 | #!/usr/bin/env python3
import gzip
import sys
import biotools as bt
import argparse
# Use argparse
# Write a program that translates an mRNA
# Assume the protein encoded is the longest ORF
def longest_orf(seq):
# find all ATGs (start codon)
assert len(seq) > 0
atgs = []
for i in range(len(seq) -2):
... |
9358046f93085f1ade11be0be05d4d0f484d5e05 | jackpan123/Python-Crash-Course-exercise | /chapter06/practice/survey.py | 372 | 3.953125 | 4 | favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
survey = ['jen', 'sarah', 'edward', 'phil', 'jack', 'pan']
for name in survey:
if name in favorite_languages.keys():
print(name.title() + ", thank you for survey!")
else:
print(name.... |
c854c78004956b54de558c2b18575e315a51d827 | dbwebb-se/python-slides | /oopython/example_code/vt23/kmom06/sort/bubble_sort3.py | 405 | 4.1875 | 4 | #!/usr/bin/python3
"""
Sorting algorithm Bubble sort
"""
def bubble_sort(seq):
"""
Sorts a list with integer values with the bubble sort algorithm. O(n*n)
"""
for _ in range(len(seq)):
for j in range(len(seq) - 1):
if seq[j] > seq[j+1]:
(seq[j], seq[j+1]) = (seq[j+1],... |
003c936cadc313650befc2c69d4dc1b65f072fb0 | diorge-zz/usage-of-set-expansion-for-structured-data | /artificialdatasets.py | 3,917 | 3.796875 | 4 | import os
import numpy as np
import pandas as pd
from sklearn.preprocessing import Binarizer
def bernoulli_generation(instances, dimensions, n_classes=2,
density=0.05, density_sd=0.02, target=None):
"""Creates a binary DataFrame using independent Bernoulli distribution.
Each class use... |
ee759aa710eeba647a8a87b1efea71b699737ccf | Styfjion/code | /24.两两交换链表中的节点.py | 1,189 | 3.75 | 4 | #
# @lc app=leetcode.cn id=24 lang=python3
#
# [24] 两两交换链表中的节点
#
# https://leetcode-cn.com/problems/swap-nodes-in-pairs/description/
#
# algorithms
# Medium (61.08%)
# Likes: 301
# Dislikes: 0
# Total Accepted: 44.8K
# Total Submissions: 71.6K
# Testcase Example: '[1,2,3,4]'
#
# 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
#
... |
9396619942f4bf94c9dace6468bf9c2bf50a602e | ChrisKenyon/Practice | /fill_graph.py | 1,467 | 3.703125 | 4 | heights = [2,0,1,0,3,2,1,0,2,3]
#heights = [0,1,0,2,1,0,1,3,2,1,2,1]
#heights = [3,0,0,2,0,0,1,0]
'''
start = 0
start_idx = 0
potential = 0
total_fill = 0
occupied = 0
highest_close = 0
highest_close_idx = 0
i = 0
import pdb
while i < len(heights):
curr = heights[i]
pdb.set_trace()
if curr > start:
... |
aed79bdf1d8c99af6c1d0098c632b56d65a6f96d | uditiarora/CG-Lab | /lab6/n3.py | 2,598 | 3.84375 | 4 | #perspective projection
from graphics import *
import math
def translate():
for i in range(n):
vertex1[i][0]=vertex1[i][0]+tx
vertex1[i][1]=vertex1[i][1]+ty
vertex1[i][2]=vertex1[i][2]+tz
vertex2[i][0]=vertex2[i][0]+tx
vertex2[i][1]=vertex2[i][1]+ty
vertex2[i][2]=vertex2[i][2]+tz
def line(x0,y0,z0,x1,y1,... |
66070cb5b210c9b4bc4ec4958db6b17339843581 | vnbl/Sorter_UWC | /sorter_UWC.py | 1,771 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
import random
lst_1 = [number for number in range(1,91)]
lst_3 = [number for number in range(1,91)]
lst_2 = [number for number in range(1,91)]
rev_lst = np.zeros([9,30],dtype=int)
random.shuffle(lst_1)
random.shuffle(l... |
687e1e26b4da1a331e72c980b09a4a064b81d25f | ashish8796/Codewars | /python-kata/squares_sequence.py | 454 | 4.21875 | 4 | '''
Complete the function that returns an array of length n, starting with the given number
x and the squares of the previous number. If n is negative or zero, return an empty array/list.
'''
x , n = 2, 5
def squares(x, n):
res = []
if n<=0:
return []
else:
for i in range(n):
... |
a3abc7c72e2f895adc25fb3164fe0c63d7b1ba41 | James4Deutschland/Vault7Data | /Logger.py | 737 | 3.6875 | 4 | from datetime import datetime
import time
###
# Kyle Beck, 2017-02-12
# This is a logger module that provides an interface for writing strings to a
# log queue that will be dumped to a file if the program ends execution.
###
log = []
outputDir = 'output/'
# Appends a message to the log. Automatically includes times... |
2f04d981ded532d2792750a82183f9f1154394c3 | rafaelperazzo/programacao-web | /moodledata/vpl_data/189/usersdata/264/65174/submittedfiles/al2.py | 196 | 4.125 | 4 | # -*- coding: utf-8 -*-
#ENTRADA: NÚMERO QUALQUER:x
x= float(input('digite um número real x:')
#PROCESSAMENTO: u:PARTE INTEIRA, j: PARTE FRACIONÁRIA
u= (X/1)
j= (x%1)
#Saída:
print(u)
print(j) |
295154400b1e8ef8a830aab5d94ac622e5a34665 | sonmaz/gesture-recognition | /sortIncreasing.py | 511 | 3.78125 | 4 | def findSmallest(arr):
list=[]
min = -1
index= -1
for i in range(8):
min = -1
index= -1
for num in range(len(arr)):
if(num not in list):
if(min < 0):
min = arr[num]
index = num
else:
if min > arr[num]:
min = arr[num]
index = num
list.append(index)
retu... |
b7f9bf9426b4a3a2ef7223ccf1ee96d60e854c26 | nathanramnath21/project-106 | /project106/cups-of-coffee-and-less-sleep.py | 208 | 3.53125 | 4 | import plotly.express as px
import csv
with open('cups of coffee vs hours of sleep.csv', newline='') as f:
df=csv.DictReader(f)
fig=px.scatter(df, x="sleep in hours", y="Coffee in ml")
fig.show() |
457f47e234ecddc651f27adc051777010279fb25 | josecaro02/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/1-last_digit.py | 456 | 3.875 | 4 | #!/usr/bin/python3
import random
number = random.randint(-10000, 10000)
p_number = -((number * -1) % 10) if number < 0 else number % 10
if p_number == 0:
print("Last digit of {:d} is {:d} and is 0".format(number, p_number))
elif p_number < 6:
print("Last digit of {:d} is {:d} and is less than 6 and not 0"
... |
91959deddeeadc330b2d2e910db6196792d35dd9 | choigabin/PythonProgramming | /IX.Project/TICTACTOE_play.py | 3,356 | 3.59375 | 4 | import tkinter
from tkinter import messagebox
from TICTACTOE import TictactoeGameEngine
class Tictactoe:
def __init__(self):
self.game_engine = TictactoeGameEngine()
def play(self):
#show board
print(self.game_engine)
while True:
#무한반복
#row, col 입력받자
... |
0754788645c086f4440803685433196ea9ee22f7 | jtraver/dev | /python3/sudoku/simple1.py | 4,182 | 3.625 | 4 | #!/usr/bin/env python3
#!/usr/bin/python
r0 = [ 5, 0, 9, 8, 1, 2, 7, 0, 0 ]
r1 = [ 0, 0, 0, 9, 0, 6, 2, 5, 1 ]
r2 = [ 0, 0, 2, 0, 3, 0, 0, 6, 0 ]
r3 = [ 0, 0, 0, 0, 0, 5, 0, 7, 0 ]
r4 = [ 8, 7, 6, 0, 2, 0, 5, 4, 9 ]
r5 = [ 0, 4, 0, 7, 0, 0, 0, 0, 0 ]
r6 = [ 0, 5, 0, 0, 9, 0, 8, 0, 0 ]
r7 = [ 7, 9, 8, ... |
1ec42fccb532e1e8ac52dd0eead4eff69e3d037c | aplcido/Machine-Learning | /Machine-Learning/testing_numpy_speed.py | 1,218 | 3.75 | 4 | """Testing NumPy speed."""
import numpy as np
from time import time
def how_long(func, *args):
"""Execute functions with given arguments, and measure time execution"""
t0 = time()
result = func(*args) #all arguments are passed in as -is
t1 = time()
return result, t1-t0
def manual_mean(arr):
... |
0480356cb0265460e433ada645e41a6b8bd31535 | fabiangothman/Python | /fundamentals/2_datatype.py | 1,003 | 3.5625 | 4 | #Datatypes
print(type("Hello world")) #str
print(type(100)) #int
print(type(100.5)) #float
print(type(False)) #bool
print(type([1, 2, 3])) #list
print(type(["Hello", "Bye", "Again"])) #list
print(type([10, "Hello", True, 11.... |
212a11aa354cafc7c542d4f5aab9665de315d803 | msw1535540/MachineLearning | /MachineLearning/Leetcode/020.valid-parentheses/Valid_Parentheses.py | 957 | 3.75 | 4 | #-*- coding:utf-8 _*-
"""
@author:charlesXu
@file: Valid_Parentheses.py
@desc:
@time: 2018/02/04
"""
'''
思路:
栈最典型的应用就是验证配对情况,作为有效的括号,有一个右括号就必定有一个左括号在前面,
所以我们可以将左括号都push进栈中,遇到右括号的时候再pop来消掉。
这里不用担心连续不同种类左括号的问题,因为有效的括号对最终还是会有紧邻的括号对。如栈中是({[,来一个]变成({,再来一个},变成(。
'''
'''
了解堆栈的性质
'''
class Solution(objec... |
c5414e4f1d1a7162c5ad876dfe9542d603aef8be | tylerphillips55/pyp-w1-gw-language-detector | /language_detector/main.py | 1,848 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""This is the entry point of the program."""
from .languages import LANGUAGES
import string
import re
def detect_language(text, languages):
text = re.compile('[%s]' % re.escape(string.punctuation)).sub('',text) #remove punctuation in string
text = text.lower()
ls = text.spli... |
60fdaa9752810c79c493d9835a6948ab2501f1d9 | RuchiraPatil/Python-3.x | /reverse.py | 84 | 3.609375 | 4 | s = input('Text : ')
for i in range(len(s)-1, -1, -1):
print(s[i], end="")
|
192f81f687b2f02046436fc88cfc24247dcd0ec2 | minhnguyen2610/C4T-BO4 | /Session6/input_number.py | 186 | 3.90625 | 4 | while True:
n = input("Nhap so vao day: ")
print(n)
if n.isdigit():
print("This shitz is el numero")
break
else:
print("This shitz ain't numero")
|
4e0a77eab4b83e2a4854e68fc14fa123bd990ddd | lpuls/CodeExercise | /leetcode/107.二叉树的层次遍历-ii.py | 1,218 | 3.59375 | 4 | #
# @lc app=leetcode.cn id=107 lang=python3
#
# [107] 二叉树的层次遍历 II
#
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
def levelO... |
f5f71dfb5334932c9424a1fccb1376cb4a442a44 | YutoTakaki0626/My-Python-REVIEW | /basic/is.py | 370 | 3.96875 | 4 | # is演算子:同じオブジェクトかどうかを判定する
a = 1
b = 1
c = 3
d = a
e = 2 - 1
print(id(1))
print(id(a))
print(id(b))
print(a is b)
print(a is not c)
hello = 'hello'
hello2 = 'h' + 'e' + 'l' + 'l' + 'o'
print(hello is hello2)
hello = 'konnichiwa'
print(hello is hello2)
# Noneかどうかの判定によく使う
nothing = None
print(id(nothing)) |
e59a1f49d2cfb1afc7176509c2e2182e0b75aae8 | ljmerza/algorithms | /python-algorithms/insertion.py | 952 | 4.5 | 4 | # insertion sort
def insertion(arr):
'''
for each item in an array, you look at the current item then the item behind it
if the current item is smaller than the one behind it then switch. go to previous item.
you are taking the current item and pushing it back each time the item before it is smaller
until this is... |
5ddd9f7cca5a5890a4c64b8b6b2aa87635353f94 | callmekeyz/Digital-Crafts-Classes | /Programming101/user-input.py | 197 | 4.03125 | 4 | #print('hi')
name = input("Name Please:")
subject = input ("Favorite subject\n")
age = input("How old are you?\n")
if age >= 21:
print("Grab a Beer?")
print (f "You said your name is {name}") |
e7498cc2d4bb05ed99f49618b0a40ba266cf935a | C-SON-TC1028-001-2113/parcial-practico-2-marianadiazl | /assignments/17NCuadradoMayor/src/exercise.py | 211 | 4 | 4 |
def main():
numero = int(input("Escribe un numero : "))
#escribe tu código abajo de esta línea
r = 1
while numero<=r**2:
r = r + 1
print(r)
if __name__=='__main__':
main()
|
1286812346feeb6a75e2ff7ecd5f265c851690af | tomduhourq/p4e-coursera | /src/DictPractice/examples.py | 807 | 3.578125 | 4 | __author__ = 'tomasduhourq'
import string
from src.FilePractice.file_helper import choose_file
# Sorting the keys of a dict
counts = {'chuck': 1, 'annie': 42, 'jan': 100}
# Create a list of the keys in the dict
def sort_keys(d):
keys = d.keys()
keys.sort()
for key in keys:
print key, d[key]
sort... |
6b588787e8b3404ba2f9e17c5f52710fa930b1f8 | GalyaBorislavova/SoftUni_Python_Advanced_May_2021 | /Exams/Python Advanced Exam - 27 June 2020/01. Bombs.py | 1,601 | 3.609375 | 4 | from collections import deque
def print_data(created_bombs, bomb_effects, bomb_casings):
if bomb_effects:
print(f"Bomb Effects: {', '.join([str(el) for el in bomb_effects])}")
else:
print(f"Bomb Effects: empty")
if bomb_casings:
print(f"Bomb Casings: {', '.join([str(el) for el in b... |
22d7f83f4ddf6c201090294d7cbbc54bd1392be7 | jchenpanyu/Python_test | /Python Machine Learning/[Ch6_P170-172]Pipelines.py | 3,079 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 06 13:43:40 2017
"Python Machine Learning"
Chapter 6
Page: 170-172
working with the Breast Cancer Wisconsin dataset, which contains 569 samples of malignant and benign tumor cells.
The first two columns in the dataset store the unique ID numbers of the samples and the cor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.