blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fa40721dae3ed2dda7d693a6adefd341265ed43b | AshankBhardwaj/python | /pattern2.py | 183 | 3.59375 | 4 | def pattern(n):
num = 65
- for i in range(0, n):
for j in range(0, i+1):
ch = chr(num)
print(ch, end=" ")
num = num +1
print("\r")
n = int(input())
pattern(n)
|
5dd10d1af098967f51550f910bc0d5f286e751be | sainthm/python-workspace | /Life_Programming/02-lambda_example.py | 411 | 3.625 | 4 | y = lambda x : 3 * x
print(y(12))
add = lambda a, b : a + b
print(add(2, 3))
little_prince = '''여섯 살 적에 나는 '체험한 이야기'라는 제목의, 원시림에 관한 책에서 기막힌 그림 하나를 본 적이 있다.'''
print(little_prince[:10])
short = lambda x : x[:10]
print(short(little_prince))
exchange = lambda won : won * 0.00087 #2020-10-14 환율 기준
print(exchange(100000... |
44a24545a7e4f2f28adb0f3abf61abd018d2c0cb | maurisg/python-for-everybody | /Chapter 10/exercise_03.py | 1,365 | 4.1875 | 4 | import string
count = 0 # Initialize variables
my_dictionary = {}
my_list = []
file = input("Enter file name: ")
try:
file = open(file)
except FileNotFoundError:
print("File cannot be opened:", file)
exit()
for line in file.readlines(): # Removes numb... |
0c2dcf64b7f3fba50b7825cbb2f4623bf5b420c4 | maurisg/python-for-everybody | /Chapter 8/exercise_05.py | 325 | 3.890625 | 4 | file = open("mbox-short.txt")
count = 0
for line in file:
if line.startswith('From:'):
continue
elif line.startswith("From"):
words = line.split()
print(words[1])
else:
continue
count = count + 1
print("There were", count, "lines in the file with From as the first wo... |
04a57b2ff8266953345d587a9da660b09b4a7fd3 | maurisg/python-for-everybody | /Chapter 10/exercise_02.py | 1,406 | 4.15625 | 4 | my_dictionary = {} # Creates an empty dictionary
my_list = [] # Creates an empty list
file = input("Enter file name: ")
try:
file = open(file)
except FileNotFoundError:
print("File cannot be opened:", file)
exit()
for line i... |
5b1782b351c8c4b81cdcd9d752bc30b1557df1e5 | moseslv/Python_101 | /New_sokudo.py | 2,621 | 4.40625 | 4 | # THREE GOLD STARS
# Sudoku [http://en.wikipedia.org/wiki/Sudoku]
# is a logic puzzle where a game
# is defined by a partially filled
# 9 x 9 square of digits where each square
# contains one of the digits 1,2,3,4,5,6,7,8,9.
# For this question we will generalize
# and simplify the game.
# Define a procedure, check_s... |
f3043ce2942d5933799ad0f762b3806f55f382af | phuongnguyen00/data-analysis-solar-cells | /Eff decay graph.py | 1,683 | 3.828125 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import openpyxl
"""
A program to graph the decay of efficiency of one particular cell over time.
(Forward data)
Assumming the current format of data.
"""
source_file = input("What is the source file name? ") +".xlsx"
df = pd.read_excel(source_file)
wb = openpyxl.lo... |
800d9b72c280df8cbecc51ebf84af969cc9e47f7 | Gendo90/topCoder | /0-300 pts/topcoderPassingGrade.py | 1,653 | 4.0625 | 4 | # Problem Statement
#
# You are studying for the final exam in a tough course, and want to know how many points you need to score on the final to pass the course. You know how many points you earned on each assignment (pointsEarned), how many points were possible on each assignment (pointsPossible), and how many points... |
f8fbd14a33d4ad5c1b047dc4a9a508c5798bf20d | Gendo90/topCoder | /0-300 pts/topcoderCultureShock.py | 1,088 | 4.21875 | 4 | # Problem Statement
#
# Bob and Doug have recently moved from Canada to the United States, and they are confused by this strange letter, "ZEE". They need your assistance. Given a string text, replace every occurrence of the word, "ZEE", with the word, "ZED", and return the result. Note that if "ZEE" is just part of a ... |
1edaeb280f23839c1d07bd6fe6138bd87104c4e9 | Gendo90/topCoder | /0-300 pts/topcoderScoringEfficiency.py | 3,013 | 3.859375 | 4 | # Problem Statement
#
# In basketball, players can attempt either two point or three point field goals, and if they are fouled, they can also attempt one point free throws. Since missing a free throw or a field goal often results in losing possession of the ball, it is important to make the most of each shot attempt. T... |
0f1b4624d7adf7d6970a0cad6067132137b46c63 | Gendo90/topCoder | /0-300 pts/topcoderNoOrderOfOperations.py | 2,133 | 4.53125 | 5 | # Problem Statement
#
# When evaluating a mathematical expression, there is the possibility of ambiguity. If you wanted to know the result of "3 + 5 * 7", you might first evaluate the (3+5) and get 56, or first evaluate the (5*7) and get 38. This ambiguity can be resolved by using the order of operations: first do mult... |
1bc03c60468e0b483858aa8d7094818de7c682a4 | Gendo90/topCoder | /400-600 pts/topcoderPaperFold.py | 2,700 | 3.875 | 4 | # Problem Statement
#
# You have a piece of paper that you need to fold to fit into a box with a given width and length. Each time you fold the paper, you can fold it in half across either its width or length, but you can only fold the paper 8 times (after 8 times, the paper is too dense to fold again).
# You will be g... |
a06b6f60324e41f192d3872b2b5f4feaa1b6157c | Gendo90/topCoder | /0-300 pts/topcoderBigBurger.py | 2,287 | 4.375 | 4 | #Problem Statement
#
#BigBurger Inc. wants to see if having a single person at the counter both to take orders and to serve them is feasible. At each BigBurger, customers will arrive and get in line. When they get to the head of the line they will place their order, which will be assembled and served to them. Then ... |
b25f6cec32de8abc56859e82ae130e2ed2798505 | Gendo90/topCoder | /0-300 pts/topcoderWidgetRepairs.py | 1,674 | 3.59375 | 4 | #Problem Statement
#
#When a widget breaks, it is sent to the widget repair shop, which is capable of repairing at most numPerDay widgets per day. Given a record of the number of widgets that arrive at the shop each morning, your task is to determine how many days the shop must operate to repair all the widgets, no... |
8c7df9386326069d7af8d47fc5f443245ac61c9e | Gendo90/topCoder | /0-300 pts/topcoderMagicSquare.py | 1,452 | 4.25 | 4 | # Problem Statement
#
# A magic square is a 3x3 array of numbers, such that the sum of each row, column, and diagonal are all the same. For example:
#
# 8 1 6
# 3 5 7
# 4 9 2
# In this example, all rows, columns, and diagonals sum to 15.
# You will be given a tuple (integer) representing the nine numbers of... |
8813e09af0620ee027b391f7e543fdc57902a08f | Gendo90/topCoder | /0-300 pts/topcoderDiskSpace.py | 3,244 | 4.0625 | 4 | #Problem Statement
#
#As of late, your usually high-performance computer has been acting rather sluggish. You come to realize that while you have plenty of free disk space on your machine, it is split up over many hard drives. You decide that the secret to improving performance is to consolidate all the data on you... |
9f61dd172cf66ee518c9e2e9ebc0361ce68c3107 | Gendo90/topCoder | /0-300 pts/topcoderTextCompressor.py | 2,170 | 4.25 | 4 | # Problem Statement
#
# Your company is working on writing a piece of software to compress a text document. As part of the software development team, you have been asked to write a function that will find the longest repeated sub-string within a piece of text, such that the two chosen occurrences of the sub-string do n... |
f9a2b46123442f8dc484396050596099e489ab02 | rperezmendoza/CS452A3 | /signer.py | 10,306 | 3.5 | 4 | #Roberto Perez Mendoza
#Assignment 3
#################################################################################
# This file gives an example of generating a digital signature and verifying it
#################################################################################
import os, random, struct
import sys
... |
cc9c0d246cf47b35b1d81c0b6604887d0338bcc0 | GYGeorge/py | /leetcode/287FindtheDuplicateNumber.py | 1,011 | 4 | 4 | # /*
# * @Author: gaoyuan
# * @Date: 2020-07-01 16:59:57
# * @Last Modified by: gaoyuan
# * @Last Modified time: 2020-07-01 16:59:57
# */
class Solution:
"""
Given an array nums containing n + 1 integers
where each integer is between 1 and n (inclusive),
prove that at least one ... |
63e23a44798d4d37fd9ce682f7313b0ee88a9091 | clague17/pdfchallenges | /bucketchallenge.py | 1,946 | 3.921875 | 4 | from collections import *
'''
You are given an array bucket_sizes (e.g. [3, 11, 21]) and a target_value (e.g. 492).
The resulting answer should be a 1 or 0 (alternatively true and false)
1 (true) - if the buckets can be used to reach the target value
0 (false) - if they cannot
ex:
Given:
bucket_sizes <-- [5, 7]
targ... |
a42f106eb411ff1d4b4ce4054c9ef7d25f0eface | MacHu-GWU/crawl_trulia-project | /crawl_trulia/packages/crawlib/htmlparser.py | 1,975 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
class SoupError(Exception):
"""Failed to convert html to beatifulsoup.
**中文文档**
html成功获得了, 但是格式有错误, 不能转化为soup。
"""
class CaptchaError(Exception):
"""Encounter a captcha page.
**中文文档**
遭遇反爬虫验证页面。
"""
... |
6de8faefb4d86596ebfcbfbeec07c36da8a1e198 | MacHu-GWU/crawl_trulia-project | /crawl_trulia/urlencoder.py | 4,021 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Because when you search an address on trulia, it actually encode your input and
generate an url, and the trulia server will process this request. So this module
is to create the request url based on your search.
"""
special_words = {
"nw": "NW", "ne": "NE", "sw"... |
7e51610f6baff28e7e612b54a43ebf3e9e46faeb | rwsargent/adventofcode | /2015/day13.py | 1,710 | 3.5 | 4 | import re
import pdb
import itertools
def read_input(filename):
pattern = re.compile(r'(\w+) would (gain|lose) (\d+) happiness units by sitting next to (\w+)')
guests = {}
with open(filename) as file:
for line in file:
sitter, diff, amount, sittee = pattern.findall(line.strip())[0]
... |
b0961d5e0df75ca3fd3f855a283d22a4c1ea0225 | studyrah/p1-introtods | /src/ps3-problemsets/p6_ols.py | 4,558 | 4.15625 | 4 | import numpy as np
import pandas
#import scipy
import statsmodels.api as sm
from datetime import *
from ggplot import *
from random import sample
"""
In this optional exercise, you should complete the function called
predictions(turnstile_weather). This function takes in our pandas
turnstile weather dataframe, and... |
11e29815b19025b0606d847d7d691955974697f4 | studyrah/p1-introtods | /src/ps3-problemsets/p4_gradientdescent_plot_residuals.py | 1,753 | 3.6875 | 4 | # -*- coding: utf-8 -*-
import numpy as np
import pandas
import pandasql
from random import sample
from datetime import *
import scipy
import matplotlib.pyplot as plt
import p3_gradientdescent as gd
def plot_residuals(turnstile_weather, predictions):
'''
Using the same methods that we used to plot a histog... |
8d5fa292ddf184e7e85934b7c890f76e0b1f89c4 | KristoferGauti/Forritun-1-HR | /practice_makes_perfect/max_int.py | 638 | 4.03125 | 4 |
num_int = int(input("Input a number: ")) # Do not change this line
listi = []
while num_int >= 0:
listi.append(num_int)
num_int = int(input("Input a number: "))
max_int = max(listi)
print("The maximum is", max_int) # Do not change this line
#dæmi 2
n = int(input("Enter the length of the sequence: "... |
ee5705945f97256c10ee0d131ab3d771c7919964 | KristoferGauti/Forritun-1-HR | /Classes_examples/Class_bókin_student_class.py | 977 | 3.84375 | 4 | class Student(object):
def __init__(self, first = "", last = "", id = 0): #The init method is our constructor
self.first_name_str = first #self is a default instance
self.last_name_str = last
self.id_int = id
#The __init__ function does not have an explicit return statement,
#in fact... |
bff9e863e279cd3114c1f31def11d0fe28541026 | KristoferGauti/Forritun-1-HR | /Classes_examples/class_set_method.py | 565 | 3.984375 | 4 | class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
def get_name(self):
return self.__name
def get_age(self):
return self.__age
def set_age(self,new_age):
if new_age > 0:
self.__age = new_age
def print_age(self):
print("{} is ... |
64d033ee383be45086397e29067b8ab98f8f1c51 | KristoferGauti/Forritun-1-HR | /projects/population1.py | 529 | 3.640625 | 4 | #Eg vann þetta verkefni með Johanni Inga i hop 2
population = 307357870 #folksfjöldinn i Bandarikjunum
year = int(31536000) #sekundur a ari (365)
birth = year / 7 #fæðing a ari
death = year / 13 #dauðsfall a ari
new = year / 35 #nyr innflytjandi a ari
#breyting a folksfjölda ar hvert
new_population = birth - death... |
5cb7e95d5dff740a7aa3199e787a65c7113339b0 | KristoferGauti/Forritun-1-HR | /Classes_examples/class_get_method.py | 711 | 4.15625 | 4 | class Person:
def __init__(self, name, age, relationship):
self.__name = name
self.__age = age
self.__relationship = relationship
def get_name(self):
return self.__name
def get_age(self):
return self.__age
def get_relationship(self):
return self.__relationship
def... |
b2ea1b29c0a8faa4c0023319b5603dd5b4e9dc05 | KristoferGauti/Forritun-1-HR | /Classes_examples/book_example_class.py | 694 | 3.734375 | 4 | class NewClass(object):
def __init__(self, param_int = 1):
self.the_int = param_int
if param_int % 2 == 0:
self.hvap = "even"
else:
self.hvap = "odd"
def process(self, instance):
sum_int = self.the_int + instance.the_int
if sum_int < 0:
return "nega... |
12a17f67d700025192e3fb6a42d7cbda949a2a3d | KristoferGauti/Forritun-1-HR | /Classes_examples/Class_bókin.py | 537 | 3.984375 | 4 | #Making a method
class MyClass (object):
class_attribute = 'world'
def my_method(self, param1):
print('\nhello {}'.format(param1))
print('The object that called this method is: {}'.format(str(self)))
self.instance_attribute = param1
my_instance = MyClass()
print("output of dir(my instance... |
99681623aedf4b02b63cf931cdd62d97009715fb | KristoferGauti/Forritun-1-HR | /Classes_examples/class_inheritance.py | 907 | 4.21875 | 4 | class Animal:
def __init__(self,name):
self.name = name
def __str__(self):
return "Hi my name is {}".format(self.name)
def make_sound(self):
print("General animal sound.")
#We declare the Dog class which inherits the Parent class Animal
class Dog(Animal):
def __init__(self, name, color)... |
902213b6bd2f7e44d5bc9ae93385c751e0229fbc | KristoferGauti/Forritun-1-HR | /sideprojects/Flag of Iceland.py | 2,852 | 3.71875 | 4 | #The Icelandic flag in all its glory
import turtle
def no_draw():
turtle.speed(7)
turtle.penup()
turtle.right(180)
turtle.forward(300)
turtle.right(90)
turtle.forward(200)
turtle.right(90)
turtle.pendown()
def text():
turtle.color("dark red")
style = ("Helvetica", 29, "bold"... |
c9d9be25037dbef56a739c7b3aaf9bed11e1163a | KristoferGauti/Forritun-1-HR | /preperation_for_the_final_exam/sliding_puzzles.py | 2,567 | 4.03125 | 4 | """Example input:
5 3 13 7 14 10 0 11 1 4 6 8 12 9 2 15"""
# Constants
DIM = 4 # dimension of the board DIMxDIM
EMPTYSLOT = 0
QUIT = 0
def initialize_board():
''' Creates the initial board according to the user input.
The board is a list of lists.
The list contains DIM elements (rows), each of which cont... |
8efc9598285fc186f0440101dec1ac8da9cfcf9a | arjun-vasudevan/Contest_Programming | /DMOJ-Python/416.py | 160 | 3.84375 | 4 | num = raw_input()
if num[:3] == "416":
print "valuable"
elif num[:3] == "647" or num[:3] == "437":
print "valueless"
else:
print "invalid"
|
57e219d0a684126eb71272bb9133dc08e4452c65 | arjun-vasudevan/Contest_Programming | /DMOJ-Python/Snow Calls.py | 694 | 3.53125 | 4 | letters = {"A":"2", "B":"2", "C":"2", "D":"3", "E":"3", "F":"3", "G":"4", "H":"4",
"I":"4", "J":"5", "K":"5", "L":"5", "M":"6", "N":"6", "O":"6", "P":"7",
"Q":"7", "R":"7", "S":"7", "T":"8", "U":"8", "V":"8", "W":"9", "X":"9",
"Y":"9", "Z":"9"}
t = input()
correct = []
for i in ... |
1dbcddebd79c59587371c10c17846219b358c83a | arjun-vasudevan/Contest_Programming | /DMOJ-Python/Next Prime.py | 495 | 3.65625 | 4 | import sys
import math
def is_prime(num):
if num == 0 or num == 1:
return False
elif num == 2:
return True
elif num % 2 != 0:
divisors = [int(x) for x in xrange(1, int(math.ceil(num**0.5))) if num % x == 0]
if len(divisors) + 1 == 2:
return True
ret... |
f8105210b529f6f4c555ebf62da87a7ceed16e57 | MarieNoelleGrant/adventOfCode | /modules/intcode_computer.py | 13,333 | 3.796875 | 4 | from os import path
def create_program(text_file):
program = list()
if path.exists(text_file):
with open(text_file, "r") as inputFile:
for line in inputFile:
number = ""
for word in line:
if word != "," and word != "\n":
... |
e20c62e7f1e6da8d40678d5ba605a67bf5ad876d | AdrianGallyot/python-challenge | /PyRoll/main.py | 2,820 | 3.5625 | 4 | #import necessary modules
import os
import csv
#Read in the CSV data for budget data
csvReader = os.path.join('PyRoll','Resources','election_data.csv')
output_path = os.path.join('PyRoll','Output','Results.txt')
#create variable to count months and List to hold election data
count = 0
votes = [] #sums to hold the val... |
2127358795bc40391d120ca3460cebda6e00d539 | Sertpolk/Temperature-changes-in-brisbane | /andy_plot.py | 386 | 3.578125 | 4 | import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv("tmax.040842.daily.csv",delimiter=",")
for col_name in data.columns:
if col_name == "date" or col_name == "maximum temperature (degC)":
continue
data = data.drop(col_name, 1)
data = data.dropna()
dates = pd.to_datetime(data['date']... |
21be3263762102a6649e92478639f32185d0d345 | buaacarzp/Leetcode_jianzhi_offer | /zu组合方式.py | 2,792 | 3.609375 | 4 | '''
给定一个数k,求出从1-k中和为k的所有可能性,要求不能有重复的数
结果是对的,但是含有重复的元素
'''
def sumk(k):
def back_track(nums,temp):
if sum(temp)==k :
res_all.append(temp)
return
for i in range(len(nums)):
if sum(temp)>k:
break
back_track(nums[:i]+nums[i+1:],temp... |
ee0b85d08eb7c92e657f16b6f46554fbcc8f596f | andywaltlova/advent_of_code_2020 | /1.py | 1,408 | 4.375 | 4 | # https://adventofcode.com/2020/day/1
from typing import List, Optional, Tuple
def read_input(path: str) -> List[int]:
with open(path) as f:
lines = [int(line.strip()) for line in f.readlines()]
return lines
def find_two_nums_with_sum(numbers: List[int], target_sum: int) -> Optional[Tuple[int, int... |
20da56e3e55010a39b1d84b58ddcf8f098d4fa40 | andywaltlova/advent_of_code_2020 | /2.py | 1,026 | 3.9375 | 4 | # https://adventofcode.com/2020/day/2
from typing import List, Optional
def read_valid_input(path: str, val_func) -> List[Optional[str]]:
with open(path) as f:
return [parse_line(line, val_func) for line in f.readlines() if parse_line(line, val_func)]
def parse_line(line: str, val_func) -> Optional[str... |
7214e04c9b7deca2d2c26697fbf1ca5d02490b4a | andywaltlova/advent_of_code_2020 | /13.py | 1,085 | 3.8125 | 4 | # https://adventofcode.com/2020/day/13
def read_input(path: str):
with open(path) as f:
lines = [line.strip() for line in f.readlines()]
timestamp = int(lines[0])
return timestamp, lines[1].split(',')
def find_first_greater_multiple(k, m):
n = 0
while n < k:
n += m
diff = n -... |
398599e3333830b937ce7ff600e94a51212b2aa0 | big-Bong/AlgoAndDs | /PythonPractice/LeetCode/Easy/53_MaximumSubarray.py | 272 | 3.796875 | 4 | def maxSubarray(arr):
if(not arr):
return None
maxSum = arr[0]
total = arr[0]
N = len(arr)
for j in range(1,N):
total += arr[j]
if(total <= arr[j]):
total = arr[j]
if(total > maxSum):
maxSum = total
return maxSum
nums = [-1]
print(maxSubarray(nums)) |
9f269ebe71d387fb41c788717a3cb2a99fdefc89 | big-Bong/AlgoAndDs | /PythonPractice/CodeWars/FindEvenIndex.py | 926 | 4.0625 | 4 | """
Find the index in the array (if it exists) where the sum to the left hand side of the index and sum to the right hand side of the index
is equal.
CODEWARS
"""
"""
def find_even_index(arr):
n = len(arr)
for i in range(0,n):
left_sum = sum(arr[:i])
right_sum = sum(arr[i+1:])
... |
85961597186aedf89eb2edfa03cc4255bd7f10cf | big-Bong/AlgoAndDs | /PythonPractice/LinkedList/LLCreation.py | 364 | 4 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def traversal(self):
node = self.head
while(node != None):
print(node.data)
node = node.next
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
llist = LinkedList()
llist.head = n1
n... |
4747168737bfec1a02b60f5599c14e86b7d66866 | big-Bong/AlgoAndDs | /PythonPractice/LeetCode/SeptemberChallenge/GetAllElementsBST.py | 1,161 | 3.625 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def getAllElements(root1, root2):
arr1 = []
arr2 = []
if(not root1 and not root2):
return []
if(not root1):
inorder(root2,arr2)
return... |
d92a1998a2d5a811c77d878cc794567560d9e53f | big-Bong/AlgoAndDs | /PythonPractice/LeetCode/SortedListToBSTOpt.py | 1,167 | 4.03125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 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,h... |
879d231bcb102e6671a6220d0b7ce7fb6bb988fd | big-Bong/AlgoAndDs | /PythonPractice/DP/StepClimbing.py | 225 | 3.59375 | 4 | def stepClimbing(n):
if(n<=0):
return
arr = [0]*(n+1)
arr[0] = 1
for i in range(1,n+1):
total = 0
for j in [1,3,5]:
if((i-j) >= 0):
total += arr[i-j]
arr[i] = total
return arr[n]
print(stepClimbing(7)) |
0a9618ccd51107c5a9619be448a711cc196d0461 | big-Bong/AlgoAndDs | /PythonPractice/LeetCode/Easy/1446_ConsecutiveCharacters.py | 338 | 3.6875 | 4 | def maxPower(s):
if(not s):
return 0
maxP = 1
N = len(s)
counter = 1
for i in range(N-1):
if(s[i] == s[i+1]):
counter += 1
if(counter > maxP):
maxP = counter
else:
counter = 1
return maxP
s = "leetcode"
#s = "ee"
#s = "e"
#s = "eelleee"
#s = "elle"
#s = "abcc"
#s = "abcd"
#s = "aabbbcccc"
p... |
0c298617f19d4d237e47d5bc8357ca5ca586b35a | big-Bong/AlgoAndDs | /PythonPractice/LeetCode/Easy/217_DuplicateElement.py | 249 | 3.828125 | 4 | from typing import Set
class Solution:
def hasDuplicateElements(self, arr):
dict = set()
for elem in arr:
if(elem in dict):
return True
else:
dict.add(elem)
return False
S = Solution()
print(S.hasDuplicateElements([1,2,3,4])) |
ce5e9bfd9e2624ba0f305932ad8b4ad1c9130c71 | big-Bong/AlgoAndDs | /PythonPractice/Trees/BinaryTree.py | 1,950 | 3.859375 | 4 | class BinaryTreeNode:
def __init__(self,value):
self.value = value
self.left = None
self.right = None
def inorder(root):
if(root):
inorder(root.left)
print(root.value)
inorder(root.right)
def preorder(root):
if(root):
print(root.value)
preorder(root.left)
preorder(root.right)
def postorder(ro... |
4cee3218f4a0d91e6c56ee11386c5e188037058b | big-Bong/AlgoAndDs | /PythonPractice/LeetCode/Medium/78_Subsets.py | 507 | 3.578125 | 4 | def subsets(nums):
if(not nums):
return [[]]
output = [[]]
for i in range(1,len(nums)+1):
data = [0 for _ in range(i)]
generateSubsets(nums,data,output,0,len(nums)-1,0)
return output
def generateSubsets(nums,data,output,start,end,index):
if(index == len(data)):
temp = [elem for elem in data]
output.ap... |
418d7c9c0f8c767a19b51b76bf47bea715e09d39 | big-Bong/AlgoAndDs | /PythonPractice/LeetCode/Medium/179_LargestNumber.py | 1,263 | 3.546875 | 4 | def largestNumber(nums):
if(not nums):
return ""
if(sum(nums) == 0):
return "0"
N = len(nums)
maxDigits = 0
for i in range(N):
digits = findNoDigits(nums[i])
nums[i] = (nums[i],digits)
if(digits > maxDigits):
maxDigits = digits
for i in range(N):
number, digits = nums[i]
if(digits != maxDigits... |
d856035b2f29db90c604c5a1d37657ba02851bfb | big-Bong/AlgoAndDs | /PythonPractice/LeetCode/Medium/148_SortList.py | 1,056 | 4.0625 | 4 | class ListNode:
def __init__(self,val = 0):
self.val = val
self.next = None
def sortList(head):
if(not head or head.next == None):
return head
middle = findMiddle(head)
nexttomiddle = middle.next
middle.next = None
left = sortList(head)
right = sortList(nexttomiddle)
return mergeList(left,right)
def fi... |
e216cf2efedef3b54c07258eb0d80a0426b637d5 | big-Bong/AlgoAndDs | /PythonPractice/LeetCode/SeptemberChallenge/WordPattern.py | 502 | 3.71875 | 4 | def wordPattern(pattern,str):
if(not pattern and not str):
return True
N = len(pattern)
arr = str.split()
M = len(arr)
if(N != M):
return False
dict1 = {}
dict2 = {}
for i in range(N):
if(pattern[i] in dict1):
if(arr[i] != dict1[pattern[i]]):
return False
if(arr[i] in dict2):
if(pattern[i] ... |
461d0527901a230e83a5e2a604c7e89baaf617a5 | big-Bong/AlgoAndDs | /PythonPractice/Graphs/UnionFind.py | 658 | 4 | 4 | #Union-Find Algorithm. Assuming Graph vertices are labeled as 0, 1, 2 etc.
#Find - Find's whether two vertices belong to same subset or not
def find(arr,v1,v2):
start_v1 = arr[v1]
while(start_v1 != -1):
v1 = start_v1
start_v1 = arr[v1]
start_v2 = arr[v2]
while(start_v2 != -1):
v2 = start_v2
start_v2 = arr... |
87a9f7ad2e924987f5b0bc34bde24dd45a4ef58c | big-Bong/AlgoAndDs | /PythonPractice/LeetCode/SeptemberChallenge/GetHint.py | 677 | 3.546875 | 4 | def getHint(secret, guess):
dict = {}
for elem in secret:
if(elem in dict):
dict[elem] += 1
else:
dict[elem] = 1
output_dict = {'A':0,'B':0}
N = len(guess)
remaining_guess = ""
for i in range(N):
if(guess[i] in dict and dict[guess[i]] > 0):
if(guess[i] == secret[i]):
output_dict['A'] += 1
... |
64e3c379e86941609ba5bcc5e4981042e16ae218 | big-Bong/AlgoAndDs | /PythonPractice/Graphs/UnionByRank.py | 1,428 | 3.71875 | 4 | #Union By Rank and Path Compression. Detect cycle in a graph.
#Find operation with path compression
def findParent(parent,vertex):
parent_vertex = parent[vertex]
while(parent[parent_vertex] != -1):
parent[vertex] = parent[parent_vertex]
vertex = parent_vertex
parent_vertex = parent[parent_vertex]
return vert... |
1cc7f7a3f01b7edab9fa9096c7467067efb59b97 | big-Bong/AlgoAndDs | /PythonPractice/LeetCode/Medium/55_JumpGame.py | 692 | 3.640625 | 4 | def canJump(nums):
if(not nums):
return False
N = len(nums)
bool_arr = [False]*N
bool_arr[-1] = True
for i in range(N-2,-1,-1):
max_jump = nums[i] + i
while(max_jump > 0):
if(max_jump < N-1 and not bool_arr[max_jump]):
max_jump -= 1
else:
bool_arr[i] = True
break
return bool_arr[0]
def... |
d35d89cc67db1d71b64f2f021c809ed61a2c4b5f | hyunwookjleeucc/Y10Design-PythonHJL | /Vending Machine/vendingmachine.py | 2,841 | 4.1875 | 4 | #September 20, 2019
#Hyunwook Justin Lee
#Upper Canada College
import webbrowser as web
print("Hi, welcome to the Vending Machine!")
print("1. Coca Cola")
print("2. Pepsi")
print("3. Honest Tea")
print("4. Raw creatine")
print("5. Aramark Special Jerk Chicken")
print(" ")
print("Choose one of the options above")
ans... |
c2bdc44be43ffe48dfb4c783289947fd19425547 | francivaldonlima/PYTHON | /MEGASEMAGERANUMERO.py | 611 | 3.90625 | 4 | #coding: utf-8
import time
import random
numeros = []
megasena = 5
numeros_sorteados = 1
while (megasena >= len(numeros)):
n = random.sample(range(1,60), 1)
print ("O" , numeros_sorteados,"° NÚMERO FOI " , n)
if (n in numeros):
print("O" , numeros_sorteados ,"° NÚMERO ESTA REPETIDO " , ... |
9fc49fc353c958eec0f40ea7151bf05f6fddac03 | gongguoliang/Sort | /Sort/MergeSort.py | 778 | 3.921875 | 4 | def merge_sort(ary):
if len(ary) <= 1 : return ary
num = int(len(ary)/2) #二分分解
left = merge_sort(ary[:num])
right = merge_sort(ary[num:])
return merge(left,right) #合并数组
def merge(left,right):
l,r = 0,0 #left与right数组的下标指针
result = []
while l<len(left) and r<len(right) ... |
ef4ea0b6b4f4ce14f4aefa315c65ccfcf72050a4 | Ksuer/100DaysOfCode | /Day22_Dictionaries.1.py | 748 | 4.6875 | 5 | my_dict = {1: 'a', 2: 'b', 3: 'c'}
print(my_dict) #{1: 'a', 2: 'b', 3: 'c'}
# Accessing Items
print(my_dict[1]) #a
# Changing value of item
my_dict[2] = 'd'
print(my_dict) #{1: 'a', 2: 'd', 3: 'c'}
# Loop through dictionary keys
for x in my_dict:
print(x) # 1 2 3
# Loop through dictionary values
for x in my_di... |
035c505545b2a25d47725ca78eac2e1354cc1baf | Ksuer/100DaysOfCode | /Day2.py | 316 | 4.125 | 4 | #One line comment
print('Hello, World!')
#Comments can be placed at the end of a line
print('Hello, World!') #One line comment
#Multi line comments
#This is comment
#Written in more than one line
print('Hello, World!')
#Multiline String
'''
This is comment
Written in more than one line
'''
print('Hello, World!') |
71b9125aaacf4f4ff33b8e46d57efa24434cf47b | Ksuer/100DaysOfCode | /Day28_WhileLoop.py | 413 | 4.40625 | 4 | # Print i as long as i is less than 6
i=0
while i<6:
print(i)
i+=1
# Break
i=1
while i<6:
print(i)
if i==3:
break
i+=1
# Continue
i=0
while i<6:
i+=1
if i==3:
continue
print(i)
# With the else statement we can run a block of code once when the condition no longer i... |
7325d661eb1aab5d481a6379ef77c483f2388661 | Ksuer/100DaysOfCode | /Day29_30_ForLoop.py | 468 | 4.34375 | 4 | numbers_list= [1,2,3,4,5]
for n in numbers_list:
print(n)
# Looping Through a String
name= 'Eman'
for n in name:
print(n)
# Exit the loop when n is 3
numbers_list= [1,2,3,4,5]
for n in numbers_list:
if n==3:
break
print(n) #1 2
# Don't print 3
for n in numbers_list:
if n==3:
... |
48714d10749f44af5287277ff4ba4e3543f80134 | kdk745/Projects | /CS313E/Mondrian2.py | 4,644 | 4.15625 | 4 | # File: Mondrian.py
# Description: Program that creates a random drawing varying complexity based on user input and outputs it as a .eps image.
# Student Name: Juanito Taveras
# Student UT EID: jmt3686
# Course Name: CS 313E
# Unique Number: 51730
# Date Created: 3/3/2015
# Date Last Modified: 3/3/2015
... |
58f932efb7eccd2cb96328702253d1bb90421b8f | kdk745/Projects | /CS313E/permute.py | 321 | 3.65625 | 4 |
def permute (a, lo, hi):
if (lo == hi):
print(a)
return
else:
for i in range (lo, hi):
a[i], a[lo] = a[lo], a[i]
permute (a, lo + 1, hi)
a[i], a[lo] = a[lo], a[i]
def main():
a = [1,2,3,4]
permute(a,0,len(a))
print()
main()... |
5fd3f629b2e32c57c8413785235647ffd52aa39d | kdk745/Projects | /CS303E/Deal2.py | 2,243 | 3.9375 | 4 | # File: Deal.py
# Description: The Monty Hall Problem - Let's Make a Deal - and the probability of switching
# Student Name: Kayne Khoury
# Student UT EID: kdk745
# Course Name: CS 303E
# Unique Number:52700
# Date Created: 10/4/2014
# Date Last Modified: 10/5/2014
import random
def main():
# enter num... |
ab8a5f861da7f1aa088df5e742d7fbe4644a84d4 | kdk745/Projects | /CS303E/revrow.py | 251 | 4.03125 | 4 | def reverse_row(list1):
rev_list = []
for row in reversed(list1):
rev_list.append(row)
return rev_list
def main():
list1 = [[2,3,4,5],[3,5,6,7]]
answer = reverse_row(list1)
print(answer)
main()
|
5121eed830b5c0b355e4e007eed96a37b9c19936 | kdk745/Projects | /CS303E/GuessingGame.py | 1,922 | 3.875 | 4 | # File: GuessingGame.py
# Description:Will guess a number between 1 and 100 inclusive in seven attempts or less
# Student Name:Kayne Khoury
# Student UT EID:kdk745
# Course Name: CS 303E
# Unique Number: 52700
# Date Created:11/17/2014
# Date Last Modified:11/17/2014
# Begin Code
def main():
# c... |
756831b956b23541fd3c0616370acd07d39f5c26 | kdk745/Projects | /CS313E/BST_Cipher.py | 4,644 | 3.984375 | 4 | # File: BST_Cipher.py
# Description: Program that encypts and decrypts strings using a binary search tree.
# Student Name: Juanito Taveras
# Student UT EID: jmt3686
# Partner Name: Kayne Khoury
# Partner UT EID: kdk745 #76
# Course Name: CS 313E
# Unique Number: 51730
# Date Created: 4/21/2015
# Date... |
ea0fd7c5729ff632944bc1c0b02514e7e6f324d3 | kdk745/Projects | /CS313E/Mondrian.py | 4,802 | 3.515625 | 4 | # File: Mondrian.py
# Description: Draws a scenic background, random trees with fruits, and then writes poetry
# Student Name: Kayne Khoury
# Class ID number: 76
# Student UT EID: kdk745
# Course Name: CS 313E
# Unique Number: 51730
# Date Created: 3/5/2015
# Date Last Modified: 3/7/2015
import turtle... |
d23521f16ff3e7b8908c7559b531d936d0f2d814 | Belco90/smartninja-wd1 | /lesson_7/conversor.py | 626 | 4.28125 | 4 | # -*- coding: utf-8 -*-
print "Hello! This is a unit converter that converts kilometers into miles."
choice = 'yes'
while choice.lower() == "y" or choice.lower() == "yes":
print "Please enter a number of kilometers that you'd like to convert into miles. Enter only a number!"
km = raw_input("Kilometers: ")
... |
9ee7c9f8af027f112fe7a5167f1f345ecfd64fd0 | QW999/HW_V | /hw/FruitBox_class.py | 811 | 3.953125 | 4 |
class FruitBox:
def __init__(self, apples, oranges):
self.apples = apples
self.oranges = oranges
if apples != int(apples) or oranges != int(oranges):
print("Put just whole fruits!!")
elif apples > 50 or oranges > 50:
print("Full box!!")
... |
a720ea806fead738d188d9b9c7173c0cbe636431 | QW999/HW_V | /hw/Quarantine_2.py | 1,217 | 4.03125 | 4 | import datetime
class Healthy:
def __init__(self, Name):
self.ill = self.Ill()
self.curred = self.ill.Curred()
self.Name = Name
def __str__(self):
return "Name: " + str(self.Name)
def healthy(self):
return self.Name + " is healthy"
class Ill:
de... |
4f1af9b5c323d8518f9e36a5783a93219882db6f | QW999/HW_V | /wk/Encapsulation.py | 460 | 3.765625 | 4 |
class car:
def __init__(self, name, mileage):
self._name = name #protected variable
self.mileage = mileage
def description(self):
return f"The {self._name} car gives the mileage of {self.mileage}km/l"
obj = car("BMW 7-series",39.53)
#accessing protected vari... |
7c7717650f6ec16302af8fee059d7dc443029874 | YanaLaz/Unix | /LAB1-main/main.py | 875 | 3.75 | 4 | # coding=utf-8
import getpass
user = getpass.getuser()
print(str("Привет, " + user + "!"))
print('----Простеший калькулятор----'
"\n"
"\n'0' в качестве знака операции"
"\nзавершит работу программы")
while True:
s = input("Знак ('+','-','*','/'): ")
if s == '0':
break
if s in ('+', ... |
e79bddf847bd602f997de825d649b99efcf87090 | jhonry-ninja/mycode | /credmaker/rclooper.py | 2,738 | 3.578125 | 4 | #!/usr/bin/env python3
# import the csv library
# for more info., NOTE: https://docs.python.org/3/library/csv.html
import csv
# make f a file object, by reading csv_users.txt
f = open("csv_users.txt", "r")
# set i equal to 0. We're going to use this as a counter
i = 0
# Now we want to use the csv.reader() This func... |
32b38a8e2b92dd88634b749aeadbfff1cdab445b | BooneSchmucker/Techdegree-Project-1-Guessing-Game | /guessing_game.py | 1,762 | 3.859375 | 4 | import random
import sys
welcome_message = ("Welcome to GuessNumber3000! I am thinking of a number between 1 and 10. Can you guess the number?")
prompt1 = "Guess the magic number between 1 and 10! "
lower = " *** It's lower. Try again *** "
higher = " *** It's higher. Try again *** "
end = "*** That was f... |
c14b684f95244c5208d1cbf9449c56a21bddba4d | zeroWin/Python | /Core python programming(2th)/Chapter 2/2_11.py | 585 | 4.03125 | 4 | aTuple = (1,2,3,4,5)
print("(1)Sum of five num input: 1")
print("(2)Average of five num input: 2")
print("(X)Exit input: X")
choose = input("Please input:")
while choose != 'X':
if choose == '1':
sum = 0
for i in aTuple:
sum += i
print("Sum of five num is %d" % sum)
elif choose == '2':
sum = 0
for i in a... |
baea5d36b5a55ae699e7d9fb75a7397c35562c66 | SuiNom/recipePicker | /recipesWeb.py | 1,065 | 3.671875 | 4 | from flask import Flask
import random
app = Flask(__name__)
#Define Recipes as a dictionary nested in a list
##Variable - Python List of recipes
###Dictionary
####Key = Dish Name
#####Value = Python List of ingredients
recipes = [
{"Meatballs and Pasta":
["Meatballs", "Pasta", "Pasta Sauce"]},
{"Fried Chicken":
... |
33c1e602286fcfa17a16781011da87e4db0463d0 | shakeyapants/lesson1 | /get_summ.py | 145 | 3.5 | 4 | def get_summ(something, something_else):
result = str(something) + str(something_else)
return result.upper()
print(get_summ('Hello', 2)) |
92534baf9a8014d45a67e8a0b564a01e3fe83f3d | luiszz8/EDD_1S2019_P1_201700339 | /Serpiente.py | 2,932 | 3.734375 | 4 | import os
class NodoS:
def __init__(self, x, y):
self.x = x
self.y = y
self.sig = None
self.ant = None
class Serpiente:
def __init__(self):
self.inici = None
self.fin = None
self.tam = 0
self.agregarFinal(NodoS(7, 5))
self.agregarFinal(No... |
8228de49c4b5467db67cf7bdee3ae7171555807a | chauhanvishu/beat | /Q4.py | 504 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 20 18:45:12 2018
@author: aksha
"""
import time
import datetime
print ("Time in seconds since the epoch: %s" %time.time())
print ("Current date and time: " , datetime.datetime.now())
print ("Or like this: " ,datetime.datetime.now().strftime("%y-%m-%d-%H-%M"))
print (... |
9f8d5e245b1cfcc9cd19f04b773167d93226c3b3 | tdemedeiros/Udacity | /UTF8-chicago_bikeshare_pt.py | 14,595 | 3.9375 | 4 | # coding: utf-8
# Começando com os imports
import csv
import matplotlib.pyplot as plt
# Vamos ler os dados como uma lista
print("Lendo o documento...")
with open("chicago.csv", "r") as file_read:
reader = csv.reader(file_read)
data_list = list(reader)
print("Ok!")
# Vamos verificar quantas linhas nós temos
p... |
0e5872a4e8dce39d91669a466323d9e213d7292b | lubanpanda/test_startPage | /common/excel.py | 766 | 3.546875 | 4 | import xlrd
class ReadExcel():
def __init__(self,file_path,sheet_name):
self.file_path=file_path
self.sheet_name=sheet_name
def read_excel(self):
workbook=xlrd.open_workbook(self.file_path)#打开excel表,填写路径
table=workbook.sheet_by_name(self.sheet_name)#找到对应的sheet页
row_num... |
9860247cb3f9c7c43a7161ca8c03a47826cb5b96 | leej11/advent_of_code_2019 | /day4/day4.py | 1,139 | 3.703125 | 4 | test = '111111'
test2 = '223450'
test3 = '123789'
start = '264793'
stop = '803935'
def password_checker(password):
pass_score = 0
double_counter = 0
double_counter_2 = 0
double_ints = []
for i in range(1,6):
if password[i] > password[i-1]:
pass_score += 1
elif pass... |
c0cf39b1bb4c7ea79e2cd6ad7e0e19d2745d99c2 | acemarco1311/Blackjack | /play_game.py | 6,007 | 3.734375 | 4 |
# Author: Le Nguyen Thanh Toan
# Email Id: acemarco9@gmail.com
#
import blackjack
def output_player(player):
player_name = player.get_name() #name of user
player_hand = player.get_hand() #cards in user's hand
player_hand_value = player.get_hand_value() #value of each card in user's hand
alternati... |
d3196e1e63ece2fa85105e85a6864592ed06066d | darkarp/Voice-Cloning-App | /synthesis/synonyms.py | 1,718 | 3.546875 | 4 | from dataset.transcribe import transcribe
import nltk
nltk.download("wordnet")
from nltk.corpus import wordnet
def get_synonyms(word):
"""
Generates a list of synonyms for a word.
Parameters
----------
word : str
Word to find synonyms of
Returns
-------
list
List of... |
ec75e043d8ca7b769ab9b6ec412fd49a747405d2 | gansy/week1-gansiva | /1Task4.py | 138 | 3.796875 | 4 | def right_justify(b):
"""Does right justification"""
a=' '
print((70-len(b))*a+b)
b=input("Enter the character =")
right_justify(b)
|
3bb1166dd7a377ecf787707b91d38a34a5c31743 | gansy/week1-gansiva | /2Task15-1.py | 356 | 4.09375 | 4 | def first(word):
"""Prints first letter in the word"""
return word[0]
def last(word):
"""Prints last letter in the word"""
return word[-1]
def middle(word):
"""Prints middle letter based on the indices"""
return word[1:-1]
print(middle("ly"))
print(first("l"))
print(middle(" "))
print(middle(... |
f1295180a73e9f4163c4af868e1b6a4073963c22 | gansy/week1-gansiva | /2Task5.py | 290 | 4.1875 | 4 | import turtle
def polygon(t,l,n):
"""Draws a polygon"""
for i in range(n):
t.fd(l)
t.lt((360/n))
len=int(input("Input the length: "))
sides=int(input("Input sides of polygon:"))
bob=turtle.Turtle()
polygon(bob,len,sides)
turtle.mainloop()
|
3a40384eee3d4d85ce57657c43e9970c9e8ee51e | GiliardGodoi/simulations-stpg | /Studies_on_partitioning/draw.py | 4,893 | 3.765625 | 4 | import pprint as pp
import random
from collections import deque
from os import path
import math
import networkx as nx
from matplotlib import pyplot as plt
def convert_graph(graph, color='black'):
G = nx.Graph()
for v, value in graph.edges.items():
G.add_node(v)
for w, weight in value.items():
... |
cbde7a9af0e6bc288aec8e7e5dd14f27d8fcaa6b | TianrunCheng/LeetcodeSubmissions | /third-maximum-number/Accepted/6-24-2021, 12:14:59 AM/Solution.py | 1,049 | 3.84375 | 4 | // https://leetcode.com/problems/third-maximum-number
class Solution:
def thirdMax(self, nums: List[int]) -> int:
maximum = nums[0]
for k in nums:
if k > maximum:
maximum = k
second = 0
flag = True
# flag: have we found at least one secon... |
84e577499f53be6e6012f7e5471ec5cbe4e72acf | TianrunCheng/LeetcodeSubmissions | /largest-rectangle-in-histogram/Runtime Error/7-14-2021, 7:15:59 PM/Solution.py | 860 | 3.703125 | 4 | // https://leetcode.com/problems/largest-rectangle-in-histogram
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
# devide and conquer: devide from the minimum of array
def helper(start: int, end: int) -> int:
# area of the largest rectangle in [start, ... |
5d47eea70ffe64dbb6b843ff14254df975552cc8 | TianrunCheng/LeetcodeSubmissions | /perfect-squares/Accepted/6-28-2021, 4:25:44 PM/Solution.py | 1,025 | 3.578125 | 4 | // https://leetcode.com/problems/perfect-squares
from collections import deque
class Solution:
def numSquares(self, n: int) -> int:
# construct a list of all perfect squares smaller than n
squares = []
queue = deque()
# queue of all reachable numbers with "step" adding of squares
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.