blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
17114bad9e3fb2b740dec21c6f3effe3aa5f6cae | meetnshah/leetcode | /longestSubarraySum.py | 1,484 | 3.953125 | 4 | # Problem Statement#
# Given an array of positive numbers and a positive number ‘S,’ find the length of the smallest contiguous subarray whose sum is greater than or equal to ‘S’. Return 0 if no such subarray exists.
# Example 1:
# Input: [2, 1, 5, 2, 3, 2], S=7
# Output: 2
# Explanation: The smallest subarra... |
a771ac206c6dbdf8fd081b3488e36d3602fb8e0f | meetnshah/leetcode | /FruitsIntoBasket.py | 784 | 3.625 | 4 | def fruitsIntoBasket(arr):
windowStart = 0
count = {}
maxCount = 0
for windowEnd in range(len(arr)): # get count of all occurrences of an element in the dictionairy
rightIdx = arr[windowEnd]
if rightIdx not in count:
count[rightIdx] = 0
count[rightIdx] ... |
918d1fa1339dc23a784941fe105cf274ad55c98d | Python-and-Bourbon/Advent-of-code-2019 | /day-01/pt-2/script.py | 304 | 3.53125 | 4 | import sys
def fuel_req(mass): return (mass // 3) - 2
total = 0
with open(sys.path[0]+'\\'+'input.txt', 'r') as masses:
for mass in masses.readlines():
iter = fuel_req(int(mass.rstrip('\n')))
while iter > 0:
total += iter
iter = fuel_req(iter)
print(total) |
dfaea68c6693f63cce8638bb978077536a7dcecc | medetkhanzhaniya/Python | /w3/set.py | 2,461 | 4.71875 | 5 | """
#CREATE A SET:
thisset={"a","b","c"}
print(thisset)
ONCE A SET CREATED
YOU CANNOT CHANGE ITS ITEMS
BUT YOU CAN ADD NEW ITEMS
#SETS CANNOT HAVE 2 ITEMS WITH SAME VALUE
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
#out:true
thisset = {"apple", "banana", "cherry"}
thisse... |
98d4d13194cdb40bf043c48d297f97b59726064d | medetkhanzhaniya/Python | /leetcode/lc5.py | 217 | 3.9375 | 4 | #Given an integer number n, return the difference between the product of its digits and the sum of its digits
a=int(input())
sum=0
product=1
while a :
n=a%10
product*=n
sum+=n
a//=10
print(product-sum) |
866ba43a50f36844e30c8952a5064524a6f5d998 | santoshselvarajr/Facial_Recognition_Using_Cascade | /faceRecognition.py | 2,475 | 3.65625 | 4 | #Working in the virtual_platform
#Required libraries are installed in the virtual platform
#Importing libraries
import cv2
import os
#Set the working directory
os.chdir("C:\\Users\\Santosh Selvaraj\\Documents\\Working Directory\\Computer_Vision_A_Z_Template_Folder\\Module 1 - Face Recognition")
#Loading the cascades... |
5c34a7a0e8a29914a6ffe44a27af786054497419 | Ayushi-07/FSDP_2019 | /DAY01/restart.py | 246 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 3 21:11:23 2019
@author: Ayushi Agrawal
"""
#RESTART
str = "RESTART"
str1 = str[ :5]
str2 = str[6:]
print(str1 + "$" + str2)
str.replace("R" , "$")
#RESTART
str = "RESTART"
print(str[:5] + '$' + str[6]) |
b17cb584cf6c78c34f6e1c7b78670fb90a9b58dd | manumuc/python | /rock-paper-scissors-lizard-spock.py | 1,905 | 4.28125 | 4 | <pre>[cc escaped="true" lang="python"]
# source: https://www.unixmen.com/rock-paper-scissors-lizard-spock-python/
#Include 'randrange' function (instead of the whole 'random' module
from random import randrange
# Setup a dictionary data structure (working with pairs efficientlyconverter = ['rock':0,'Spock':1,'pa... |
fb8a10f89fc38052190a480da6eeeacf88d6dd22 | govind-mukundan/playground | /python/class.py | 2,379 | 4.28125 | 4 | # Demo class to illustrate the syntax of a python class
# Illustrates inheritance, getters/setters, private and public properties
class MyParent1:
def __init__(self):
print ("Hello from " + str(self.__class__.__name__))
class MyParent2:
pass
# Inheriting from object is necessary for @property etc to wor... |
2aee376565cc251ac116183a0deee21ad98346bc | IvanCheresky/Economics | /futuredata.py | 17,833 | 3.65625 | 4 | import math
import pandas
import multipledispatch
import random
# global variables
period = 0
# create a dataframe with the data created
def custom_df(info):
df = pandas.DataFrame(info, columns=list(data.keys()))
# print(df)
# data = {"indice_tiempo": ["2020-12-01", "2021-01-01"],
# "tipo_c... |
3840ad226aa5e02c33f396b9bd5baec10c02748a | david822mex/python-snake | /list comprehension.py | 1,069 | 3.90625 | 4 | import random
import pandas
old_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
old_dict = {"Name": "David", "Age": 30, "Sex": "M"}
# 1.create a new list from old_list
new_list = [each * 2 for each in old_list]
print(new_list)
# 2. apply a condition with if statement
new_list2 = [each * 2 for each in old_list if each > 5 & e... |
af26bb168affb2e4cc2b72b95ab0edd6c580a109 | czoekim/searching | /Anagrams.py | 669 | 3.96875 | 4 | # Anagrams
# CZK, CMS430
f= open('words.txt')
d = {}
for word in f:
#Takes all words in file and sorts them in alphabetical order
word = word.strip()
word_list = [] #value for dict
sorted_word = tuple(sorted(word)) #key for dict
#Checks if sorted word is already a key in dict
#If s... |
f7772b3d245042ce2e58f514825a857bf6ecb034 | bhoomi51/python-code | /button_click.py | 535 | 4.09375 | 4 | from tkinter import *
# create root window
root = Tk()
# root window title and dimension
root.title("Tkinter")
root.geometry('350x200')
# adding a label to the root window
lbl = Label(root, text="Are you a Geek?")
lbl.grid()
# function to display text when
# button is clicked
def clicked():
lb... |
d4d0f0f542cea125d1baa9b4fc79553eae81a561 | bhoomi51/python-code | /read demo 3.py | 409 | 3.734375 | 4 | file1 = open(r"C:\Users\sony\Desktop\hello.txt","r+")
print("Output of Read function is ")
print(file1.read())
print()
# seek(n) takes the file handle to the nth
# bite from the beginning.
file1.seek(0)
print("Output of Readline function is ")
print(file1.readline())
print()
file1.seek(0)
# readlin... |
e95ff98d41b9202f31fc714dbfe0022029ab96c6 | codingpurush/class11python | /armstrong_till_N.py | 234 | 3.765625 | 4 | total=0
x=int(input())
for i in range(1,x+1):
sum=0
temp=i
while i>0:
r=i%10
cube=r**3
sum+=cube
i=i//10
if sum==temp:
print(temp)
total=total+temp
print("sum=", total)
|
5d19615aad9686f453fc9c04fc19af3aa35a72dd | jag/PopulationPyramid.net | /CSVParser.py | 2,197 | 3.640625 | 4 | import csv
def parse(country):
reader = csv.reader(open('data/'+country+'.csv', 'rU'), delimiter=',')
dict ={}
ages = set([])
years = set([])
years_totals= {}
for row in reader :
if len(row)>0 and not row[0].startswith("Source") and not row[0].startswith(" ") and not row[0].startswit... |
f18e425af18abe856c8b7b18a1fc38b3e0b3f043 | PascalHelbig/regeln | /create_csv.py | 874 | 3.75 | 4 | """
This module creates a csv file for Anki import
"""
LEVELS = [
{"char": 'l', "nums": 64, "tag": "leicht"},
{"char": 'm', "nums": 86, "tag": "mittel"},
{"char": 's', "nums": 84, "tag": "schwer"}
]
URL = "http://game.finckh.net/situat/alle.htm"
FILE_NAME = "finckh.csv"
def create_link(level_char, number)... |
bf60116ff0ea8e2a8d5c5a50b19ae457ddcf0bdf | GastonPaez/PY-Apps | /players_shuffle/players_shuffle.py | 2,505 | 3.625 | 4 | from tkinter import Label, Button, Listbox, Tk, Frame, Entry, ANCHOR, END, RIGHT, LEFT
from random import shuffle
root = Tk()
root.title("Shuffle Teams")
lb1 = Label(root, text="Shuffle Teams")
lb1.pack(pady=10)
lb2 = Label(root, text="Add Players: ")
lb2.pack()
# List of players to be added
players_list = []
def... |
c51e87b3ed25ae3a58dcbf6ae0e3d91c248e7690 | vinhnh1905/pythonProject | /Distance Traveled.py | 115 | 3.953125 | 4 | h = float(input("Input the time that the car will travel: "))
d = h*70
print("Time: %s Distance: %s miles" % (h,d)) |
16f485791f71fff3e2616846af53a484f57e130d | JouniKiiskila/OhjelmointiTA2 | /muunnos.py | 270 | 3.734375 | 4 | syntymavuosi_str = input("Minä vuonna olet syntynyt? ")
# muutetaan kokonaisluvuksi
syntymavuosi = int(syntymavuosi_str)
ika = 2021 - syntymavuosi
print('täytät tätnä vuonna', ika, 'vuotta')
luku = 313
numerosarja = str(luku)
print('numerosarjassa', luku, 'on') |
888e34889ab8cea5212562986f0758372fffe658 | lordzil/cartesian | /cartesian-generator.py | 2,683 | 4.09375 | 4 | import numpy as np
import random
size = int(input()) #array size defined by user input
content = ['x','.'] #to be randomized accross the array
matrix = np.zeros((size,size), dtype = object) #create a defined array, fill with 0
flag = 0 #loop breaker
#===========================
# randomizing and checking... |
17cc753a32a80d4443db320d85c9d1257d32a7ce | jackwener/leetcode | /34.在排序数组中查找元素的第一个和最后一个位置.py | 1,714 | 3.875 | 4 | #
# @lc app=leetcode.cn id=34 lang=python3
#
# [34] 在排序数组中查找元素的第一个和最后一个位置
#
# https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/
#
# algorithms
# Medium (38.25%)
# Likes: 290
# Dislikes: 0
# Total Accepted: 56.4K
# Total Submissions: 145.9K
# Testcase Example: '... |
446f38b441d1901ce9ba42677b581d49b6553dab | jackwener/leetcode | /199.二叉树的右视图.py | 663 | 3.578125 | 4 | #
# @lc app=leetcode.cn id=199 lang=python3
#
# [199] 二叉树的右视图
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.res = []
def right... |
793d2ca14547bf23a4f24508804f6bf4bcd2a327 | jackwener/leetcode | /326.3-的幂.py | 882 | 3.703125 | 4 | #
# @lc app=leetcode.cn id=326 lang=python3
#
# [326] 3的幂
#
# https://leetcode-cn.com/problems/power-of-three/description/
#
# algorithms
# Easy (45.57%)
# Likes: 82
# Dislikes: 0
# Total Accepted: 32K
# Total Submissions: 69.7K
# Testcase Example: '27'
#
# 给定一个整数,写一个函数来判断它是否是 3 的幂次方。
#
# 示例 1:
#
# 输入: 27
# 输出... |
e65db147b77d0ec9b539de49b90e6311f311c681 | jackwener/leetcode | /415.字符串相加.py | 1,197 | 3.5 | 4 | #
# @lc app=leetcode.cn id=415 lang=python3
#
# [415] 字符串相加
#
# https://leetcode-cn.com/problems/add-strings/description/
#
# algorithms
# Easy (48.51%)
# Likes: 126
# Dislikes: 0
# Total Accepted: 21.7K
# Total Submissions: 44.3K
# Testcase Example: '"0"\n"0"'
#
# 给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
#
# 注意:
#
... |
f01f965c80771103b8d91dbceb4eeec48b88bee4 | jackwener/leetcode | /66.加一.py | 1,136 | 3.578125 | 4 | #
# @lc app=leetcode.cn id=66 lang=python3
#
# [66] 加一
#
# https://leetcode-cn.com/problems/plus-one/description/
#
# algorithms
# Easy (42.07%)
# Likes: 395
# Dislikes: 0
# Total Accepted: 104.6K
# Total Submissions: 247.5K
# Testcase Example: '[1,2,3]'
#
# 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
#
# 最高位数字存放在数组的首位, ... |
8032f1fdcddb2f0b702f0512214b89d0f9d8f9d1 | jackwener/leetcode | /42.接雨水.py | 2,167 | 3.5 | 4 | #
# @lc app=leetcode.cn id=42 lang=python3
#
# [42] 接雨水
#
# https://leetcode-cn.com/problems/trapping-rain-water/description/
#
# algorithms
# Hard (47.39%)
# Likes: 746
# Dislikes: 0
# Total Accepted: 42.9K
# Total Submissions: 90.2K
# Testcase Example: '[0,1,0,2,1,0,1,3,2,1,2,1]'
#
# 给定 n 个非负整数表示每个宽度为 1 的柱子的高度... |
0777b589338d704ed323a2ba0e501e43aaf41db4 | jackwener/leetcode | /43.字符串相乘.py | 1,664 | 3.609375 | 4 | #
# @lc app=leetcode.cn id=43 lang=python3
#
# [43] 字符串相乘
#
# https://leetcode-cn.com/problems/multiply-strings/description/
#
# algorithms
# Medium (40.96%)
# Likes: 256
# Dislikes: 0
# Total Accepted: 40.5K
# Total Submissions: 97.9K
# Testcase Example: '"2"\n"3"'
#
# 给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 nu... |
b0cfb0f7b8036e2daa763f0afdc10ebc0a536fc3 | kiranyaN/Demo | /dayscount.py | 1,032 | 3.984375 | 4 | from datetime import *
from tkinter import *
def disp():
year1 = int(e1.get())#int(input('Enter year '))
month1 = int(e2.get())#int(input('Enter month '))
day1 = int(e3.get())#int(input('Enter day '))
d1 = date.today() - date(year1, month1, day1)
msg.set(d1)
print(d1)
r... |
e084df60335948f9232fa0689b2bfa8fb3ef6b75 | dnpfefferle/python-challenge | /PyBank/PBmaincode.py | 2,040 | 3.84375 | 4 | import os
import csv
budgetPath = ("budget_data.csv")
months = []
pAndL = []
thisMonthRev = 0
lastMonthRev = 0
rev_change = 0
revChanges = []
with open(budgetPath, newline="", encoding="utf-8") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
header = next(csvreader)
for row in csvre... |
54c454bf32e27a1f48f7c7a1ea29c479dafa8568 | hackerpup/CoinProject | /main.py | 880 | 3.796875 | 4 | print("Change Calclator")
quarter = 25
dime = 10
nickel = 5
penny = 1
moneygiven = input("Enter how much money given: ")
citem = input("How much did the item cost?: ")
#Write your code here to give exact number of quarters (qmb) and dimes (dmb) and nickels (nmb) and pennies (pnb)
#based on the difference between ci... |
7bcfe32cd192f71f03375682f67c5a6c2c489f2d | gerrymandr/spanning_trees | /fan_chung_bound.py | 1,009 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 12 00:24:22 2018
@author: MGGG
"""
import numpy as np
alpha = .2200507
beta = .44068679
def left_side(area, perimeter):
first_term = - 1* np.log(area)
second_term = (area - 1) * np.log( 4 * np.exp(-1 * alpha))
third_term = (-1 * beta * perimeter* ( 1 - 1 / ... |
9a60dccb3e47a47be7de209e91cd768d089b201a | ruanmarcoss/TrabalhosPython | /16-Aula16/aula16.py | 429 | 3.640625 | 4 | # Aula 16 29-11-2019
# ????????
#cadastro de playlist
#lendo musica, artista e album
from faixa import criar_faixa,salvar_faixa,ler_faixa
musica = input('digite a música: ')
album = input('digite o album: ')
artista = input('digite o artista: ')
faixa = criar_faixa(musica,album,artista)
salvar_faixa(faixa)
lista ... |
9ef6acffbc3909f2662328af0c5ec18050086e78 | ruanmarcoss/TrabalhosPython | /19-Aula19/exercicio1.py | 1,573 | 3.84375 | 4 | # Aula 19 - 04-12-2019
# Lista com for e metodos
# 1 - Com a seguinte lista imprima na tela (usando a indexação e f-string)
cadastroHBSIS = ['nome', ['Alex' ,'Paulo' ,'Pedro' ,'Mateus' ,'Carlos' ,'João' ,'Joaquim'],
'telefone',['4799991','4799992','4799993','4799994','4799995','4799996','4799... |
7af3f969552d12c31e4cc5a8d9bca6ccfba9f06a | ruanmarcoss/TrabalhosPython | /18-Aula18/exercicio4.py | 2,466 | 3.875 | 4 | # Aula 18 - 03-11-2019
# interação de lista com o for
# Usando o comando for vamos fazer uma interação de varialvel tipo coleção. A interação é (simplificadamente)
# percorer toda a variavel e isolar seu valores.
# 1.1 Com a seguinte lista, use o for para interar esta tupla e apresentar (usando o f-string) O nome ... |
604a6f75e53b4b4db25fec4f00a77f6897d95015 | jglezt/game-of-pyfe | /game_of_pyfe/tests/test_utils.py | 2,185 | 3.546875 | 4 | """
Test suit for utils.py file.
"""
import math
import numpy as np
from ..utils import create_printable_board, validate_board
from .base_test import BaseTestCase, unittest
class TestValidateBoard(BaseTestCase):
"""
Tests for the validate_board function.
"""
def test_board_shape(self):
"""T... |
d5a0dc36ace43a6fe0427e3196ee404f4f0443b0 | Dimonium-239/tunnel-evacuation-simulation | /tunnel.py | 14,400 | 3.53125 | 4 | import pygame as pg
import colors as c
from settings import *
import math
import random
class Tunnel(pg.sprite.Sprite):
"""
A class used to represent routes of tunnel
...
Attributes
----------
tunnel_group :
group which contain routes, lines
exit_group :
group which cont... |
b4163210b6b2bf19882ef26e023cc4facd7c01cd | extrajp2014/Sorting | /src/recursive_sorting/recursive_sorting.py | 1,501 | 3.890625 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge( arrA, arrB ):
elements = len( arrA ) + len( arrB )
merged_arr = [0] * elements
# TO-DO
idx_arrA = 0
idx_arrB = 0
for i in range(elements):
if len(arrA) == idx_arrA:
for j in range(idx_arrB, len(ar... |
86ad4a99e13b92164e849667178dfcff78da3200 | JacobPrudden/PRCO304 | /PlayGame.py | 23,256 | 3.609375 | 4 | '''
Created on 18 Feb 2018
@author: Jacob
'''
import MachineLearning as ml
import tkinter
import tensorflow as tf
import numpy as np
from tensorflow.python.framework import ops
import Functions
import time
from random import randint
import Training
global board
board = Functions.BoardInit()
player = 1
... |
c0e4b60e7bdac2719ee37a944fcc4add4bbb1264 | Jhang512/driving | /driving.py | 378 | 4.21875 | 4 | country = input('What is your nationality: ')
age = input('How old are you: ')
age = int(age)
if country == 'taiwan':
if age >= 18:
print('You can learn driving')
else:
print('You cannot learn driving')
elif country == 'usa':
if age >= 16:
print('You can learn driving')
else:
print('You cannot learn drivin... |
27e4294de35fe7d0abfbb927e87b8ff8c4e2ad46 | practice-more/matplotlib-practice | /graph/graph_style.py | 338 | 3.59375 | 4 | from matplotlib.pyplot import *
# 用例数据
x = [1,2,3,4]
y = [5,4,3,2]
# 创建新图表
figure()
# 坐标轴与大小自适应
autoscale()
# 可以设置线宽,线的样式,标记的样式,标志和图例
plot(x, y, linewidth=1.5, color=(0.5,0.5,1), label='plot', linestyle="-", marker='+')
legend(loc=3)
grid()
show()
|
a82c406eb8b18d9e5506a319a85ebcc5b3ed6d14 | wyrcode/mnist_cnn | /network/flatten.py | 946 | 3.515625 | 4 | # -*- coding: utf-8 -*-
##########################
# #
# @Author: KangKang #
# #
##########################
class Flatten:
def __init__(self, layer):
self.upper_layer = layer
self.num_input = layer.num_output
self.input_w = laye... |
d3b3a2f39945050d6dd423146c794965069ead21 | jdipietro235/DailyProgramming | /GameOfThrees-239.py | 1,521 | 4.34375 | 4 |
# 2017-05-17
# Task #1
# Challenge #239, published 2015-11-02
# Game of Threes
"""
https://www.reddit.com/r/dailyprogrammer/comments/3r7wxz/20151102_challenge_239_easy_a_game_of_threes/?utm_content=title&utm_medium=browse&utm_source=reddit&utm_name=dailyprogrammer
Back in middle school, I had a peculiar way of deali... |
64fd7c8d1bc14dd9c670cba81f555429fb7b558d | olutoni/pythonclass | /control_exercises/stages_of_life.py | 691 | 3.90625 | 4 | try_again = True
while try_again:
age = int(input("How old are you?: "))
if age < 2:
print(f"You are {age} year old and you are a baby")
elif age < 4:
print(f"You are {age} years old and you are a toddler")
elif age < 13:
print(f"You are {age} years old and you are a kid")
el... |
34c6462540a0125331db9eefb0108ee71624684d | olutoni/pythonclass | /list_exercises/tuple.py | 300 | 3.796875 | 4 | simple_foods = ("Rice", "Beans", "Yam", "Pasta", "Cereal")
for food in simple_foods:
print(food)
print(simple_foods[0])
# The statement below returs an error as they are immutable
#simple_foods[0] = "Plantain"
simple_foods = ("Plantain", "Beans", "Yam", "Pasta", "Cereal")
print(simple_foods)
|
330ba20a83c20ecb7df2e616379023f74631ee2c | olutoni/pythonclass | /control_exercises/km_to_miles_control.py | 351 | 4.40625 | 4 | distance_km = input("Enter distance in kilometers: ")
if distance_km.isnumeric():
distance_km = int(distance_km)
if distance_km < 1:
print("enter a positive distance")
else:
distance_miles = distance_km/0.6214
print(f"{distance_km}km is {distance_miles} miles")
else:
print("You... |
cd9a96097aefec724be41ca954d1407641c93795 | olutoni/pythonclass | /list_exercises/pizza.py | 415 | 3.8125 | 4 | my_pizza = ["Deluxe", "BBQ Chicken Feast", "Brooklyn"]
for pizza in my_pizza:
print(f"I like {pizza} pizza.\n")
print("I really love pizza!!!\n")
friend_pizza = my_pizza[:]
my_pizza.append("Pepperoni")
friend_pizza.append("meat lovers")
print(f"My favorite pizzas are:")
for pizza in my_pizza:
print(pizza)
... |
924d7324d970925b0f26804bc135ffd318128745 | olutoni/pythonclass | /recursion_exercise/recursion_prime_check.py | 332 | 4.21875 | 4 | # program to check if a number is a prime number using recursion
number = int(input("enter number: "))
def is_prime(num, i=2):
if num <= 2:
return True if number == 2 else False
if num % i == 0:
return False
if i * i > num:
return True
return is_prime(num, i+1)
print(is_pri... |
10c70c24825c0b8ce1e9d6ceb03bd152f3d2d0c1 | slohmes/sp16-wit-python-workshops | /session 3/2d_arrays.py | 1,149 | 4.21875 | 4 | '''
Sarah Lohmeier, 3/7/16
SESSION 3: Graphics and Animation
2D ARRAYS
'''
# helper function
def matrix_print(matrix):
print '['
for i in range(len(matrix)):
line = '['
for j in range(len(matrix[i])):
line = line + str(matrix[i][j]) + ', '
line += '],'
print line
... |
56ed9f2b27dc15dd6899dc320942569274f15742 | kruschk/etc | /Python/100_Doors.py | 1,064 | 3.59375 | 4 | import time
start = time.clock()
door_initial = [0 for x in range(100)] # 0 will indicate closed, 1 will indicate open
def toggle(list_in, incr):
# returns a list containing the opposite of whatever was in the list (0 or 1) for each increment.
i = incr - 1
while i < len(list_in):
if list_... |
930015be4f0e0261812a8d4199a30e937113db0b | Dhiraj55/Information_Security | /OES_IS_2021/Exp_5B-blockcipher.py | 426 | 3.859375 | 4 | import pyDes
import os
plaintext = input("Enter plaintext : ")
def padded_text(s):
while len(s)%8 !=0 :
s+=' '
return s
p = padded_text(plaintext)
k_ecb = pyDes.des("DESCRYPT",pyDes.ECB, "\0\0\0\0\0\0\0\0",pad=None,padmode=None)
e_ecb = k_ecb.encrypt(str.encode(p))
print("The Encrypted string (in ... |
07ffea7a0b3d7062bd1c8eb13b1c5730e913acdb | shirleyilenechan/coding-challenges | /has_cycle.py | 295 | 3.953125 | 4 | # Given a linked list, determine if it has a cycle in it.
def has_cycle(head):
ll_set = set()
current = head
while current:
if current not in ll_set:
ll_set.add(current)
current = current.next
else:
return True
return False
|
7a939415e227c67f6f403d9292496fc74fb785b7 | shirleyilenechan/coding-challenges | /print_ll.py | 143 | 3.578125 | 4 | def print_linked_list(head):
current = head
while current is not None:
print(current.data)
current = current.next
|
8c8565c96790802f486422b1307097df9882257a | gotikoko/github-demo | /closure.py | 276 | 4.0625 | 4 | # Python program to illustrate
# closures
def outerFunction(text):
text = text
def innerFunction():
print(text)
# Note we are returning function
# WITHOUT parenthesis
return innerFunction
if __name__ == '__main__':
myFunction = outerFunction('Hey!')
myFunction()
|
8aa48619ba0e0741d001f061041aa944c7ee6d05 | amysimmons/CFG-Python-Spring-2018 | /01/formatting.py | 471 | 4.28125 | 4 | # STRING FORMATTING
age = 22
like = "taylor swift".title()
name = "Amy"
print "My age is {} and I like {}".format(age, like)
print "My age is 22 and I like Taylor Swift"
print "My age is {1} and I like {0}".format(age, like)
print "My age is Taylor Swift and I like 22"
print "My name is {}, my age is {} and I like... |
298989764c2e60db0cc9388f7f1f2e7ee80080e6 | celier/leet | /easy/python/two_sum.py | 541 | 3.78125 | 4 | """
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
"""
class Solution:
def twoSum(self, nu... |
cc657881d1e3dae55ba14ca9091b12bd1de5e9ce | celier/leet | /easy/python/roman_to_integer.py | 426 | 3.8125 | 4 | """
Given a roman numeral, convert it to an integer.
"""
class Solution:
def romanToInt(self, s):
roman = {'M': 1000,'D': 500 ,'C': 100,'L': 50,'X': 10,'V': 5,'I': 1}
year = 0
for index in range(0, len(s) - 1):
if roman[s[index]] < roman[s[index+1]]:
year -= roma... |
8fcffddce0cdf94e63f4691c9ab55ee42217c96a | ahmedaliraza/AI-lab1 | /lab3-41.py | 155 | 3.65625 | 4 | string=input("input a string")
vowels={'a,e,i,o,u'}
d={'a':0,'e':0,'i':0,'o':0,'u':0}
for i in string:
if i in vowels:
d[i]+=1
print(d) |
307ddb8c2cc078964a872d7dfc4eeeee64a29aae | nitvishn/crypto | /randomCase.py | 303 | 3.734375 | 4 | import random
import os
string=input("String: ")
bannedChars=[]
while(True):
newString=""
for char in string:
if char in bannedChars:
continue
if(random.random()>0.5):
newString+=char.upper()
else:
newString+=char.lower()
print(newString)
string=input("String: ")
os.system('clear')
|
eb2818358c618ce84defc7decf64e3784f3c24ba | abhinashjain/codes | /codeforces/Table_Tennis_Game_2.py | 1,440 | 3.90625 | 4 | #!/usr/bin/python
# coding: utf-8
(k,a,b)=map(int,raw_input().split(' '))
awin=a/k
bwin=b/k
maxset=awin+bwin
if(maxset):
arem=a%k
brem=b%k
if(arem>0 and bwin==0):
print "-1"
else:
if(brem>0 and awin==0):
print "-1"
else:
print maxset
else:
print "-1"
... |
297a5886f75bde1bb4e8d1923401512848dcc53f | abhinashjain/codes | /codechef/Snakproc.py | 2,698 | 4.25 | 4 | #!/usr/bin/python
# coding: utf-8
r=int(raw_input())
for i in xrange(r):
l=int(raw_input())
str=raw_input()
ch=invalid=0
for j in str:
if((j=='T' and ch!=1) or (j=='H' and ch!=0)):
invalid=1
break
if(j=='H' and ch==0):
ch=1
if(j=='T' and ch==1... |
304e1ec73d319f99d095f1243d5a92eee2d8eec9 | abhinashjain/codes | /spoj/Crds.py | 736 | 3.609375 | 4 | #!/usr/bin/python
# coding: utf-8
t=int(raw_input())
for i in range(t):
n=int(raw_input())
ans=((n*(3*n+1))/2) % 1000007;
print ans
'''
Maricruz have a lot of cards, she always uses her cards to build pyramids as shown in Crds.jpg image:
A pyramid card of 3 leves.
She always wonder how many cards does she n... |
a1f38ed8affbe2372504d43f95fad224b8826761 | abhinashjain/codes | /codechef/Predict.py | 1,808 | 3.828125 | 4 | #!/usr/bin/python
# coding: utf-8
t=int(raw_input())
for i in range(t):
pa=float(raw_input())
pb=1-pa;
if(pa>=pb):
s=10000*pb;
else:
s=10000*pa;
s=(20000*pa*pb)+10000-s; # profit = 20000*pa*pb-(B*pa+A*pb); # (5880-4000)*0.51+(4080-6000)*0.49
print s
'''
Chef Datta likes betting in Indian Premier League... |
f4f150965659fe287e733ec2d7d5af903ccda3aa | abhinashjain/codes | /hackerrank/Zigzag_Array.py | 1,503 | 3.53125 | 4 | #!/usr/bin/python
# coding: utf-8
n=int(raw_input())
arr=map(int,raw_input().split(' '))
ans=0
for i in xrange(n-2):
if((arr[i]<arr[i+1] and arr[i+1]<arr[i+2]) or (arr[i]>arr[i+1] and arr[i+1]>arr[i+2])):
ans+=1
print ans
'''
We say an array of n distinct integers, A=[a0,a1,...,a(n-1)], is zigzag if no ... |
ab4b173f42a9b051a7aa6b6aca969b57314af5d7 | abhinashjain/codes | /spoj/Uj.py | 1,421 | 3.765625 | 4 | #!/usr/bin/python
# coding: utf-8
while(1):
(a,b)=raw_input().split()
a=int(a)
b=int(b)
if((a==0) & (b==0)):
break
print a**b
'''
Dear Uncle Jack is willing to give away some of his collectable CDs to his nephews. Among the titles you can find very rare albums of Hard Rock, Classical Music, Reggae and much mo... |
1a0fd0b2f79fd7f35ca82e93e5851c15d0b86a6c | abhinashjain/codes | /codechef/Palingam.py | 3,390 | 3.5625 | 4 | #!/usr/bin/python
# coding: utf-8
t=int(raw_input())
for i in xrange(t):
s=raw_input()
t=raw_input()
sarr=[0]*26
tarr=[0]*26
for j in s:
ind=ord(j)-97
sarr[ind]+=1
for j in t:
ind=ord(j)-97
tarr[ind]+=1
bwin=1
for j in xrange(26):
if(tarr[j]==0 an... |
8f97da7c54be77e69733bb92efae07666c0ab421 | Didden91/PythonCourse1 | /Week 13/P4_XMLinPython.py | 1,689 | 4.25 | 4 | #To use XML in Python we have to import a library called ElementTree
import xml.etree.ElementTree as ET #The as ET is a shortcut, very useful, makes calling it a lot simpler
data = '''
<person>
<name>Chuck</name>
<phone type="intl">
+1 734 303 4456
</phone>
<email hide="yes" />
</person>'''
tree = ET.from... |
69940b6c1626270cf73c0fe36c2819bbba1523bd | Didden91/PythonCourse1 | /Week 11/P5_GreedyMatching.py | 929 | 4.28125 | 4 | #WARNING: GREEDY MATCHING
#Repeat characters like * and + push OUTWARD in BOTH directions (referred to as greedy) to match THE LARGEST POSSIBLE STRING
#This can make your results different to what you want.
#Example:
import re
x = 'From: Using the : character'
y = re.findall('^F.+:', x)
print (y)
#So you want to find '... |
ac9ba1caec5036dabb08a6bbca5dfb32e8067a06 | Didden91/PythonCourse1 | /Week 8/8_6.py | 213 | 4 | 4 | total = list()
while True:
numbinp = input("enter a number:")
if numbinp == 'done': break
floatnum = float(numbinp)
total.append(floatnum)
print("Maximum:",max(total))
print("Minimum:",min(total))
|
9c74e24deb16d11cc0194504b4be55ea81bd1115 | Didden91/PythonCourse1 | /Week 6/6_3.py | 645 | 4.125 | 4 | def count(letter, word):
counter = 0
for search in word:
if search == letter:
counter = counter + 1
return counter
letterinput = input("Enter a letter: ")
wordinput = input("Enter a word: ")
wordinput = wordinput.strip('b ')
counter = count(letterinput, wordinput)
print(counter)
lowe... |
1b183e59f58d2adcf3a5624d57b0b0a129fe6c40 | Didden91/PythonCourse1 | /Week 9/9_4.py | 495 | 3.5625 | 4 | fname = input('Enter file name:')
try:
fhand = open(fname)
except:
print('invalid file name')
quit()
dixie = dict()
for line in fhand:
if not line.startswith('From '): continue
words = line.split()
words = words[1:2]
for word in words:
dixie[word] = dixie.get(word, 0) + 1
maxcount ... |
1b8b5732eeb4b7c9c767c815e5c0f2ec0676a99a | Didden91/PythonCourse1 | /Week 12/P7_HTMLParsing.py | 2,523 | 4.375 | 4 | #So now, what do we do with a webpage once we've retrieved it into our program
# We call this WEB SCRAPING, or WEB SPIDERING
# Not all website are happy to be scraped, quite a few don't want a 'robot' scraping their content
# They can ban you (account or IP) if they detect you scraping, so be careful when playing aroun... |
0196fbecdcaae1f917c8d17e505e2d6ca5cb8b4f | Didden91/PythonCourse1 | /Week 14/P4_Inheritance.py | 1,400 | 4.5 | 4 | # When we make a new class - we can reuse an existing class and inherit all the capabilities of an existing class
# and then add our own little bit to make our new class
#
# Another form of store and reuse
#
# Write once - reuse many times
#
# The new class (child) has all the capabilities of the old class (parent) - a... |
7f0b30c47f4b59a0803b329cda0af3051f6a2ff7 | jbrockmendel/monte_sims | /tax/tax_calculator.py | 2,602 | 3.6875 | 4 | """
Module that defines logic to calculate taxes
"""
import bracket_definitions as bd
import deduction_definitions as dd
import combined_bracket as cb
import constants
class TaxCalculation(object):
"""A tax calculator for a specific filing status and state.
Note that this only supports standard deduction
... |
b84979e10ccbae278fd29528003a144ad6e03b18 | 2blam/algo_practice | /sorting/quicksort.py | 658 | 3.8125 | 4 | # quick sort
# Best: O(n log n); Worst: O(n ^ 2); Average case: O (n log n); Space Complexity: Best - log n, Average: n
def quicksort(lst):
if len(lst) <=1:
return lst
less, equal, greater = [], [], []
# pick the first element as pivot (can use last one / random element)
pivot = lst[0]
... |
2bfd47468da51fe845f296dd921b4c3c8ca84b0e | creighton1199/AI_Project_1 | /Matrix.py | 2,226 | 3.796875 | 4 | import numpy as np
def matrix_multilication(A, B):
multiplied=np.tile(0, (A.shape[0], B.shape[1])) #initializing a matrix of required size
current=0
for x in range(A.shape[0]): #first for loop runs through all rows of Mat A
for y in range(B.shape[1]): #second for loop runs through all col... |
47e3ee0aa65599b23394a1b494508e0e6e1e753b | d-robert-buckley3/FSND | /Programming_Fundamentals/Use_Classes/turtle_poly.py | 402 | 4.125 | 4 | import turtle
def draw_poly(sides, size):
window = turtle.Screen()
window.bgcolor("white")
myturtle = turtle.Turtle()
myturtle.shape("classic")
myturtle.color("black")
myturtle.speed(2)
for side in range(sides):
myturtle.forward(size)
myturtle.right(360/sides)... |
07c3dc60a30bfade2e81de53d77357dcedc2344f | klamont15/cs61a | /hw04/problems/hw04.py | 3,640 | 3.59375 | 4 | HW_SOURCE_FILE = 'hw04.py'
def g(n):
"""Return the value of G(n), computed recursively.
>>> g(1)
1
>>> g(2)
2
>>> g(3)
3
>>> g(4)
10
>>> g(5)
22
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'g', ['While', 'For'])
True
"""
if n <= 3:
... |
a8833b2929b14debdbe9b968d2ff1d29ea345e43 | mouraa0/python-exercises | /exercises/ex098.py | 428 | 3.75 | 4 | def contador(a, b, c):
if a > b:
c = -c
for i in range(a, b - 1, c):
print(f'{i}', end=' ')
print('')
elif a < b:
for i in range(a, b + 1, c):
print(f'{i}', end=' ')
print('')
print('='*30)
contador(1, 10, 1)
contador(10, 0, 2)
inicio = ... |
fb65aafd67b5dba7035bea3926b8f8501f58376f | mouraa0/python-exercises | /exercises/ex102.py | 416 | 3.78125 | 4 | def fatorial(a, show=False):
c = 1
for i in range(a, 0, -1):
c *= i
if show:
print(f'{i}', end='')
if i > 1:
print(' x ', end='')
else:
print(' = ',end='')
return c
num = int(input('Digite um número: '))
opcao = inp... |
afa43f0e087e001e185c04db6a949619c6405024 | mouraa0/python-exercises | /exercises/ex059.py | 1,052 | 3.859375 | 4 | def ex059():
valor1 = float(input('Primeiro valor: '))
valor2 = float(input('Segundo valor: '))
op = 0
while op != 5:
op = input('Escolha:\n[1] Somar\n[2] Multiplicar\n[3] Maior\n[4] Novos valores\n[5] Fechar\n')
while op not in ['1', '2', '3', '4', '5']:
op = input('Escolha ... |
22add3d9fd54f5beee9fe3c041cc75a34d276849 | mouraa0/python-exercises | /exercises/ex100.py | 368 | 3.578125 | 4 | from random import randint
def sorteia():
lista = []
for i in range(5):
lista.append(randint(1, 10))
print(lista)
return lista
def somaPar(l):
somador = 0
for i in l:
if i % 2 == 0:
somador += i
print(f'Soma dos números pares sorteados: ... |
912b87d35273e0b970a50393ab6d86835d7216c3 | mouraa0/python-exercises | /exercises/ex064.py | 343 | 3.640625 | 4 | def ex064():
numereco = 0
soma = 0
contador = 0
while numereco != 999:
numereco = int(input('Digite um número (para encerrar digite 999):\n'))
if numereco != 999:
soma += numereco
contador += 1
print(f'{contador} números foram digitados\nSom... |
f081d9a599423e30d6ff9e9f532d84bf70b825fd | mouraa0/python-exercises | /exercises/ex050.py | 277 | 3.828125 | 4 | def ex050():
somatorio = 0
for i in range(1,7):
num = int(input('Digite um número: '))
if num % 2 == 0:
print(f'{num} é par')
somatorio += num
print(f'A soma de todos os pares citado é igual a {somatorio}')
ex050()
|
d287447a289cd660f90bc15b839562630bcbf394 | mouraa0/python-exercises | /exercises/ex052.py | 260 | 3.59375 | 4 | def ex052():
numero = int(input('Número:\n'))
contador = 0
for i in range(2, numero):
if numero % i == 0:
contador += 1
if contador != 0:
print('Não é primo')
else:
print('É primo')
ex052()
|
d24fb6b688a13252d2594b8d2eb0cec4cc9b6590 | wkostuch/sandcastle | /sand_castle_shapes.py | 17,528 | 3.75 | 4 | import math
#File of classes for the various shapes with methods attached
'''
CONSTANTS for use in the file
'''
SAND_DENSITY = 2082.0 # kg / m^3
SAND_DIAMETER = 0.000375 # diameter in meters, aka 375 micro-meters
SAND_RADIUS = SAND_DIAMETER / 2 #meters
SAND_VOLUME = (4/3) * math.pi * (SAND_RADIUS**3)
WATER_DENSITY =... |
40ad54ff65392e06c2fb912f5b9b9373120440e7 | eric-s-s/paragraph_generator | /paragraph_generator/answer_checker.py | 1,745 | 3.5 | 4 | """
strategy. take answer string and original paragraph.
use create_answer_paragraph to generate new paragraph with correct plural nouns.
use ParagraphComparisons to generate comparitor.
return requested json including answer paragraph according to kind of comparison requested.
"""
from paragraph_generator.backend... |
ea8246a8aeb2e0ad683a28c3565efcb0fee4fa46 | Puttipong1234/PYBOTT-5TH-5 | /basic_python/match_fuzzy.py | 732 | 3.625 | 4 | # print(1+1) #2
# def add(num1 , num2):
# print("คุณได้ทำการบวกเลข 2 ตัว คือ {} และ {}".format(num1,num2))
# result = num1+num2
# print("ผลลัพธ์คือ {}".format(result))
# return result
# ผลลัพธ์ = add(num1=5,num2=10)
# print(ผลลัพธ์)
from fuzzywuzzy import process
def match_fuzzy(text,text_list,score):... |
ed26c58769cdce9bc099d1df83b6892e238c0804 | SummerLyn/devcamp_2016 | /python/Nov_29_Tue/warm_up.py | 527 | 4.1875 | 4 | def is_odd(num):
"""
>>> is_odd(1)
True
"""
if num % 2 == 0:
return False
else:
return True
def is_divisible(num1, num2):
"""
>>> is_divisible(4, 3)
True
>>>
"""
if num1 % num2 == 0:
return True
else:
return False
def is_palindro... |
7186b0324e96780924078e1d1e07058c1ddc1545 | SummerLyn/devcamp_2016 | /python/Nov_29_Tue/File_Reader/file_reader.py | 1,482 | 4.3125 | 4 | # This is an example on how to open a file as a read only text document
def open_file():
'''
Input: no input variables
Usage: open and read a text file
Output: return a list of words in the text file
'''
words = []
with open('constitution.html','r') as file:
#text = file.read()
#... |
3972d0743b7bc1256c6de0da8cafbb4ab3e6443f | SummerLyn/devcamp_2016 | /python/Nov_30_Wed/global_variable_notes.py | 263 | 3.90625 | 4 | import random as rand
numbers =[]
def add_to_numbers():
number = int(input("Enter num: ")
for i in range(1, number+1):
numbers.append(i)
def main():
add_to_numbers()
print(numbers)
numbers.append(55)
print(numbers)
main()
|
11df50626e7b44c30e2ac185d6b90c8182c56fed | SummerLyn/devcamp_2016 | /Assignments/Python/BlackJack/deckclass.py | 2,611 | 3.9375 | 4 | from cardclass import Card
from random import shuffle
from itertools import product
suits = ['\u2660', '\u2665', '\u2666', '\u2663']
faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
class Deck:
def __init__(self, num_decks):
self.num_decks = num_decks
self.c... |
549d05dd07db0861e05d1a748cd34ce3cc5ed303 | SummerLyn/devcamp_2016 | /python/day3/string_problem_day3.py | 395 | 4.1875 | 4 | # Take the first and last letter of the string and replace the middle part of
# the word with the lenght of every other letter.
user_input_fun = input(" Give me a fun word. >>")
#user_input_shorter = input("Enter in a shorter word. >>")
if len(user_input_fun) < 3:
print("Error!")
else:
print(user_input_fun[... |
1219597ac11a07ca8bbce48b6f18b61ca058052f | SummerLyn/devcamp_2016 | /python/day7/more_for_loops.py | 495 | 4.15625 | 4 | #use for range loop and then for each loop to print
word_list = ["a","b","c","d","e","f","g"]
# for each loop
for i in word_list:
print(i)
# for loop using range
for i in range(0,len(word_list)):
print(word_list[i])
#get user input
#loop through string and print value
#if value is a vowel break out of loop... |
0dabaa83adddc6da213923473e516cf441bd496b | SummerLyn/devcamp_2016 | /python/Dec_8_snowday/BlackJack/Deckclass.py | 702 | 3.71875 | 4 | from Cardclass import Card
from random import shuffle
from itertools import product
class Deck:
def __init__(self):
self.cards = []
self.make_deck()
def make_deck(self):
suits = ['\u2660', '\u2665', '\u2666', '\u2663']
faces = ['2','3','4','5','6','7','8','9','10','Jack','Quee... |
384919a15842c7a21431ba6f227a503ff8b2495d | Isaccchoi/python-practice | /function/argument.py | 221 | 4.0625 | 4 | def multiplication(*args):
multiple = 1
if len(args) >=2:
for arg in args:
multiple *= arg
else:
multiple = args[0]**2
print( multiple)
multiplication(3)
multiplication(3,5)
|
30e65ce29f5241ccec766f6d540f4035d59d63a3 | andrewsli/problem-solving | /python-scripting/list_less_than_ten.py | 85 | 3.71875 | 4 | a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
print(f"{[num for num in a if num < 10]}") |
455c7276e15412d0c71f05a1679ffe5f37e01c53 | NIROJ-SATYAL/calculator.py | /calculator.py | 3,022 | 4.09375 | 4 | from tkinter import *
def click(number):
current=e.get()
e.delete(0,END)
e.insert(0,str(current)+str(number))
def button_clear():
e.delete(0,END)
def back_space():
e.delete(len(e.get())-1,END)
def button_add():
first_number=e.get()
global f_num
global math
math="addition"
f_nu... |
a6d830905d07854acd6f7114cc9e4dc68f52077e | cafeduke/learn | /Python/Core/L02_Module/simple.py | 611 | 3.71875 | 4 | ''' A simple module '''
mesg = "Hello World"
l = [10, "Apple", 3.14159, "Ball", 31, "Cat"]
num = [3, 5, 10, 2, 3.14159]
def greet(str="Raghu"):
print("Hello {}, Inside fun".format(str))
class Wheel:
def __init__ (self, size, color):
self.size = size
self.color = color
def spin(self, count=1):
for ... |
2d3d01facdd8cf1951f31bd1705391b1ccb53b68 | cafeduke/learn | /Python/Advanced/maga/call_on_object.py | 1,009 | 4.28125 | 4 | ##
# The __call__() method of a class is internally invoked when an object is called, just like a function.
#
# obj(param1, param2, param3, ..., paramN)
#
# The parameters are passed to the __call__ method!
#
# Connecting calls
# ----------------
# Like anyother method __call__ can take any number of arguments and r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.