blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b1fee8de3dec372f733a215dadefcb2aee4f4aae | Akshive/Exercism-Python-Solutions | /saddle-points/saddle_points.py | 746 | 3.671875 | 4 | def is_smallest(matrix, x, y):
m = len(matrix)
for i in range(m):
if(matrix[i][y] < matrix[x][y]): return False
return True
def is_largest(matrix, x, y):
n = len(matrix[0])
for j in range(n):
if(matrix[x][j] > matrix[x][y]): return False
return True
def saddle_points(matrix):
... |
2e45d6347bac0c1c8dbd15aec76563a06afcd790 | andresalbertoramos/Master-en-Programacion-con-Python_ed2 | /gonzalo/CLASES 1 a 11/clase3/for3.py | 276 | 3.671875 | 4 |
lista_compra = ['raton', 'teclado', 'monitor', 'ist operati', 'windows']
for item in lista_compra:
print(item)
######
numeros = [2, 8, 7, 5, 0, 9, 22, 99]
numeros_duplicados = list()
for num in numeros:
numeros_duplicados.append(num*2)
print(numeros_duplicados)
|
4c4d433057c998587c6321895a70a8d8b8b2ade8 | malluri/python | /30.py | 503 | 3.71875 | 4 | """
30. Take actuual string, soucrce string, destination string. replce first nth occurances of soucestring with destination string of actual string
"""
str=raw_input("string")
source=raw_input("sourcestring")
dest=raw_input("destination")
n=input("occurence")
count=0
s=" "
l=len(str)-len(source)+1
for i in range(0,l)... |
5da1d588cd0f1c982c77d3baeba6a84dedf829d2 | marekkulesza/Daily-Questions | /Daily question7.py | 899 | 4.09375 | 4 | #The input format:
# Two lines: first the spin of the particle,
# then its charge. You do NOT have to convert
# these values to floats.
# The output format:
# The particle and its class separated by a space.
input1 = input()
input2 = input()
if input1 == "1/2" and input2 == "-1/3":
print("Strange Q... |
b2b0afd2dcb0f55b74247dfefe792ce51df3e59e | HowardLei/Python | /11lambda表达式.py | 1,464 | 4 | 4 | """
lambda 函数:匿名函数。这个函数可以省去定义函数名的时间
如何创建:lambda 参数: 返回值
"""
from typing import re
t = lambda x, y: 2 * x + y
# print(t(2, 3))
# 有关 lambda 函数的补充 BIF
# 1、filter(函数或 None, 迭代器) 函数:过滤器函数。前面的函数表示过滤规则返回一个过滤器对象。
# 如果满足这个过滤规则,则保留下来,如果不满足,则将其筛选出来。
p = filter(lambda x: x % 2, range(100))
for e in list(p):
print(e)
# 2、映射函... |
f421478509a07ea1c65dea66a58672049f049694 | matt-zx315/Curso-Python | /Topico_11/Exercicios06.py | 36,700 | 3.890625 | 4 | import binascii
import colored
import os
from random import randint
"""
Exercício 1: Criar um programa que:
item a: permita criar e abrir um arquivo:
item b: permita a gravação de caracteres nesse arquivo, encerrando a gravação ao digitar '0'.
item c: fechar o arquivo
Em seguida, ler o arquivo caractere por caractere.
... |
d6eedfa5f148130fd96f2864b4220b389019ba61 | JustinNix/prac5 | /hex_colours.py | 637 | 3.953125 | 4 | COLOURS_HEXADECIMAL = {"aliceblue": "#f0f8ff", "antiquewhite": "#faebd7", "antiquewhite1": "#ffefdb",
"antiquewhite2": "#eedfcc", "antiquewhite3": "#cdc0b0", "antiquewhite4": "#8b8378"}
width = len(max(COLOURS_HEXADECIMAL.keys()))
for colour, hexadecimal in COLOURS_HEXADECIMAL.items():
print(... |
2d316930eddda7e093d5d5c4724430b423a147b1 | MurradA/pythontraining | /Challenges/P066.py | 242 | 3.953125 | 4 | import turtle
import random
colours = ["blue", "black", "yellow", "red", "green", "purple"]
turtle.pensize(3)
for i in range(0, 8):
turtle.color(random.choice(colours))
turtle.forward(50)
turtle.right(45)
turtle.exitonclick()
|
271df530ba4f32d21ef25b3cd6c7cdf81a537966 | calebPowell-oak/pythonForZipCode | /CrapsGame.py | 1,427 | 3.96875 | 4 |
import random
def main():
response = raw_input("Do you want to play craps (y/n)?")
if response == 'y':
instructions = raw_input("Do you need instructions (y/n)")
if instructions == 'y':
print("Instruction!")
while response == 'y':
pause = raw_input("press <Enter> to... |
57208c4edb0cf1acaddd19120c720189cfa97d73 | alx-mag/EulerProject | /problem6.py | 365 | 3.890625 | 4 | def sum_of_squares(count):
_sum = 0
for x in range(1, count + 1):
_sum += pow(x, 2)
return _sum
def square_of_sum(count):
_sum = 0
for x in range(1, count + 1):
_sum += x
return pow(_sum, 2)
if __name__ == '__main__':
count = 100
print("The difference: " + str(abs(sum... |
1038452b506542597e72ef96079388bb6721d9d2 | poffe312/leguajes-y-automatas2 | /operaciones.py | 2,159 | 3.515625 | 4 | #nombre : poeraciones.py
#objetivo: muestra como trabajar los metodos p funciones
#autor:
#fecha:
#-----------------------------------
#funcion para sumar dos enteros
#-----------------------------------
def suma(num1,num2):
return num1+num2
#-----------------------------------
#funcion para restar dos enteros
#---... |
8f05f746ded6bc66c49fdfb0b78913c082c34290 | FYawson/AlarmClockTest | /Cmd_AlarmClock.py | 609 | 3.734375 | 4 | import datetime
import winsound
filename = "old-fashioned-door-bell.wav"
alarmHour = int(input("What hour do you want the alarm to ring? "))
alarmMinute = int(input("What minute do you want the alarm to ring? "))
amPm = str(input("am or pm? "))
print("waiting for alarm at: ", alarmHour, alarmMinut... |
bd523820b31b3aef20c3cacf25c2a680c5a00c38 | nizamra/Python-Stack | /python fundementals/functions basic 2.py | 682 | 3.71875 | 4 | 1>>
def countDown(num):
li=[]
for i in range(num,0,-1):
li.append(i)
print(li)
countDown(5)
2>>
def PrintReturn(li):
if len(li) is 2:
print("first value :", li[0])
return li[1]
PrintReturn([2,4])
3>>
def firstPlusLength(li):
print(li[0]+len(li))
firstPlusLength([1,4,6,3])
... |
e63c39e31e3c572a305d971cf136dc49c8c6af69 | micahtyong/Leetcode | /linkedlist/206-reverse-ll.py | 525 | 3.578125 | 4 | # Idea: Sentinel node and new list.
# Edit: No need for sentinel
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseList(self, head):
"""
:type head: ListN... |
5302a839cec09afabe0442d33cc86ebf4776f746 | bre-nda/Password-Locker | /run.py | 4,100 | 4.25 | 4 | #!/usr/bin/env python3.6
from credentials import Credentials
from user import User
def create_credentials(uname,password,email):
'''
Function to create a new credential
'''
new_credentials = Credentials(uname,password,email)
return new_credentials
def create_user(fname,uname,email):
'''
Fu... |
93ea77990b2cde3a1a1a48914af416b830065af8 | takin6/algorithm-practice | /at_coder/biginner/2_1/2_1_4/yukicoder_133.py | 677 | 3.53125 | 4 | # import itertools
# from math import factorial
# N = int(input())
# A = list(map(int, input().split()))
# B = list(map(int, input().split()))
# total = N*N
# chance = 0
# for p in itertools.permutations(A):
# for q in itertools.permutations(B):
# if sum([ p[i] > q[i] for i in range(N) ]) > N//2:
... |
cff6d213b9745f05e3bd6bc4cf2061043e1fc976 | encalien/programming_problems | /Elementary/1_07_multiplication_table.py | 194 | 4.3125 | 4 | # Write a program that prints a multiplication table for numbers up to 12.
for i in range(1, 13):
row = "{:2}".format(i)
for j in range(2, 13):
row += "{:4}".format(i * j)
print(row)
|
f56838d768aeaf7815e7f1abc6af9fc8446b8eb2 | waltman/advent-of-code-2017 | /day22/sporifica_virus2.py | 1,765 | 3.546875 | 4 | #!/usr/bin/env python3
from sys import argv
def emptyg(size):
return [ [ '.' for y in range(size) ] for x in range(size) ]
def printg(g):
for row in range(len(g)):
for col in range(len(g)):
print('{} '.format(g[row][col]), end='')
print('')
print('')
def turn_right(d):
if ... |
7c4e9ec2ec7b93dd8a8c4e8a46d6ac0574ecaf85 | georgiann3554/Python | /scramble.py | 1,156 | 3.53125 | 4 | import random
fhand=open("input.txt")
fin=fhand.read()
fhand2=open("output.txt",'w')
words=fin.split()
listt=[]
punc=[",",".","?","!",";"]
def scramble(i):
newword=""
newword2=""
listt2=[]
if i[len(i)-1] in punc:
count=(len(i)-3)
while(count is not 0):
... |
1c6e45c7daaa9e6598f165f1cb5e173864b67ce4 | rames4498/Bootcamps_and_workshops | /sqlite_db/db2.py | 582 | 3.625 | 4 | import sqlite3
conn = sqlite3.connect('my_data.sqlite')
cursor = conn.cursor()
cursor.execute("INSERT INTO SCHOOL (ID,NAME,AGE,ADDRESS,MARKS) \
VALUES (1, 'Rohan', 14, 'Delhi', 200)");
cursor.execute("INSERT INTO SCHOOL (ID,NAME,AGE,ADDRESS,MARKS) \
VALUES (2, 'Allen', 14, 'Bangalore', 150 )");
curso... |
19dcfccb4f7af6719ecc832002c83de4598b8cc4 | akyyev/My_python | /day11_regex/__init__.py | 780 | 4.03125 | 4 | # search and replace
import re
st = 'My name is David, Hi David'
pattern = r'David'
new_st = re.sub(pattern, 'Amy', st)
print(new_st)
st2 = r'I am \r\a\w' # r makes the string as raw string
print(st2)
# Metacharacters
# '.' -- any character
# '^' -- start
# '$' -- end
# '[]' -- any one match from specific ch... |
e6c53ebeae4c9817e96ac7bb914a4b81e1194e18 | shehryarbajwa/Algorithms--Datastructures | /algoexpert/1-strings/palidnrome_substring.py | 641 | 3.5625 | 4 | def longestPalindromicSubstring(string):
currentLongest = [0,1]
for i in range(1, len(string)):
odd = getPalindromeFrom(string, i - 1, i + 1)
even = getPalindromeFrom(string, i - 1, i)
longest = max(odd, even, key=lambda y: y[1] - y[0])
currentLongest = max(longest, currentLongest, key=lambda x: x[1] - x[... |
4b22430c3c120bb067e8d29b55bcb405614648f8 | AlessandroMion/Algorithm-Assignment-1 | /main.py | 4,068 | 4.375 | 4 | #P1: Write a program that asks the user for a temperature in Fahrenheit and prints out the same temperature in Celsius.
#Firstly, ask a question for tempF (temp if fahrenheit)
tempF = int(input(" Input a number in Fahrenheit: "))
#then this below is the calculation for the tempF to tempC
tempC = (tempF - 32) * (5 / 9)... |
8ed28e13bf955639eafa22368dfa76cc5e6cf1e0 | ALANKRIT-BHATT/Factorial | /digit seperatiion.py | 118 | 4.0625 | 4 | x=int(input("Enter a number to sperate it's digits "))
while x>0:
y=int(x%10)
print(y)
x=int(x/10)
|
bef02f5f286f0f9ec08e8edfe2b7392dc472c6b2 | mangokangroo/CV_homework | /week3/linear_regression_vectorization.py | 2,187 | 3.71875 | 4 | import numpy as np
import random
# Generate random test data
def gen_sample_data():
w = random.randint(0, 10) + random.random()
b = random.randint(0, 5) + random.random()
num_samples = 100
x_list = []
y_list = []
for i in range(num_samples):
x = random.randint(0, 100) * ran... |
8047f430c12e696aca77d78a08231dbf3abbc578 | austinsonger/CodingChallenges | /Hackerrank/Python/Containers/Word Order/main.py | 411 | 3.65625 | 4 | from collections import defaultdict
n = int(raw_input())
words = list()
word_counter = defaultdict(int)
for i in range(0, n):
key = raw_input().strip()
word_counter[key] += 1
words.append(key)
print len(word_counter)
res = list()
for word in words:
count = word_counter[word]
if count > 0:
... |
4b2c5f78497f558636b2ab4788c7944e39e3e42b | CrazyFrag45/Codewars_tasks | /Task_26_Calculate Meal Total_7kyu.py | 453 | 3.953125 | 4 | '''
Create a function that returns the total of a meal including tip and tax. You should not tip on the tax.
You will be given the subtotal, the tax as a percentage and the tip as a percentage. Please round your result to two
decimal places.
'''
# First:
def calculate_total(subtotal, tax, tip):
return round(subt... |
4afe910faa9fa149f9a39563807b7acaed4e32a5 | sudolm9/MSU_Python | /Python HW 1/named convert.py | 586 | 4.25 | 4 | #This program takes an input from the user and changes the sentence that is inputed.
print('Enter a sentence and i will change it')
a = input('Enter a sentence')
print('The sentence in lower case is: ',a.lower())
a1 = a.lower()
for c in ['a','e','i','o','u']:
a1=a1.replace(c,c.upper())
a2 = a.lower()
for d in ['b',... |
24affeb0ec71a8fef94ac2e81f2f9c02c63f4329 | mandyqcx/scrapy | /learnpython/test/property.py | 378 | 3.59375 | 4 | class Rectangle:
def __init__(self):
self.width=0
self.height=0
def set_size(self,size):
self.width,self.height=size
def get_size(self):
return self.width,self.height
size=property(get_size,set_size)
if __name__=='__main__':
r=Rectangle()
r.width=10
r.height=... |
ac00bff142b2324e656bf45d19451f9e26d10f72 | KuZa91/How-Many-Singular-Values | /HowManySVls.py | 1,885 | 3.515625 | 4 | # This program, once called will load the first argument of the call as the image to analyze,
# and will esteem in function of the required precision how many singular values are necessary for the decomposition
import sys
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
plt.style.use('graysca... |
7e7040b02b6afa6c6575e4e52f95b10b442c527f | gxmls/Python_Basic | /test3_2.py | 193 | 3.515625 | 4 | '''
描述
获得输入的一个字符串s,以字符减号(-)分割s,将其中首尾两段用加号(+)组合后输出。
'''
s=input().split('-')
print("{:}+{}".format(s[0],s[-1]))
|
062a17910e0ca25085b491049d513c3b84ca7663 | inspectorvector/euler | /007.py | 633 | 4 | 4 | import math
def find_prime(number_of_prime): # specifies the prime you want to find, eg (10) = 10th prime number
discovered_primes = []
current_check = 0
while len(discovered_primes) < number_of_prime:
current_check += 1
if is_prime(current_check):
discovered_primes.append(curr... |
b64129677aeca4585da96c728ffa56108a807536 | qwertyoleg/Poly_python | /Rectangle.py | 962 | 4.25 | 4 | from colour import Color
class Rectangle:
def __init__(self, colour = Color("green"), height = 1, width = 2):
self.__height = height
self.__colour = colour
self.__width = width
def get_colour(self):
return self.__colour
def get_width(self):
return self.__width
... |
c37ba66733e957b6a0424a7fa6b7dcf8b4cb0ce5 | acecodes/ace_algos | /ml/rec/rec_engine.py | 7,407 | 3.765625 | 4 | from math import sqrt
"""
A sample recommendation engine
Some code from "Programming Collective Intelligence" by Toby Segaran
"""
def sim_distance(prefs, person1, person2):
"""Distance-based similarity score for two people"""
try:
# Mutually-rated items
similarities = {}
for item in ... |
f2d5b99bd0ab1cba362f7b993a1a31df6957fb47 | tadeuif/Exercicios-ACs | /Matérias/Estrutura de Dados/Aula 6/fila_josephus.py | 883 | 3.53125 | 4 | '''
Tadeu Inocencio Freitas - RA 1800250
Tibério Cruz - RA 1800110
'''
def enqueue(fila, elemento):
fila.append(elemento)
def dequeue(fila):
return fila.pop(0)
def josephus(jogadores, p):
fila = []
i = 1
while len(fila) < jogadores: #Colocando os jogadores na fila
enqueue(fila, i)
... |
a74b914db897d7eec990cada9df55007f7ddd9c9 | mpivet-p/linear_regression | /prediction.py | 539 | 3.90625 | 4 | import sys
import numpy as np
def cost_prediction(x, theta):
return (theta[0] + theta[1] * x)
if __name__ == "__main__":
#Reading data file
try:
theta = np.genfromtxt("theta.csv", delimiter=',', skip_header=1)
except:
sys.exit("theta.csv error")
try:
kilometers = float(in... |
9abe62981241e00a0647ba8384f8d938db55d04e | fengxiaolong4/Data-Structures-and-Algorithms-in-Python | /src/ch06/array_stack.py | 1,129 | 3.953125 | 4 | class Empty(Exception):
"""Error attempting to access an element from an empty container.
"""
pass
class ArrayStack:
"""LIFO Stack implementation using a Python list as underlying storage.
"""
def __init__(self):
"""Create an empty stack."""
self._data = []
def __len__(se... |
43eae009b70b104ab33910348ae6bab4a960000a | gkaustchr/Python | /Aulas/tuplas.py | 565 | 4.03125 | 4 | #TUPLAS SÃO IMUTAVEIS! NÃO PODE ALTERAR OU EXCLUIR ELEMENTOS
num = (10, 20, 30, 40, 50, 60, 70)
print(num)
nume = 10, 11, 12, 13, 14, 15, 16
print(nume)
lista = [num, nume] #Lista de Tuplas
print(lista)
(idade, peso) = "24,70.2".split(',') #Cria um tupla com itens separados por virgulas
print(idade)
print(peso)
#... |
1e696cc62bb85bfd56917923f2ac6e439c8e6748 | cyperh17/python | /OOP/abstract_classes.py | 292 | 3.78125 | 4 | #import abc
from abc import ABCMeta, abstractmethod
class BaseClass(object):
__metaclass__ = ABCMeta
@abstractmethod
def printHam(self):
pass
class DerivedClass(BaseClass):
def printHam(self):
print('Ham')
#x = BaseClass()
d = DerivedClass()
d.printHam() |
241b3d6caf1691b0ca3675d32fc35ad7fbad4070 | akhilpen/CSE305 | /Assignment-2/hw2.py | 9,802 | 3.515625 | 4 | toBind={}
def push(line):
alphabetList = "abcdefghijklmnopqrstuvwxyz"
if '"' in line:
stack.push(line[0:len(line)-1])
elif line[0] in alphabetList:
if line[0:len(line)-1] not in toBind:
toBind[line[0:len(line)-1]] = 'empty'
stack.push(line[0:len(line)-1])
elif line[0] == '-':
if line[1] == '0':
stac... |
40ff3304029531250293b14c4865ed103c9cd126 | kevchengcodes/kcheng | /euler/euler_9.py | 917 | 3.734375 | 4 | """
********* Euler Problem 9 *********
PROMPT:
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
# Use Euclid's formula to find a, b,... |
5d7485c457a030e4058636d566b1f02b8d5f4b29 | AbdulkarimF/Python | /Day15.py | 1,257 | 4.25 | 4 | # Python Lists
# List Length
print('Example 1')
thislist = ['apple', 'banana', 'cherry']
print(len(thislist))
# Add Items
print('Example 2')
thislist = ['apple', 'banana', 'cherry']
thislist.append('orange')
print(thislist)
print('Example 3')
thislist = ['apple', 'banana', 'cherry']
thislist.insert(1, 'oran... |
034ef0103e3ec5965d2f19a5b90fb2f97504da97 | NikitaPavlov1337/codewars | /6_kyu_Persistent_Bugger.py | 893 | 3.890625 | 4 | # Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence,
# which is the number of times you must multiply the digits in num until you reach a single digit.
# For example:
# persistence(39) => 3 # Because 3*9 = 27, 2*7 = 14, 1*4=4
# # a... |
be62507a0a5f779c4d67c9fa6df1b98d84a608b2 | rayt579/leetcode | /premium/google/sorting_and_searching/shortest_distance_from_all_buildings.py | 1,730 | 3.65625 | 4 | from collections import deque
class Solution:
def shortestDistance(self, grid):
"""
:type grid: list[list[int]]
:rtype: int
"""
if not grid or not grid[0]:
return -1
m, n = len(grid), len(grid[0])
min_distance, num_buildings = [[0] * n for _ in r... |
cc456150c52a5cbd33d1370a010199c232d14cfb | tracyhn/Chapter-5-PE.-20 | /Huynh_Chap5_PE20.py | 2,602 | 4.21875 | 4 | #=======================================================================================
#Author: Tracy Huynh
#Program ID: Huynh_Chap5_PE20.py
#Due Date: 04/29/2019
#Description: This program generates a random number from 1 to 100
# and prompts the user to guess it. Tracks the numbe... |
d7f12cc31ba3a8c6d5ef42922787e971fbd18e32 | Catboi347/python_homework | /name_switcher.py | 123 | 3.78125 | 4 | firstname = input("Type in your name ")[::-1]
lastname = input("Type in your last name ")[::-1]
print (firstname, lastname) |
a7a0f90182ab141e90292c09487cbb233b03f63a | AlexBaraban/Python_classes | /Homework_7.py | 3,188 | 4.09375 | 4 | # Homework_7
#
# Задания 1
#
# Попросите пользователя ввести слово без пробелов. Пока он не введёт правильно, просите его ввести.
# Проверьте, что вы правильно закодили с помощью assert инструкции
# Решение
# while True:
# a = str(input('Enter word without space: '))
# if a.find(' ') == -1:
# ... |
c9a38fc1c21c738fa7675561c663333acabc5640 | habereet/awesomeScripts | /simple-image-encryptor/generator.py | 581 | 3.703125 | 4 | #!/usr/bin/env python
# python 3.8.5
import numpy
from PIL import Image
def genImage(img_width=512, img_height=256):
# Define img width and height as an integer
img_width = int(img_width)
img_height = int(img_height)
# Define key name
filename = 'key.png'
img_array = numpy.random.rand(img_he... |
ef9d61c5cd1afc30dc8c1897c3f8c8551043d21f | cutewindy/Leetcode | /Two_Sum.py | 722 | 3.875 | 4 | # Given an array of integers, find two numbers such that they add up to a specific target number.
# The function twoSum should return indices of the two numbers such that
# they add up to the target, where index1 must be less than index2.
# Please note that your returned answers (both index1 and index2) are not zero... |
67987d487e350b58a587f3c2e53dcf87e2d5a609 | Amidala1/GBPython | /Lesson8/Lesson_8_1.py | 1,718 | 3.515625 | 4 | """
1. Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде строки формата «день-месяц-год».
В рамках класса реализовать два метода. Первый, с декоратором @classmethod, должен извлекать число, месяц,
год и преобразовывать их тип к типу «Число». Второй, с декоратором @staticmethod, должен ... |
4243c4ccf54353da6ae3def7fcb7541bda785675 | retr03/python | /hackgame.py | 2,292 | 3.765625 | 4 | user = 'admin'
password = 'password'
user1 = input('enter the username:')
while user1 == user:
print('correct user')
break
else:
print('try again')
user2 = input('enter the paswword:')
while user2 == password:
print('access granted')
break
else:
print('try again')
a = 'a)1. access the... |
4fb08306bc936936ecd07d11655a83e9817ec598 | cs60050/Eagle-I | /GUI_Codes/Segmentation_GUI.py | 967 | 3.609375 | 4 | from Tkinter import *
import tkMessageBox
import tkFileDialog
import os
import glob
import tkFont
top = Tk()
### when button clicks,it selects the file
def helloCallBack():
file_path_string = tkFileDialog.askopenfilename() #stores the file path in a variable
os.system("python3 main.py "+str(file_path_st... |
3cf73fb5000b61eb7e49fe2833d34e0f0a7712d9 | RengaRengarajan/AlgorithmQuestions | /MyBinaryTree.py | 5,314 | 4.0625 | 4 | from LinkedList import LinkedList
class BinaryTree:
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def __init__(self):
self.root: self.TreeNode = None
def add_root_node(self, value):
... |
30e9ca3a26092fce874dc14bac7d908ce89e020a | hkelder/Python | /Lesson1/powers.py | 99 | 4 | 4 | n = int(input("Enter a number:"))
exponent = 0
for exponent in range(17):
print(n ** exponent)
|
f4832bef9ba291b37b50454be3d0190e8a3d147b | zhkflame/StudyCode | /search/liner_search_1.py | 116 | 3.546875 | 4 | def liner_search(v,L):
i=0
while i !=len(L) and L[i]!=v:
i=i+1
return 'none' if i==len(L) else i |
865f574a7be12d8bc9b6281f464f5f23bb88b792 | purvimisal/Rebuilding-Unix-Commands | /rm.py | 555 | 4.0625 | 4 | #rm command is used to remove objects such as files, directories, symbolic links and so on from the file system like UNIX.
import sys
import os
import shutil
path = sys.argv[1]
if os.path.isdir(path):
try:
shutil.rmtree(path)
except OSError as e:
print ("Error: %s - %s." % (e.filename,e.strerro... |
54da2520b2c88dd627583b60c269f8e3b42a7b81 | Lauro199471/ML-Web | /CECS 453/hw3/code/solution.py | 3,608 | 4.03125 | 4 | import numpy as np
from helper import *
'''
Homework2: logistic regression classifier
'''
def sigmoid(s):
return 1 / (1 + np.exp(-s))
def logistic_regression(data, label, max_iter, learning_rate):
'''
The logistic regression classifier function.
Args:
data: train data with shape (1561, 3), w... |
9342c7c3af11d38e35c57ab83d8d50b9c946de45 | waseemw/maze-solver | /FitnessEvaluation.py | 3,699 | 3.890625 | 4 | # Method for calculating agent paths
def RunAgent(agent, StartPos, EndPos, maze):
temp = StartPos.copy() # Making copy of startpos for not changing startpos
path = [] # Empty list for agent path
premove = agent.chromosome[0] # Variable for keeping track of previous move
# Loop to iterate through al... |
8481ce54f800173bc3bb647b5d93b34a36a888e5 | bryan234-ca/trabajos-clase | /año bisiesto.py | 609 | 3.796875 | 4 | # -*- El año es bisiesto o no -*-
"""
Created on Thu Jul 2 14:29:08 2020
@author: Bryan Carpio
"""
def es_bisiesto(anio):
if anio % 400 ==0:
return True
elif anio % 100 ==0:
return False
elif anio % 4 ==0:
return True
else:
return False
anio = 1900
pri... |
23ea2b69ee024471d765a8b28a358430b5ef0506 | krisszcode/3rdsiweek | /game_stat/printing.py | 1,529 | 3.65625 | 4 |
# Printing functions
def count_games(file_name):
with open(file_name, "r") as file:
x=file.readlines()
count=0
for lines in x:
count+=1
return count
print(count_games('game_stat.txt'))
def decide(file_name, year):
with open(file_name, "r") as file:
x=file.... |
7b5700f448e8e2b58b0d2f418bdee857d83ac410 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4159/codes/1593_1805.py | 162 | 3.515625 | 4 | xa = float(input("Xa "))
ya = float(input("Ya "))
xb = float(input("Xb "))
yb = float(input("Yb "))
xm = (xa+xb)/2
ym = (ya+yb)/2
print(round(xm, 1),round(ym, 1)) |
f6262244f9646d4b06939d38f03aaeb123c796ea | briarfox/ShellistaExt | /ShellistaExt/plugins/core/gzip_plugin.py | 883 | 3.59375 | 4 | '''gzip:
tar and gzip a file/directory
'''
from .. tools.toolbox import bash,pprint
import tarfile,os,io
def make_tarfile(source_dir):
bytes = io.BytesIO()
path = os.path.abspath(os.path.join(os.getcwd(),source_dir))
with tarfile.open(fileobj = bytes, mode="w:gz") as tar:
tar.add(path,arcname=os.p... |
61cee6ead9619c86ae2c37105e0bbb950077bfe0 | JPDZ67/alien | /alien/datetime_cleanup.py | 951 | 3.65625 | 4 | import pandas as pd
from datetime import datetime
MIN_DATE = '1999-12-31 23:59:59'
def datetime_cleanup(df, main_df=None):
"""Fixes the datetime column by replacing 24: with 0: and converting to datetime object"""
df['datetime'] = df['datetime'].apply(lambda x: x.replace('24:', '0:'))
df['datetime'] = pd... |
664af0ac1c2267fe2cff870962fb83e014d25947 | kanglicheng/CodeBreakersCode | /Hash Maps/706. Design HashMap (3. same).py | 2,586 | 3.796875 | 4 | # need ask python private class?
class Node:
def __init__(self, key, val):
self.key = key
self.val = val
self.next = None
def link(self, nextNode):
#print("next is set to:" + str(nextNode))
self.next = nextNode
class MyHashMap:
... |
e5abaf6918cb63c67e74f32e7662135c2c6ee84f | Justin-Teng/HackerRank | /Tutorials/30-Days-of-Code/day-25.py | 421 | 4.0625 | 4 | import math
t = int(input())
for _ in range(t):
n = int(input())
if n == 2:
print('Prime')
continue
if n == 1 or n % 2 == 0:
print('Not prime')
continue
flag = False
for i in range(3, math.floor(math.sqrt(n))+1, 2):
if n % i == 0:
print... |
9ff45b042d40ada14c5c8c011b5f6ea1a9f4d991 | Jackyzzk/Coding-Interviews-2 | /剑指offer-面试题45. 把数组排成最小的数.py | 1,154 | 3.6875 | 4 | class Solution(object):
"""
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
输入: [10,2]
输出: "102"
输入: [3,30,34,5,9]
输出: "3033459"
0 < nums.length <= 100
输出结果可能非常大,所以你需要返回一个字符串而不是整数
拼接起来的数字可能会有前导 0,最后结果不需要去掉前导 0
链接:https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof
"""
def minNumber(self... |
f02b0184872e0bbd9f4b9a4ab0fbbd538c3d6663 | NagaSolo/hyperledger-assessment | /question_1a.py | 551 | 4.15625 | 4 |
""" Question 1a
This is unoptimized and coupled solution
Using python built-in module date and calendar
Nested loop increase time complexity
"""
import calendar
from datetime import date
sunday = 0
for y in range(1901, 2001):
sun_text = calendar.TextCalendar(calendar.SUNDAY)... |
83af1b8b57a991d9db957cf4a828121dd815adf3 | YangXinNewlife/LeetCode | /easy/count_binary_substrings_696.py | 1,426 | 3.5 | 4 | # -*- coding:utf-8 -*-
__author__ = 'yangxin_ryan'
"""
Solutions:
题意是计算给定的字符串中有多少个连续、相邻的子串;
例如:00110011
子串:0011、01、10、1100、01、0011
这里为什么00110011不是,原因是001100的00和00中间隔着11,不连续所以不是,那么我们可以设定两个指针pre(旧的) ,cur(当前的)
pre与cur依次交替记录上一个00...或者11...
过程模拟:
index代表下标, value代表下标对应的值
-- 00110011
index = 0, value = 0
cur = 1
pre = 0
inde... |
85d22e63eda0153b7d097c341ce0705294bcbf31 | ll996075dd/xuexi | /day2-11.py | 649 | 3.6875 | 4 | #-*- conding:UTF-8 -*-
#题目:一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?
tour = []
height = []
hei = int(input("请输入高度:")) # 起始高度
tim = 10 # 次数
while(hei):
for i in range(1, tim + 1):
if i == 1:
tour.append(hei)
else:
tour.append(2*hei)
hei /= 2
... |
eb36bb76c20d62f8a8b0d3ba0d9d34dbc4ce653c | sidaf/scripts | /missing_numbers.py | 1,528 | 3.53125 | 4 | #!/usr/bin/env python2.7
import argparse
import sys
def missing_numbers(num_list, start, end):
original_list = [x for x in range(start, end + 1)]
num_list = set(num_list)
return (list(num_list ^ set(original_list)))
########
# MAIN #
########
if __name__ == '__main__':
desc = 'List missing ports fr... |
caaaf82d6e1c94978ff26a223e0b2f1b9dab9d68 | Arpita-Mahapatra/Python_class | /14_03_Task2.py | 1,093 | 3.9375 | 4 | #int_to_int
'''a=2
b=int(a)
print(type(b))
print(b)'''
#int_to_str
'''a=2
b=str(a)
print(type(b))
print(b)'''
#int_to_float
'''a=2
b=float(a)
print(type(b))
print(b)'''
#int_to_bool
'''a=2
b=bool(a)
print(type(b))
print(b)'''
#str_to_int
'''a="Hello"
b= int(a)
print(type(b))
print(b)'''
... |
2210eb8e552efcfcf65c50d990b92a88a2b239ec | bhavyanarra/Library-Management-System-Python | /Books.py | 3,808 | 4.21875 | 4 | from Functions import Update_data
# A new class called Books is created with Update_data being the parent class.
# All the methods from the Update_data class are inherited and relevant methods are used in this Books class.
class Books(Update_data):
def __init__(self):
super().__init__()
# ... |
0a2c3f6468a5a546fc8f7e577c97f0103972ddf7 | Edson-Padilha/Curso_em_video | /ex057_validacao_dados.py | 238 | 3.890625 | 4 | sexo = str(input('Informe seu sexo [M/F]: ')).upper()[0].strip()
while sexo not in 'M F':
sexo = str(input('Dados inválidos. Por favor, informe seu sexo: ')).strip().upper()[0]
print('Sexo {} registrado com sucesso.'.format(sexo))
|
aec6a5fd95afe29fa3d9639b37c86b7025fa9b84 | Oivanov1/python-home | /task3.py | 321 | 4.03125 | 4 | from random import randrange
target_number=randrange(100)
input_digit = int(input('Enter your digit: '))
while input_digit != target_number:
if input_digit>target_number:
print ("Too mach")
else:
print ("Too low")
input_digit = int(input('Enter your digit: '))
print("Nostardamus xD")... |
061257f1ebda51ab94f62af03ea52601bf08fd58 | 89JH/studyRepo | /python/operater.py | 560 | 3.890625 | 4 |
num1 = 20
num2 = 30
print(num1 + num2)
print(num1 - num2)
print(num1 * num2)
print(num1 / num2)
print(num1 % num2)
print(num1 // num2)
print(True | True)
if(num1 < num2):
print('{0} < {1}'.format(num1, num2))
if(num1 == 20):
print('{0}'.format(num1))
if(num1 > num2):
print('{0} > {1}'.format(num1, n... |
d0c7165d49f4ef8753bc76864d8c59e468776866 | Aries5522/daily | /2021届秋招/leetcode/栈/滑动窗口最大值.py | 1,073 | 3.953125 | 4 | '''
给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。
正常来说是on,但是感觉可以用dp
这一题有点难:参考之前实现栈的结构包含最小值,使得找到最小值的为O(1)
使用一个双向队列来完成,左边出右边进
单调队列(从大到小)
有数值进来的时候,pop()掉比他小的
判断左边最大值是不是弹出去的那个,是的话就弹走,否则就保持
'''
from typing import List
import collections
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
... |
88497f813f12969f0818a804a4d4778d221da1a6 | Ellie1994/python_quick_and_dirty | /stand_combine.py | 145 | 3.859375 | 4 | nums = [1,2,3,4,5,6,7,8,9,10]
my_list = []
for letter in "abcd":
for num in range(5):
my_list.append((letter,num))
print(my_list)
|
57e0fb7ff6b99d7397be4407bf10ea35e6819680 | dhreyes/AirBnB_clone | /tests/test_models/test_place.py | 2,738 | 3.609375 | 4 | #!/usr/bin/python3
"""
This module contains unit test for the Place class
"""
from models.place import Place
import unittest
import pep8
class TestPlace(unittest.TestCase):
"""
Test Place class using unit test
"""
def testPep8(self):
"""
Check pep8 linter requirements
"""
... |
01a52a02ae7f21cf8b4ab98e17afc9bacdec0e91 | kimmothy/PuzzleSolver | /container/PriorityQueue.py | 7,187 | 3.734375 | 4 | class HeapNode:
left = None
right = None
data = None
def __init__(self,data):
self. data = data
def heapify(self):
data = self.data
if self.left is None and self.right is None:
return
elif self.right is None:
if self.left.data < self.data:
... |
d1cb0c68d724f0b0d5fc04ac5fc7434d0831b811 | JagritiG/DS-Algorithm-Python3 | /stack/stacks.py | 1,240 | 4.28125 | 4 | class Stack:
def __init__(self):
self.items = []
def push(self, item):
"""Accepts an item as a parameter and appends it to the end of the list.
Returns nothing.
"""
self.items.append(item)
def pop(self):
"""Removes and returns the last item or top item from... |
82573cf114384d8389177f6262fa7bad1c9b4cc2 | ypyao77/python-startup | /python-cookbook/03.digit-date-time/08-fraction.py | 975 | 4.5625 | 5 | #!/usr/bin/env python3
# 3.8 分数运算
import math
# 你进入时间机器,突然发现你正在做小学家庭作业,并涉及到分数计算问题。或者你可能需要写代码去计算在你的木工工厂中的测量值
if __name__ == "__main__":
# fractions 模块可以被用来执行包含分数的数学运算。
from fractions import Fraction
a = Fraction(5, 4)
b = Fraction(7, 16)
print("a: ", a)
print("b: ", b)
print("a + b: ", a +... |
7a962cb52f6c8cd4d97e56b8d6850cbf3c927091 | MehranJanfeshan/python-samples | /error-exception/general-except.py | 206 | 3.53125 | 4 | def add(num1, num2):
try:
result = num1 + num2
# Generic error
except:
print('Something went wrong!')
else:
print('Add went well!')
print(result)
add(1, 2)
|
781766bcb9ce3c052d6b61eb7c8389dc77947830 | ervitis/challenges | /others/bubble/main.py | 347 | 3.78125 | 4 | # -*- coding: utf-8 -*-
def bubble(sentence):
d = list(sentence)
for i in range(len(d) - 1):
for j in range(i, len(d)):
if ord(d[i]) > ord(d[j]):
d[i], d[j] = d[j], d[i]
return d
def main():
print(bubble('dddddzzzzzaazabhgbkirsdwtrhgbjytbaajtyccbb'))
if __name__... |
32a583f1765bf694738fa095a126b6a011dc9bcc | bradpenney/learningPython | /SquareSpiral1.py | 175 | 3.96875 | 4 | #SquareSpiral1.py - Draws a square spiral
import turtle
t = turtle.Pen()
turtle.bgcolor('black')
for x in range(300):
t.pencolor('red')
t.forward(x)
t.left(90) |
9a2dabf066d048f5996291059a15e5f404efbef4 | Jasmine-2002/Python | /pta.py | 435 | 3.6875 | 4 | def Freq(line):
rlist = list(line)
rdict = {}
for i in rlist:
if rdict.get(i,-1)==-1:
rdict[i] = 1
else:
rdict[i] += 1
print(len(rdict))
res = sorted(rdict)
print(res)
k = 0
for j in range(len(rdict)):
for key,value in rdict.items():
... |
263e95e488bc24069d3e2d794d8e181ae0bdbe17 | lestupinanp/inflammation | /mosquito.py | 527 | 3.703125 | 4 | import pandas
from matplotlib import pyplot as plt
data= pandas.read_csv('mosquito_data.csv')
print plt.plot(data['year'], data['mosquitos'])
plt.show()
print "hello world"
a= 5*2
print a
#print data['rainfall'][data['rainfall']>200]
#print data.mean()
#
#for temp in data['temperature']:
# celsius= (temp-32)/1.8
# ... |
7c633aeb0548138084e155afa122a43b1cc2053b | songjon93/Projects | /AI/Chess/Chess/Iterative.py | 821 | 3.875 | 4 | import chess
from MinimaxAI import MinimaxAI
class Iterative():
def __init__(self, depth):
self.depth = depth
# Loop from 1 to the designated depth, initiallize the minimaxAI object with the iterated depth, search for the
# optimal move. If there was a change msade to the optimal move throughout t... |
bcee917c525b73626b6c07d1b50c5ef7d941df43 | Praneeth313/Python | /Guessing Game.py | 1,537 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 14 19:46:38 2021
@author: Lenovo
"""
"""
Guess the Number
A simple game in which the user/player has to guess the number that is randomly
picked by the computer.
"""
'''
import randoom module to generate a random number from the range set by user.
''... |
ad0378f416ada014006ef860b5df2fea6569b42e | Eger37/algoritmization | /second_colloquium/45.py | 863 | 3.9375 | 4 | # 45. Перетин даху має форму півкола з радіусом R м. Сформувати таблицю,
# яка містить довжини опор, які встановлюються через кожні R / 5 м.
import math
# from sympy import symbols, S
# import numpy as np
def my_int_input(text_def):
while True:
try:
input_num_def = int(input(text_d... |
5cdf7a1d3b55d89bbce3183ffad615ff193a1c2b | kiyoxi2020/leetcode | /code/leetcode-206.py | 625 | 3.671875 | 4 | '''
leetcode 206. 反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseList(self, head):
"""
:type h... |
1e8eaec6b17722c22a4f6e1f284d9214e46d9f0d | Jiangjao/-algorithm015 | /Week_03/construct-binary-tree-from-preorder-and-inorder-traversal.py | 845 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import copy
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: L... |
ab1b90560107b3912e4225d0dec02f944222eb62 | FluffyFu/Leetcode | /71_simplify_path/solution.py | 313 | 3.90625 | 4 | def simplify_path(path):
path = path.split('/')
stack = []
for d in path:
if d and d != '.' and d != '..' and d != '/':
stack.append(d)
elif d == '..' and stack:
stack.pop()
if not stack:
return '/'
else:
return '/' + '/'.join(stack)
|
9fa9050e2ec7f39ebbd2f259402d0544c46a7e90 | ansuns/python-exam | /oop/student.py | 6,175 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'RoLiHop'
#实例的变量名如果以__(两个)开头,就变成了一个私有变量(private)
class Student(object):
def __init__(self, name, age):
self.__name = name
self.__age = age
def print_score(self):
print('%s的年龄是:%s'%(self.__name, self.__age))
d... |
948314f745ca29f5f644a4bc5253b1ec3d64e8b5 | GitHhb/hackerrank | /interoffice-travel/interoffice-travel-v5.py | 2,810 | 3.78125 | 4 | #!/bin/python
import sys
import array
sys.stdin = open('./2-input', 'r')
# sys.stdin = open('./1-input', 'r')
n = int(raw_input().strip())
# Each index 'i' contains the energy necessary to travel 'i' units.
w = map(int, raw_input().strip().split(' '))
# connections as list pointing to list of connected nodes
con = ... |
1dbc1c782f0ec776bd3c9ddd0a8fc6a7f232f87f | shimuraii/MachineLearning | /LinearFINAL/test.py | 1,607 | 3.640625 | 4 | import pandas as pd
import numpy as np
import sklearn
from sklearn import linear_model
import matplotlib.pyplot as pyplot
import pickle
from matplotlib import style
data = pd.read_csv("student-mat.csv", sep=";")
print(data.head())
data = data[["G1", "G2", "G3", "studytime", "absences", "freetime"]]
predic... |
b62642ba1787f402789d4bc6d31a7bc839401ec8 | zoeang/pythoncourse2018 | /day03/Ang_lab03.py | 1,616 | 4.125 | 4 | import string
## 1. write tests in lab03_tests.py
## 2. then code for the following functions
## Raising errors is more common when developing ------------------------
## These functions all take a single string as an argument.
## Presumably your code won't work for an int
## raise a built-in (or custom!) exception i... |
73b7c4320fb24dee8fec879d4b9a940150e1a0f7 | Tiago-Baptista/CursoEmVideo_Python3 | /cursoemvideo/python3_mundo3/aula_20/ex098.py | 699 | 3.71875 | 4 | from time import sleep
def contador(a, b, c):
for t in range(a, b, c):
sleep(0.5)
print(f'{t} ', end='')
sleep(2)
print()
# Programa principal
print('Contagem de 1 a 10 de 1 em 1')
contador(1, 11, 1)
print('Contagem de 10 a 0 de 2 em 2')
contador(10, -1, -2)
print('Contagem personalizada')... |
3101a4f7d4c38874e281158de39cb1514aa6e63a | steven-shi/LeetcodeSolutions | /algorithms/island-perimeter.py | 1,909 | 3.953125 | 4 | '''
https://leetcode.com/problems/island-perimeter/
Island Perimeter
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one islan... |
ab7f426c87f778d45cfcd044a37b07f72b61433e | tonyzhangqi2000/learning | /day02/exercise02.py | 295 | 3.8125 | 4 | # 练习题:
# 输入四位整数,分别取出各位数据
# 计算各位数字之和
inputValue = input("请输入四位整数:")
inputValue = int(inputValue)
a = inputValue % 10
b = (inputValue // 10) % 10
c = (inputValue // 100) % 10
d = inputValue // 1000
e = a + b + c + d
print(e)
|
d75bbaf6a902034ade93a755ce5762091a2f2532 | driscolllu17/csf_prog_labs | /hw2.py | 2,408 | 4.375 | 4 | # Name: Joseph Barnes
# Evergreen Login: barjos05
# Computer Science Foundations
# Homework 2
# You may do your work by editing this file, or by typing code at the
# command line and copying it into the appropriate part of this file when
# you are done. When you are done, running this file should compute and
# print ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.