blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3eac98ab5b902b1a74323c6f3f3471b06933807c | cabbageGG/play_with_algorithm | /LeetCode/59. 螺旋矩阵 II.py | 1,730 | 3.84375 | 4 | #-*- coding: utf-8 -*-
# '''
# 给出正整数 n,生成正方形矩阵,矩阵元素为 1 到 n2 ,元素按顺时针顺序螺旋排列。
# 例如,
# 给定正整数 n = 3,
# 应返回如下矩阵:
# [
# [ 1, 2, 3 ],
# [ 8, 9, 4 ],
# [ 7, 6, 5 ]
# ]
# '''
class Solution:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""... |
82ee5f5e8f11181d9150f55200a9817ef2ecefeb | clarizamayo/JupyterNotebooks | /Labs/Week 7/Clariza_Mayo-module.py | 1,030 | 4.09375 | 4 | from random import randint
class GuessingColors:
def __init__(self):
self.max_guesses = 3
self.guesses = 0
self.colors = ["green", "blue", "white"]
@staticmethod
def welcome_message():
print("Welcome to the Guessing colors' game!")
def start(se... |
b38be31d1c11d06ad9827eae0c81a706bfd7ec21 | flaviodev/python-course2 | /src/app/menu.py | 1,182 | 3.515625 | 4 | def show_menu(str_title, dict_options, dict_functions):
while(1):
print_title(str_title)
print_menu_title()
print_menu_options(dict_options)
chosen_option = get_chosen_option()
try:
if(int(chosen_option) == 0):
break
e... |
a0c41fe55387de36a7655632caae5f3f1ef73514 | kingmadridli/Staj_1 | /8_2021/27.08.2021/pd_1_introduction.py | 508 | 4.21875 | 4 | import pandas as pd
# pandas is used for dataframes
dict_1 = {
"NAME":["Ali","Veli","Kenan","Hilal","Ayşe","Evren"],
"Age":[15,16,17,33,45,66],
"Salary":[100,150,240,350,110,220]
}
data_frame_1 = pd.DataFrame(dict_1) # Creating a dataframe using dict_1
print(data_frame_1)
... |
a736165d9a19b68673675880ed236a1298ccc790 | catsymptote/Lektor_Programming | /Code/Oblig_2/Other/2-1-c.py | 802 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 11:02:15 2019
@author: catsymptote
Oppgave 2.1, c
"""
import matplotlib.pylab as plt
import numpy as np
# p-vector is the P(x)-function base vector ("p_i")
# u-vector is the input vector ("x").
p = [1, 3, -2, 6, 4, -9, 1, 8]
u = [-4, 1, 5, 9, -... |
99bb4ca3e38712453ffe0d6ea415c71d97fb9136 | SulavThapa/Python-Simple-store-product-calculation | /write.py | 538 | 3.53125 | 4 | def writing(List, Dictionary):
list_=List
dict_=Dictionary
for key_ in dict_.keys():
if key_=="PHONE":
list_[0][2]=str(int(list_[0][2])-dict_["PHONE"])
elif key_=="LAPTOP":
list_[1][2]=str(int(list_[1][2])-dict_["LAPTOP"])
else:
list_[2][2... |
f8b09daad945ed342390989aa200df70811edbaf | leoopez/StructuresPy | /Tree/BinaryTree/BinaryTree.py | 3,570 | 3.859375 | 4 | class TreeNode:
def __init__(self, data=None, parent=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
self.parent = parent
def __str__(self):
return str(self.data)
class BinaryTree:
def __init__(self, values=None):
... |
e9fd2d58f04c06c30fd45c3f33f74394860dc0e6 | natebrunelle/cs1110f18 | /markdown/files/cs1110-001f19/rays_turtle_race.py | 1,623 | 4.53125 | 5 | import turtle
import random # we will get access to the random library, so that we can generate random numbers
number_of_turtles=10
# this creates a variable called turtle, of type list
# a list is a collection that we can add and remove members from
# we will use this list to add several turtles in to a common gro... |
a58247698bb01f274fd59e2d7fb9e7b1ab4dbaa2 | SethPate/AdventOfCode | /2016/day8/seth8b.py | 5,108 | 3.828125 | 4 | input1 = open('input.txt', 'r')
content = [i.strip() for i in input1.readlines()]
#test_content = ['rect 3x2','rotate column x=1 by 1','rotate row y=0 by 4','rotate column x=1 by 1']
screen = [range(0,50) for i in range(0,6)] #create the screen
for i in range(len(screen)): #set all pixels to 'off'
for j in range(0,... |
411f6781abca0ffc7f54aca570e291e315aa17ca | shjang1013/Algorithm | /BAEKJOON/1차원배열/4344_평균은 넘겠지.py | 318 | 3.640625 | 4 | # 입력
num = int(input())
for _ in range(num):
count = 0
test_case = list(map(int, input().split()))
avg = sum(test_case[1:])/test_case[0]
for j in test_case[1:]:
# 평균을 넘는 학생의 수
if avg<j:
count += 1
print("%.3f%%" %round(count/test_case[0]*100,3))
|
bf1c0ff62bfa4b7474ef4acbbb6e1f67f2224dca | ccie5601/pyLearn | /splits.py | 380 | 4.21875 | 4 | #split a string into an array with a for loop
def split_str(s):
return [ch for ch in s]
#split a string using list operator
def split_str(s):
return list(s)
# default splits at space
variable.split()
# split at the colon
variable.split(':')
# split at comma
variable.split(',')
# split at length of number x
spl... |
446a6af553577342880cde453fbf80851a7daba2 | yhw-miracle/tkinter_demo | /demo/demo002_OOP.py | 649 | 3.515625 | 4 | # -*- coding: utf-8 -*-
# @Time: 2019/8/3 21:00
# @Author: yhw-miracle
# @Email: yhw_software@qq.com
# @File: demo002_OOP.py
# @Software: PyCharm
from tkinter import *
class App:
def __init__(self, master):
frame = Frame(master = master)
frame.pack()
self.button = Button(frame, text = "ex... |
fe133b2950009493536bb2b2998d28189b0e434d | whodanyalahmed/coursera_assignments | /coursera/DS/lst.py | 209 | 3.765625 | 4 | fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
f = line.split()
for i in f:
if i in lst:
continue
lst.append(i)
so = sorted(lst)
print(so)
|
dae4d467ff187ab8cbf6d5175e6656ea563854a3 | sbuddhiraju/Symbolic-Regression | /equation_tree.py | 3,604 | 3.578125 | 4 | from numpy.random import random
# implements an equation tree class
class Node:
def __init__(self):
self.val = None # value of node, corresponding to the value up to that node when x is entered and constants are specified
self.name = None # name of node
self.eq_class = None #... |
39dd29ef89151c74a0c76f76ea2d10ef5c2c4dcf | anuragsinhame/algos | /prime_number.py | 333 | 3.96875 | 4 | def check_prime(n):
i = 2
if(n>2):
while(i != (n//2)):
if(n%i==0):
return False
else:
i+=1
elif(n==2):
return True
else:
return False
return True
for i in range(0,100):
if check_prime(i):
print(f"{i} is a pr... |
be68f88ed9cd2af6e2f82694b7423406713c1de3 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4067/codes/1643_2704.py | 149 | 3.828125 | 4 | nota = float(input("nota: "))
boni = input("boni: ")
if boni.upper() == "S":
mensagem = nota + (10/100* nota)
else:
mensagem = nota
print(mensagem) |
63203b631c9062c10c2fdce91a451e59b635f0b3 | wolfworld6/AlgorithmNote | /base/sort/python/HeapSort.py | 1,975 | 3.5 | 4 | # 堆排序 时间复杂度O(nlog2n) 最坏情况O(nlog2n) 空间复杂度O(1) 不稳定
def heap_sort(unsort_nums):
# 最后一个非叶子节点(假设为k,则2k+1=len(n)-1或2k+2=len(n)-1)
last_non_leaf_node = (len(unsort_nums) - 2) // 2
for i in range(last_non_leaf_node, -1, -1):
print('--------heap_sort----------', i)
# 从最后一个非叶子节点往前,挨个保证非叶子节点的值比叶子节点的大
... |
ba475365227af14b6bc650b9b69d713743e5dab8 | viraldii/PracticeBin | /forLoops.py | 505 | 4.3125 | 4 | user = {
'name': 'Golem',
'age': 4000,
'canSwim': False
}
print(user)
#iterable items include: List, Dictionaries, Tuples,
#Sets, Strings
#Print Key and value within the Object
for item in user.items():
print(item)
#Prints all the values in the Object
for item in user.values():
#tuple unpacking
... |
3aa3b9506454642b2d5bbd7e2b6125885e170050 | easternRainy/LeetCode | /LeetCode1048.py | 2,311 | 3.90625 | 4 | class Node:
def __init__(self, s):
self.s = s
self.children = []
def debug(self):
print(self.s)
for n in self.children:
n.debug()
class NodeTree:
def __init__(self):
self.root = Node("")
def add(self, s):
if len(self.root... |
e02f34ae2a7392599d75db41ef2a1d8a89fcf120 | revantg/dippernight | /bccl/sales_order_details/scrape_table.py | 8,964 | 3.859375 | 4 | """
This program scrapes the data from BCCL website.
It makes use of the area_info.pickle file generated by
running the scraping.py prorgam.
It saves the final Data in the pickle format in the file
"scraped_data.pickle" and in JSON format in file
"scraped_data.json".
See usage at the end ... |
c89ad827da1772fa72cb0a9b434e23ee6b9d5de4 | Bushmangreen/my_world | /Season_2/Exercises/k_th_smallest_prime_fraction.py | 492 | 3.78125 | 4 | def k_th_smallest_prime_fraction(array, k):
my_list = []
permutation = (len(array) * (len(array) - 1)) / 2
for i in range(len(array)-1):
for j in range(i+1,len(array)):
my_list.append(array[i]/array[j])
sorted(my_list)
for i in range(len(array)-1):
for j in range(i+1,len(array)):
if (my_list[k-1] == arra... |
4d8b108b635e9703e41763c8bcf352d277795c3b | sunilnandihalli/leetcode | /editor/en/[95]Unique Binary Search Trees II.py | 1,540 | 3.96875 | 4 | # Given an integer n, generate all structurally unique BST's (binary search tree
# s) that store values 1 ... n.
#
# Example:
#
#
# Input: 3
# Output:
# [
# [1,null,3,2],
# [3,2,null,1],
# [3,1,null,null,2],
# [2,1,3],
# [1,null,2,null,3]
# ]
# Explanation:
# The above output corresponds to the 5 uniqu... |
99fbbb0d72af14f0afe5637910d9dc4c2077da7f | AlfonsoVenancio/BasesNoRelacionales | /BDnR/Programas/Python/Ej1_5_UsoDiccionario.py | 627 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 22 13:19:05 2019
Ej. 1.5: devuelve como diccionario las palabras que aparecen dentro de una
cadena dada como parámetro, junto con sus ocurrencias.
@author: psdist
"""
def palabras(cad):
#Separa cada palabra y las entrega en una lista.
lista= cad.split()
print(lista... |
055a78114089726d90e8713821828310a7718772 | PemLer/Journey_of_Algorithm | /nowcoder/T27_Permutation.py | 561 | 3.5625 | 4 | # -*- coding:utf-8 -*-
class Solution:
def Permutation(self, ss):
if not ss:
return []
self.res = []
ss_list = list(ss)
self.dfs(ss_list, [])
return sorted(list(set([''.join(x) for x in self.res])))
def dfs(self, ss_list, sub):
if not ss_list:
... |
b708c3c234e16e44dd6a67f5b2913e7ccf960e7a | mariadiaz-lpsr/class-samples | /drawColorGrid.py | 750 | 3.71875 | 4 | import turtle
def drawSideSquare(myTurtle):
length = 0
while length < 2:
drawFigure(myTurtle)
length = length + 1
def drawFigure(myTurtle):
myTurtle.color('red')
drawSquare(myTurtle)
myTurtle.right(90)
myTurtle.color('yellow')
drawSquare(myTurtle)
myTurtle.right(90)
myTurtle.color('blue')
d... |
adeba685c03c3f7593c4a7bde14a28b25a21f48a | ruchi2ch/Python-Programming-Assignment | /week 1/1_3.py | 330 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 01:40:12 2020
@author: HP FOLIO 9480M
"""
'''Problem 1_3:
Write a function problem1_3(n) that adds up the numbers 1 through n and
prints out the result.
'''
def problem1_3(n):
my_sum=0
i=1
while i<=n :
my_sum +=i
i+=1
p... |
7c2a7287932fa034997ac48726758380568cbbc5 | Zogheen/it254DetectACLAnomalies | /int.py | 1,022 | 3.890625 | 4 | #!/usr/bin/env python3
class int:
def __init__(self, name, ip):
self.name = name
self.ip = ip
self.inn = list()
self.out = list()
def addaclin(self, aclnum):
self.inn.append(aclnum)
def addaclout(self, aclnum):
self.out.append(aclnum)
def ... |
e47e606cd628a73f82770772d731f5fb0b5bcbc6 | osbaldoAlbornoz/python-scripts | /funcionDecoradora2.py | 1,102 | 3.828125 | 4 | # V74 Funcion Decoradora 2 (con parametros)
# Haremos una funcion decoradora para agregar funcionalidad a las funciones suma y resta
def funcion_decoradora(funcion_parametro):
def funcion_interior(*args, **kwargs): #con *args se indica que se pueden recibir un numero indeterminado de parametros
# con *kw... |
36a1083839987f08e7595c7d4da81f33321d6a0b | BONK1/Python | /conditionalStatements.py | 328 | 4.1875 | 4 | #US Election Voting System
name = input("What's your name?")
age = int(input("What's your age?"))
if age < 100 and age > 0:
if age >= 18:
print(f'{name} is allowed to vote!')
else:
print(f'{name} is not allowed this year!')
else:
print(f'{name}, Please enter a proper... |
4dc94791104539157179c11ee73dbb358fdf2834 | YoyinZyc/Leetcode_Python | /LinkedIn/Pro366_Find_Leaves_of_BT.py | 834 | 3.65625 | 4 | '''
LinkedIn_Medium
10.14 6:27pm
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findLeaves(self, root):
"""
:type root: TreeNode
:rtype:... |
be88a32490d163ec1b98830b01e517a836e45fed | AdamZhouSE/pythonHomework | /Code/CodeRecords/2396/61094/320601.py | 163 | 3.8125 | 4 | n=input()
s=input()
if(s=='3 4 5 1 6 2'):
print('4 6 4 5 6 6 ',end='')
elif(s=='4 1 3 5 2'):
print('2 5 4 5 5 ',end='')
else:
print('2 4 4 4 ',end='') |
566e1f76375c5ab8a5fe79fb4b7379bc01004f9f | clefego/python-codes | /tipo.py | 301 | 3.9375 | 4 | n1 = int(input('Digite o valor1: '))
n2 = int(input('Digite o valor1: '))
n3 = float(input('Digite o valor3: '))
s1 = n1 + n2
print('A soma entre', n1, 'e', n2, 'vale', s1)
print('A soma entre {0} e {1} vale {2}'.format(n1, n2, s1))
print('O valor decimal vale: ', n3)
print(type(n2))
print(type(n3)) |
6d9781a3e3f16d9168183f08c8a2d4b50e8c99f4 | archerckk/PyTest | /Ar_Script/ar_270_NLP处理练习.py | 1,161 | 3.625 | 4 | import re
"""
1、读取文件
2、去掉所有的标点符号和换行符,并把所有大写变成小写;
3、合并相同的词,统计每个词出现的频率,并按照词频从大到小排序;
4、将结果安航输出到文件out.txt
"""
def parser(text):
'去掉所有的换行符和标点符号'
text=re.sub(r'[^\w ]','',text)
'将所有大写变成小写'
text=text.lower()
'将字符串用空格分隔开来'
text=text.split(' ')
'过滤掉那些空字符串'
text=filter(None,text)
'统计字符串频... |
dd160742e75e9f40768d020d95b45501681a9a9c | WinstonR96/BDGUI | /principal.py | 11,839 | 3.546875 | 4 | #Elaborado por Winston Junior Rodriguez Stand - Estudiante 5to semestre de Ingenìeria de Sistemas
#importamos los modulos necesarios, en el caso "Tkinter (GUI) y MySQLdb(Base de datos)"
from tkinter import *
from tkinter.messagebox import showinfo
import MySQLdb
#definimos metodos que seran utilizados
def iniciar():#m... |
f5f36564fbd91a209c5b4a587c2c275fcbc83663 | Perilynn/HackerRank-Coding-Challenges | /Data Structures/Median Updates/Sri.py | 1,276 | 3.546875 | 4 | #!/bin/python
def opDeterminer(ops):
vals = []
for op in ops:
if op[0] == 'r':
(vals, success) = removeOp(vals, long(op[1]))
if not success:
print ('Wrong!')
continue
elif op[0] == 'a':
(vals, success) = addOp(vals, long(op[1])... |
bd5e2819f37dfde1511bf22b774062809b4f49bb | momentum-cohort-2018-10/w1d2-house-hunting-dacs2010 | /House_Hunting.py | 948 | 4.21875 | 4 | total_cost = float(input("Enter the cost of your dream home: "))
print("dream home price " + str(total_cost))
annual_salary = float(input("Enter your annual salary: "))
print("how much you make " + str(annual_salary))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
print("port... |
b1bae4b3c95226ba85208fe2f54aa9530e9ba585 | knpatil/learning-python | /src/car.py | 1,524 | 4.25 | 4 | class Car:
# constructor
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
# odometer
self.odometer_reading = 0
self.color = "red"
# to string method -- means string representation of object
def __str__(self):
... |
b09c6471d6d678ac473a32b613e2295a9ba3d2f4 | Chandramani/learningApacheMahout | /src/python/chapter3/src/CategoricalFeatureToBinary.py | 877 | 3.546875 | 4 | __author__ = 'ctiwary'
import pandas as pd
import patsy
class CategoricalFeatureToBinary:
def __init__(self):
pass
# read the csv into a data frame
df = pd.read_csv("../../../../data/chapter3/adult.data.csv")
# print the column headers
print df.columns.values
#convert the selected co... |
79c7873bb29222420f5733040e902bd38d9d4ad0 | Harrison-Z1000/CMPT120-Project | /vindauga.py | 36,157 | 4.28125 | 4 | # Introduction to Programming
# Authors: Harrison Zheng, Will Dye, and Brendan Pacheco
# Date: 12/13/2019
# Final Project: This is a text based adventure game.
from player import Player
from locale import Location
from item import Item
def main():
title()
name = input("Enter your name: ")
player_object ... |
138756edd0ba4a33cca35794ebd7540914cd5c14 | RieLCho/PS_Practice | /Baekjoon/baekjoon/5543.py | 346 | 3.640625 | 4 | burger = [0 for i in range(3)]
nomimono = [0 for i in range(2)]
burger[0] = int(input())
burger[1] = int(input())
burger[2] = int(input())
nomimono[0] = int(input())
nomimono[1] = int(input())
result = 10**9
for i in range(3):
for j in range(2):
temp = burger[i] + nomimono[j] - 50
result = min(res... |
78a122845734230f6fc2c96bc3d61c4c9684581b | CodeInDna/Algo_with_Python | /03_Hard/03_Largest_Range/Largest_Range.py | 1,644 | 4.09375 | 4 | # ---------------------------------- PROBLEM 3 (HARD) --------------------------------------#
# Largest Range
# Write a function that takes in an array of integers and returns an array of length 2 representing
# the largest range of numbers contained in that array. The first number in the output array should be
# th... |
ba75d3985e46be76863ba1b29f444a11c1edb065 | sarthakjain95/UPESx162 | /SEM I/CSE/PYTHON CLASS/CLASSx7.py | 2,077 | 3.65625 | 4 |
#! /usr/bin/env python3
import numpy as np
a= np.array([234,23,42,34,23,5,2354,23,4324])
print(a)
b= np.array([(234,234,23,423,4,32,4,234),(23,423,65,865,8,65,765,765) ])
print(b)
c= np.array([(214234234),(),(234234),(),(),(234324)])
print(c)
matrix= [ [1,2,3], [4,5,6], [7,8,9] ]
matrix= np.array(matrix)
print( ... |
a7eb56d2a9e5080fbf2828cab3c57eaf53aade01 | tejashvi1411/FileSeperatorPythonProgramme | /File Seperator.py | 1,121 | 3.828125 | 4 | #File Seperator Application
#By Tejashvi
#Moves Audio,Video And Document Files Into Seperate Folders
import os, shutil
dict = {'audioext': ['.mp3','.m4a','.wav','.flac'],
'videoext':['.mp4','.mkv','.MKV','.mpeg','.flv','.vlc'],
'documentext':['.pdf','.txt','.doc','.docx','.PPTX','.PPT','.xlsx']}
path = inp... |
81aa2ee36e3ae549fea5d72bdca67d1626f824c9 | Madhivarman/DataStructures | /leetcodeProblems/gas_station.py | 1,063 | 4 | 4 | """
Problem Statement:
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You
begin the journey with an empty tank at one of the gas sta... |
6f369aee03a6c142d3811f23e470a274a094e1fc | abhishek-1986/MyPythonLearning | /venv/numbers.py | 271 | 4.0625 | 4 | x=10 #int
y=11.2
print(float(x)) #float() Converts int to float
print(int(y)) #int() converts from float to int
largenumber=max(10,20,30,40,50) #max() returns maximum of the given numbers
print(largenumber)
smallnumber=min(1,2,-1,3,4,5,-4)
print(smallnumber) |
618ed0fbdb1d75e0831b5628558539c96f62c709 | ogarnica/Compumaticas | /circulo.py | 353 | 3.78125 | 4 | import turtle
t = turtle.Pen()
a = 10
for x in range(20):
turtle.speed(0)
t.forward(a)
t.backward(a)
t.left(5)
a += 3
for x in range(7):
turtle.speed(0)
t.forward(a)
t.backward(a)
t.left(5)
a -= 1
for x in range(20):
turtle.speed(0)
t.forward(a)
t.backward(a)
t... |
167004b639708d5777758d3326074726eb531ca0 | PoornimaDevii/python_training | /PycharmProjects/samp_proj1/unix_cmds9.py | 1,395 | 3.53125 | 4 | import os, time,sys
print("The child will write text to a pipe and")
print("The parent will read the text written by child")
r, w = os.pipe()
x = 9
pid = os.fork() # Replicating the process
#print("Hello World")
if pid == 0:
time.sleep(5)
x = x + 9
f = open('dictout.txt', 'w')
f.write(str(x))
f.c... |
67fc4f5abe2b99442b4215eb60a6b5b48d0af630 | p17055/PYTHON-ERGASIA-EXAMINOY | /ask7.py | 267 | 3.734375 | 4 | from datetime import datetime
now = datetime.now()
today = now.day
samedates = 0
for i in range (1, 10):
if datetime.today().day + i == today:
samedates = samedates +1
answer = 'Same dates as today within the next 10 years:'
print(samedates, answer)
|
b58c7c4ad60d5dc9e15716fa7166394fadfe28c3 | mniju/Datastructures | /EPI book/5.6 Buy and sell Stock.py | 1,813 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 19 19:00:56 2020
@author: niju
"""
from typing import List
def buysellstock(A: List[float]) -> float:
minbuyprice = A[0] # inf also works
profit = -10000 # zero also works
for price in A:
if price < minbuyprice:
minb... |
cdd7665e03d392060b7518d1bc1085ebb376f9ad | william-frazier/exercism | /anagram/anagram.py | 652 | 3.84375 | 4 | def find_anagrams(word, candidates):
letter_dict = dict()
result = []
for letter in word:
letter = letter.lower()
if letter not in letter_dict:
letter_dict[letter] = 1
else:
letter_dict[letter] += 1
for poss in candidates:
poss_letter_dict = dict()... |
97425a5a5f3a5a2745c2c24ea8a998f7c617dd24 | Afriendarko/revert | /demo.py | 188 | 3.96875 | 4 | digits = 0
letters = 0
st = input("Enter the string: ")
for i in st:
if (i.isdigit()):
digits = digits+1
letters = len(st)-digits
print("Digits: ",digits,"Letters: ",letters)
|
7c4ab6e2ed153e1193fdf3afe7fee0fe5e6dad3e | venkatadri123/Python_Programs | /100_Basic_Programs/program_92.py | 430 | 3.875 | 4 | # 92. With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list
# after removing all duplicate values with original order reserved.
# li=[12,24,35,24,88,120,155,88,120,155]
# print(set(li))
# def removeDuplicate( li ):
list = [12, 24, 35, 24, 88, 120, 155, 88, 120, 155]
list1=[]
for i ... |
b79dc25ed05a1c0ae04f87076f2315d7a79fa805 | caption01/python-beginner-mark | /oop/car.py | 803 | 4.1875 | 4 | class Car:
"""Represent a car object"""
miles = 0
def __init__(self, color, make, modal, miles=0):
"""Set initial detail of car"""
self.color = color
self.make = make
self.modal = modal
self.miles = miles
def add_miles(self, miles):
"""Increase miles by ... |
8f55f67b47bbff1a4f5699be254157a28927074c | mackorone/euler | /src/017.py | 1,088 | 3.84375 | 4 | ONES_DIGITS = [
'', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine',
]
TENS_DIGITS = [
'', None, 'twenty', 'thirty', 'forty',
'fifty', 'sixty', 'seventy', 'eighty', 'ninety',
]
TEENS = [
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fiftee... |
7269c36007cda1808dccdff784d67c872839b3b3 | Yennutiebat/Noeties_repo | /TICT-VIPROG-15/Les04/Practive files/4.4..py | 423 | 3.671875 | 4 | def new_password(oldpassword,newpassword):
if oldpassword != newpassword and \
len(newpassword) >= 6:
for c in newpassword:
if c in '0123456789':
return True
return False
else:
return False
res = new_password('vakProg17','python17')
print(... |
7e90e1788e960602a28935b5ce39deb929800571 | kimnh16/Homework | /17-09-28/input_practice.py | 111 | 3.703125 | 4 | #x=input("?")
#a=int(x)
#y=input("?")
#b=int(y)
#print(a*b)
x=int(input("?"))
y=int(input("?"))
print(x*y)
|
4ed1b5af7363df3f9447fdeaf2317eeaf9604b8f | andyzt/tceh-python | /course2/try_except.py | 839 | 4.15625 | 4 | # -*- coding: utf-8 -*-
try:
print(1/0)
except:
print('Bad operation!')
try:
print(1/0)
except Exception as ex: # there's difference with `except:`
print('Bad operation!', type(ex), ex)
try:
print(1/0)
except ZeroDivisionError as ex:
print('Divided by zero!', ex)
try:
raise ValueError... |
a3f93c7e25423fea0a3785997995f70bdc707f9a | muthazhagu/simpleETL | /main.py | 597 | 3.546875 | 4 | from insertdocuments import insertDocuments
from insertrecords import insertRecords
import sys
def main(args):
"""
This method calls the insertDocuments module, and inserts n number of documents
into MongoDB.
Then it calls the insertRecords module to insert the documents in MongoDB in to
SQLite.
... |
aed710442c5cf49a03b9c8e2d21eec260d75ef75 | vvek475/Competetive_Programming | /Competitive/comp_8/Q2_LION_squad.py | 687 | 4.28125 | 4 |
def reverse_num(inp):
#this line converts number to positive if negative
num=abs(inp)
strn=str(num)
nums=int(strn[::-1])
#these above lines converts num to string and is reversed
if inp>0:
print(nums)
else:
#if input was negative this converts to negative again after above proce... |
047575676bdba75e3c03a58a407fca7f32656cb0 | HyPerSix/PythonCoding | /Coding/order.py | 2,241 | 4.03125 | 4 | def add():
iname=input("Enter item name : ")
while True:
if iname.upper()=="":
print("Please try again !!!")
iname=input("Enter item name : ")
else:
break
itemm=int(input("How many item ? : "))
cost=float(input(f"How much {iname} ? : "))
ii=-1... |
7726f162db4370fa371b0158d9863d2d78c5c895 | SUREYAPRAGAASH09/Unsorted-Array-Exercises | /15.Compare_Two_Array_Elements/Compare_Two_Array_Elements.py | 897 | 4.03125 | 4 | Question :
==========
15. Write a function that takes two unsorted integer arrays as input and returns True if the two arrays are the same.
Input :
=======
Unsorted Array Elements
Output :
========
If two array element is same set flag to Ture other than set flag to False
import FindLenght
def compareTwoA... |
bb85ec71af250b60da660912d472014048c2ea23 | Dragonriser/DSA_Practice | /Binary Search/SearchInsertPosition.py | 699 | 4.03125 | 4 | """
QUESTION:
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5
Output: 2
"""
#CODE:
class Solution:
def searchInsert(self, nums: List[... |
cb30e9b071e1eb020f7a89f7eefe24123a22fb4e | Montemayor008/PYTHON | /4 Distance between 2 points pt2.py | 234 | 3.671875 | 4 |
print ("Inserte 2 valores para X y 2 valores para Y")
xVarX1 = int(input())
xVarX2 = int(input())
xVarY1 = int(input())
xVarY2 = int(input())
distancia = ((((xVarY2-xVarY1)**2)+((xVarX2-xVarX1)**2))**.5)
print(distancia) |
9bb3d9d3c83183400d014e5c0635cf9da2aa87a5 | AndrewSpeed/advent-of-code-2019 | /advent_of_code/day_2/part_2/solution.py | 1,817 | 3.625 | 4 | from pathlib import Path
from enum import Enum
RELATIVE_INPUT_FILE_PATH = "data/input.txt"
class OpCode(Enum):
ADD = 1
MULTIPLY = 2
HALT_EXECUTION = 99
def file_contents(file_path):
with open(file_path, "r+") as file:
return file.read()
def item_for(instruction_pointer, program):
retu... |
e930f252732afc9896bb1e757a002b410e65973b | momohouqi/ml | /demos/mnist_fullconnect_keras.py | 861 | 3.6875 | 4 | import tensorflow as tf # 深度学习库,Tensor 就是多维数组
def train(epoch_num):
# build a model
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28, 28)))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))
model.compile(optimizer='adam', loss='sparse_categorical_... |
660cb9b3d338520dc16b5cb4778f68c692fe8750 | AvantikaJalote/Techcider_Code_365 | /DAY_2_.PY | 637 | 3.890625 | 4 | """
Day 2 -
A floor has a center wooden section of size ‘n×m’, that has to be covered with carpet.
The carpet has to be stitched using square pieces of cloth of length ‘a’.
Find the minimum number of cloths that must be stitched together to cover the wooden section.
The carpet may cover an additional area outs... |
7dbbbf56e6f5f88f2505ad048b10a3a118c6c574 | gadamsetty-lohith-kumar/skillrack | /Unit Matrix Count 28-10-2018 .py | 1,176 | 3.984375 | 4 | '''
Unit Matrix Count
An N*N matrix containing 1s and 0s is given as the input to the program. The program must print the number of 2x2 unit matrices in the given matrix.
A matrix is said to be unit matrix if all the integers are 1. Also, consider the overlapping matrices.
Boundary Condition(s):
1 <= N <= 100
... |
ad8a81613a34b6af4385f27256ab69b5867eecf9 | prince21298/Basic-python | /mr.py | 3,397 | 3.828125 | 4 | # for i in range(1001):
# if i%3==0:
# print i,"nav"
# if i%7==0:
# print i,"gurukul"
# if i%21==0:
# print i,"navgurukul"
# user1= input("number of student")
# user2=input("ek student ka kharcha")
# a=user1*user2
# if a<=50000:
# print a, "hum budget ke andar hai"
# else:
# print a, "hum budget se bahar ... |
2c9a159b19804870f280d90153e3cc166c654445 | ww-tech/primrose | /primrose/transformers/filter.py | 3,051 | 3.703125 | 4 | """Transform data by filtering in data using filtering operations
Author(s):
Michael Skarlinski (michael.skarlinski@weightwatchers.com)
Carl Anderson (carl.anderson@weightwatchers.com)
"""
import operator
import logging
import numpy as np
import pandas as pd
from primrose.base.transformer import AbstractTr... |
e91cb4bf3b6db714aa1327a21ec7f43a6e42e86d | tcoln/Python-Leetcode | /151.翻转字符串里的单词.py | 662 | 3.65625 | 4 | class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
:note:
利用栈压入每个单词
"""
if not s:
return ''
#s = " hello world! "
l = len(s)
word = ''
stack = []
for c in s:
if ... |
d0050a28ba14d8e9dec9bc21a6b2fc77c8d9c09f | connvoi/leetcode | /g/arrayandstrings/jumpgame.py | 887 | 3.5625 | 4 | #https://leetcode.com/explore/interview/card/google/59/array-and-strings/3053/
class Solution:
def canJump(self, nums: list):
l = len(nums)
i,maximum = 0 , 0
#iを一つずつ勧めていく。それがmaxと同じ値になったら終わり
#iを1ずつすすめるのは最小の移動単位が1だから。
#隣にうつって、となりのvalue[i] + iと、numsの長さが同じだったらtrueを返す
#... |
61c1b7a3fbae3518b69b837a25df15be62eca4da | YisusSuperstar/ProbaGit | /InicialesMayus.py | 1,006 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#Morse
print "Introduzca un texto"
Txt=raw_input()
for i in range(len(Txt)):
if Txt[i]=="a":
print "·-",
if Txt[i]=="b":
print "-···",
if Txt[i]=="c":
print "-·-·",
if Txt[i]=="d":
print "-··",
if Txt[i]=="e":
print "·",
if Txt[i]=="f":
print "··-·",
if T... |
425c34623c343fbe35620bf38fa5fc934bfe90ab | matejm/project-euler | /problem102.py | 1,025 | 3.546875 | 4 |
def contains_center(A, B, C):
A, B, C = sorted((A, B, C))
if A[0] > 0:
return False
try:
k_ab = (B[1] - A[1]) / (B[0] - A[0])
except ZeroDivisionError:
# vertical line
k_ab = (B[1] - A[1]) * 1e19
try:
k_ac = (C[1] - A[1]) / (C[0] - A[0])
except ZeroDivisionError:
k_ab = (C[1] - A[1]) * 1e19
k_ao ... |
0526d7e87c6252c980f175f67b27b2e35ade3775 | Harmandhindsa19/python | /class9/3_assignment.py | 577 | 3.90625 | 4 | class temperature:
def __init__(self, fahrenheit, celsius):
self.fahrenheit=fahrenheit
self.celsius=celsius
def fahren(self):
self.fahreneit=1.8*self.celsius+32
print("enter the value of temperature in celius:", self.fahrenheit)
def cel(self):
self.celsius = self.fa... |
f83d6a3c121469f8e7f438aa789b70dbb37534b2 | Richie010/uplift-python-resources | /List Problems/find-average-of-a-list.py | 367 | 4.03125 | 4 | ourList = [4, 5, 1, 2, 9, 7, 10, 8]
count = 0
for i in ourList:
count += i
sumOfList = sum(ourList)
# We can do this by either the sum function that takes the list as the argument and also we can do this by the count that we created using the for loop over our list
avg = sumOfList / len(ourList)
print("Sum = {}".fo... |
44810a3c685580563874a5879a5186bfebd07e1c | Tigge/advent-of-code-2020 | /day6.py | 444 | 3.609375 | 4 | import functools
import operator
def parse(f):
return [[set(g2) for g2 in g1.split("\n")] for g1 in f.read().strip().split("\n\n")]
with open("day6.txt", "r", encoding="utf-8") as f:
groups = list(parse(f))
p1 = (functools.reduce(operator.or_, group) for group in groups)
p2 = (functools.reduce(oper... |
066f91dd8ea09aec5c14186c029c1aefe84edac3 | candrajulius/Phyton | /KontrolPerulangan/KontrolPerulangan.py | 3,349 | 3.84375 | 4 |
# Penggunaan break pada phyton
import sys
for letter in 'pyhton':
if letter == 'h':
break
print("Current letter {}".format(letter))
print("\n")
# Contoh 2 dari break
var = 10
while var > 0:
print("Current variabel {}".format(var))
var = var - 1
if var == 5:
break
# Continue
for... |
b56aadf481681d4ca69854217a239e241ba6b474 | nitinaggarwal1986/learnpythonthehardway | /ex16c.py | 1,206 | 4.75 | 5 | # To use the argv command to take the filename as the argument.
from sys import argv
# Taking filename as a parameter passed to the python script.
script, filename = argv
# To check with user if they want to overwrite the file mentioned.
print "We're going to erase %r." % filename
print "If you don't want that, hit C... |
11687c1cd850e63f724ea20bc61e7891af99df24 | JanPoonthong/pong | /pong.py | 3,362 | 4.03125 | 4 | import turtle
# Create a screen position and color
wn = turtle.Screen()
wn.title("Pong")
wn.bgcolor("Black")
wn.setup(width=800, height=600)
wn.tracer(0)
# Score
score_a = 0
score_b = 0
# Paddle A
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.shapesize(stretch... |
4ef09fc808b0e7b64a818d3c11dcdf422d258f27 | MingYuanTina/Resource | /code_challenge/1PythonLib/Problems/Problem13.py | 1,323 | 3.65625 | 4 | # REFERENCE
# 252. Meeting Rooms
# https://leetcode.com/problems/shortest-word-distance/description/
# DESCRIPTION
# Given an array of meeting time intervals consisting of start
# and end times [[s1,e1],[s2,e2],...] (si < ei),
# determine if a person could attend all meetings.
# EXAMPLE
# Input: [[0,30],[5,... |
bface0ee8325adbf0f721149b28bdf740738cb3b | Vaibhhav7860/yt-codehelp-python | /Lectures/Lecture 2/CircleArea.py | 102 | 4.03125 | 4 | print("Enter circle radius :")
r = int(input())
area = 3.14 * r * r
print("The area is: ")
print(area) |
b798048bf93f62b54974788f02be1a1d9227d38e | nandinimurthy/datadrivenastronomy | /meanof1Darray.py | 855 | 3.9375 | 4 | import numpy as np
# Function to calculate mean and median without using statistics module
# Input: CSV file
# Output: Mean and Median of data stored in CSV file
def calc_stats(file):
data = []
for line in open(file, 'r'):
data.append(line.strip().split(','))
data = np.asarray(data, float)
total = 0
values = []
r... |
0fe7f4e5c92f067eaf1304cd9cab6927fe7abcc3 | milen-g-georgiev/Python-101 | /task02.py | 795 | 3.75 | 4 | # Build a start list and an end list
def build(numbers):
a = []
b = []
length = len(numbers)
a.append(numbers[0])
for i in range(1,length):
if numbers[i] - numbers[i-1] > 1:
a.append(numbers[i])
b.append(numbers[i-1])
b.append(numbers[length-1])
return a, b
# Input data into list
de... |
1f6b03042c3ae0658784925622ed29de03c2a4cb | jcpc17/python | /exercicio-10.py | 265 | 3.859375 | 4 | #CRIE UM PROGRAMA QUE LEIA QUANTO DINHEIRO A PESSOA TEM NA CARTEIRA E MOSTRE QUANTOS DOLARES ELA PODE COMPRAR
real = float(input('Informe quantos reais você tem na carteira: '))
dolar = (real / 5.29)
print('Você pode comprar {:.2f} dólares'.format(dolar)) |
e60f472c00065bbcc9afbf15701ada82c9ff1c4b | aJanefish/Work | /Python/MyPythonTest/zy/com/test/Test007.py | 213 | 3.828125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
题目:将一个列表的数据复制到另一个列表中。
"""
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print a
b = a
print b
c = a[:]
print b
a.reverse()
print a
|
ebb0666aa0c3235d2bdd607902777866f5c1146d | varsha3003/Calculator-using-GUI | /calculator.py | 3,528 | 3.65625 | 4 |
from Tkinter import *
def butclick(numbers):
global operator
operator=operator + str(numbers)
text_Input.set(operator)
def cleardisplay():
global operator
operator=""
text_Input.set("")
def equals():
global operator
sumup=str(eval(operator))
... |
b09d8367bdaad17e3125e5f79227724e3a4dd220 | ashishiit/workspace | /LovePython/FactorialRecursionFormat.py | 205 | 3.890625 | 4 | '''
Created on Oct 28, 2016
@author: s528358
'''
def Factorial(num):
if num == 0:
return 1
else:
result = num * Factorial(num-1)
return result
print('result = %d'%Factorial(4)) |
49062cb4a93a00caf2a687e2a90c025d5c158b38 | suxian06/leetcode | /75.SortColors.py | 1,174 | 3.734375 | 4 | # Runtime: 32 ms, faster than 85.34% of Python3 online submissions for Sort Colors.
# Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Sort Colors.
# two pass
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place ins... |
b27d6294e282c3f3ba27d120de664903a5feb1d9 | lopz82/exercism-python | /isbn-verifier/isbn_verifier.py | 292 | 3.5 | 4 | import re
def is_valid(isbn: str) -> bool:
isbn = isbn.replace("-", "")
if not re.match(r"^\d{9}(\d|X)$", isbn):
return False
clean = [int(char) if char.isdigit() else 10 for char in isbn]
return sum(int(value) * (10 - i) for i, value in enumerate(clean)) % 11 == 0
|
c24dc1c703583614e4fecf98d94f2b8eaf54d054 | alvaroaguirre/Project_Euler | /Problems_1_to_10/problem_2.py | 485 | 3.765625 | 4 | # Problem 2
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valu... |
7474d4a7fd0391cfc803d685059fab7f8918753f | lixiang007666/Algorithm_LanQiao | /Base/dict_base.py | 183 | 3.625 | 4 | list1=[1,2,2,2,3]
d={}
for i in list1:
d[i]=d.get(i,0)+1
print(d)
print(d.items())
print(d.keys())
print(d.values())
d=sorted(d.items(),key=lambda x:x[1],reverse=True)
print(d)
|
beb50ceafd059997ab71d807ec66cb6864285e0e | medlum/python-helpers | /rename-files/helper_rename_file.py | 1,223 | 4.34375 | 4 | import os
import re
from os import path
def convert_name(textfile, extension):
''' This function replace whitespace with underscore and add a file extension.
It takes 2 arguments:
1. A .txt file which consists of student names to be in 1 column with n rows.
2. Extension argument for the file type... |
a49695cefb0d9c9b51a58264b66ac17b2c859e32 | Bawya1098/Hackerrank | /hackerrank/hackerrank/day_test_2/sherlock.py | 287 | 3.65625 | 4 | from collections import Counter
s = 'aabbccdde'
dict = {}
for element in s:
if element not in dict:
dict[element] = 1
else:
dict[element] += 1
print(dict)
values = dict.values()
list = []
for val in values:
list.append(val)
print(list)
print(Counter(list))
|
02b151d92634f9f2ea4364b2ca88bd5486521ed7 | ccsreenidhin/100_Python_Problems | /Learning_Python_100_problems/python5.py | 958 | 3.953125 | 4 | ###############################################################################################################
###################################################SREENIDHIN C C##############################################
################################################################################################... |
8b4104bc5d0ece89344062007cd41f575c904064 | jesusdelatorre30/repetitivas-python | /ejercicio_17.py | 832 | 4 | 4 | trabajadores = int(input("¿Cuántos trabajadores tiene la empresa?:"))
sueldo_por_hora = float(input("Introduzca el sueldo por hora:"))
horas_acum = 0
for trabajador in range(1, trabajadores + 1): #desde el primer trabajador hasta el ultimo
horas_por_trabajador = 0
dias = int(input("¿Cuántos días ha trabajado el ... |
86aa02de38dc3d321c0b4046f014d4a6d72296c8 | arip995/project-euler | /q7.py | 281 | 3.90625 | 4 | def isPrime(n):
for i in range(3, int(n**0.5) + 1,2):
if n % i == 0:
return False
return True
def prime(n):
x = 0
prime = 1
while x < n:
prime += 2
if isPrime(prime):
x += 1
return prime
print(prime(10000))
|
aad1c8ea138ccd3e294b3e8690e43b8bfedf9013 | psycho-pomp/DSA-Workshop | /Week2/Mathematics/Learn/HcfLcm.py | 130 | 3.625 | 4 | # Abhishek Anand
# GCD & LCM
a,b=map(int,input().split())
mul=a*b
while b:
a,b=b,a%b
gcd=a
lcm=(mul//gcd)
print(gcd,lcm)
|
72fac1208abecbc3d7e1aa1ea8f0e66d37e07351 | z0t0b/ISMN6656 | /Homework/HW3/HW3Q1.py | 612 | 4.1875 | 4 | # P3.23
# gets user input for income amount for the year
income = float(input("Please enter your income for the year: $"))
# assigns tax value based on income range
if(income <= 50000):
tax = 0.01
elif(50000 < income <= 75000):
tax = 0.02
elif(75000 < income <= 100000):
tax = 0.03
elif(100000 < i... |
69f15580fc124d5044be50742b22c00cd1174577 | null-p01ntr/CanIGoOut | /main.py | 885 | 3.890625 | 4 | import datetime
import sys
age = int(input("Yaşınızı girin: "))
time = datetime.datetime.now()
hour = time.hour
day = time.weekday()
if(day>4): #haftasonu
if(hour >= 10 and hour < 20):
if(age > 20 and age < 65):
print("maskeni tak, çık")
sys.exit()
elif(age >= 65 and hour < 13):
print("maskeni tak, çık"... |
4220d8213b36310aa2c0f6ad9430fc76024ee7fc | Marvinmw/GraphGallery | /graphgallery/utils/misc.py | 983 | 3.71875 | 4 | import six
__all__ = ["merge_as_list", "ask_to_proceed_with_overwrite"]
def merge_as_list(*args):
out = []
for x in args:
if x is not None:
if isinstance(x, (list, tuple)):
out += x
else:
out += [x]
return out
def ask_to_proceed_with_overwr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.