blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
325c4e623b8503ef0ec256f098017b267c8e042f | maiphuong1809/nguyemaiphuong-fundamental-c4t4 | /session03/Homework/sum_b.py | 221 | 3.78125 | 4 | num = int(input("Enter a number: "))
Sum = 0
for i in range (1, num+1):
m=1
for p in range(1,i+1):
m=m*p
Sum=Sum+1/m
print("S = 1/1! + 1/2! + ... + 1/{0}{1}{2}".format(num,"! = ",Sum)) |
ef469699554b40fdcc01a86579f809c72a2d4c81 | maiphuong1809/nguyemaiphuong-fundamental-c4t4 | /session03/document/login.py | 265 | 3.578125 | 4 | import getpass
username = input("User Name:")
if username == "Maiphuong":
password = getpass.getpass()
if password == "1809":
print ("Welcome MP")
else:
print ("Incorrect password")
else:
print ("You are not the user") |
2ef1c534ba2f148c6d3c4ecef46a20ecf559702a | maiphuong1809/nguyemaiphuong-fundamental-c4t4 | /session04/btvn04.py/turtle02.py | 171 | 3.5 | 4 | from turtle import*
speed (-1)
color("blue")
for i in range (50):
for _ in range (4):
forward (20+i*4)
left (90)
right (350)
mainloop() |
870ecd7b02371c23199c478e9e553396c283cba0 | gracenng/Salam-Technica | /data_process.py | 3,172 | 3.5 | 4 | import requests
import pandas as pd
import csv
from google.cloud import bigquery
import jwt
def convert():
import PyPDF2
# creating a pdf file object
pdfFileObj = open('tax1.pdf', 'rb')
# creating a pdf reader object
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pageObj = pdfReader.getPage(0)
... |
bc57deeabb754244531d8c1f808539a32deea385 | x0rk/python-projects | /linear-undeterminate-equation.py | 431 | 3.5 | 4 | # Enter the coefficients of the linear indeterminate equation in the following format
# ax + by + c = 0
a = int(input("Enter the value of a: "))
b = int(input("Enter the value of b: "))
c = int(input("Enter the value of c: "))
n = int(input("Enter the number of solutions needed: "))
soln = []
x = 0
while n > 0:
y = ... |
6201df60093b11437ff5d8697aa337f679dfbbdc | x0rk/python-projects | /3x+1.py | 266 | 3.875 | 4 | n = int(input("Enter a number: "))
c = 0
n1 = n
while n != 1:
if n%2 == 0:
n/=2
else:
n=3*n + 1
print('\n'+n+'\n')
g = n1 if n1 > n and else n
c+=1
print("Number of Loops: ",c)
print("The greatest number attained is {}".format(g)) |
64fe2091fc3fcec1bcaf73e9c73a1d3a8669965f | x0rk/python-projects | /String_wave.py | 343 | 3.890625 | 4 | from time import sleep
str1 = input("Enter a string: ")
str1 = str1.upper()
#str1 = 'COMPUTER'
for i in range(5):
index=1
for i in str1:
print(str1[:index])
index+=1
sleep(0.1)
ind=len(str1)-1
for i in str1:
print(str1[:ind])
ind-=1
... |
b6dc25781beab01f24fc77946d4f2dbf36a74d6b | maheshhingane/HackerRank | /Algorithms/Implementation/MinumumSwaps.py | 801 | 3.796875 | 4 | """
https://www.hackerrank.com/challenges/minimum-swaps-2/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays
"""
#!/bin/python3
import math
import os
import random
import re
import sys
def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
def isSorted(arr):
retu... |
6edf756b810736d44def93847adefb86891d1173 | maheshhingane/HackerRank | /Algorithms/Implementation/Timeouts/ClimbingTheLeaderboard.py | 1,619 | 3.78125 | 4 | """
https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem
"""
import sys
def find_rank(scores, score, carry):
if len(scores) == 0:
return carry + 1
mid_index = len(scores) // 2
mid_score = scores[mid_index]
if mid_score == score:
return carry + mid_index + 1
eli... |
22e73cc81c0d6b8282d2a87348372e53cbec2082 | maheshhingane/HackerRank | /Algorithms/Implementation/2DArray.py | 970 | 3.703125 | 4 | """
https://www.hackerrank.com/challenges/2d-array/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the hourglassSum function below.
def hourglassSum(arr):
maxHourGlassSum = 0
... |
562650643b326ea605c81912aac9f8c2aea3030d | ozzi7/Hackerrank-Solutions | /Python/Regex and Parsing/validating-uid.py | 355 | 3.5625 | 4 | import re
for i in range(int(input())):
s = input().strip()
m1 = re.search(r'(?=(.*[A-Z]){2})', s)
m2 = re.search(r'(?=(.*\d){3})', s)
m3 = not re.search(r'[^a-zA-Z0-9]', s)
m4 = not re.search(r'(.)(.*\1){1}', s)
m5 = (len(s) == 10)
if (m1 and m2 and m3 and m4 and m5):
print("Valid")... |
b6460431b2fc27c7dc8ed8708ade77f8fa5457d4 | ozzi7/Hackerrank-Solutions | /Algorithms/Implementation/electronics-shop.py | 494 | 3.609375 | 4 | #!/bin/python3
import sys
import itertools
def getMoneySpent(keyboards, drives, s):
l = list(filter(lambda z : z <= s, [x+y for (x,y) in itertools.product(keyboards,drives)]))
if(len(l) > 0):
return max(l)
else:
return -1
s,n,m = input().strip().split(' ')
s,n,m = [int(s),int(n),int(m)]
k... |
b5f81b79fc0c990f44822af8bbc8f23a916eeaf8 | behrouzan/py-test | /src/001.py | 3,264 | 3.78125 | 4 | import pandas as pd
# this is a fucking test comment
# nba = pd.read_csv('files/nba_data.csv')
# print(type(nba))
# print(len(nba)) # len() is python built-in func
# print(nba.shape) # shape is an attribute of DataFrame
# The result is a tuple containing the number of rows and columns
# print(nba.head)
# print(n... |
451052f0b6fda97fb3119e1bdca69f9d7fff6957 | dkhachatrian/openmplab | /quick_stats.py | 958 | 3.84375 | 4 | import re
import sys #recognize command line args
import __future__ #in case using Python 2
def main():
""" Takes in input string of file in current directory.
Calculates average numbers and appends to end of file.
"""
if len(sys.argv) != 2:
print("Not the correct number of arguments!")
return
f_string = sys... |
820abce4f9d2ca4f8435512d9ad69873abb106b3 | Vani-start/python-learning | /while.py | 553 | 4.28125 | 4 | #while executes until condition becomes true
x=1
while x <= 10 :
print(x)
x=x+1
else:
print("when condition failes")
#While true:
# do something
#else:
# Condifion failed
#While / While Else loops - a while loop executes as long as an user-specified condition is evaluated as True; the "else" clause is opti... |
276371d9a0d71eaaa40a582f4a55c9a7e15d220f | Vani-start/python-learning | /bubble.py | 295 | 4.03125 | 4 |
def BubbleSort(arr):
n=len(arr)
for i in range(n):
print(i)
for j in range(0,n-i-1):
print(j)
print(range(0,n-i-1))
print(arr)
if arr[j]>arr[j+1]:
temp=arr[j]
arr[j]=arr[j+1]
arr[j+1]=temp
print(arr)
arr=[21,12,34,67,13,9]
BubbleSort(arr)
print(arr) |
495429537628e1b51b144775abb34d060034ac20 | Vani-start/python-learning | /convertdatatype.py | 980 | 4.125 | 4 | #Convet one datatype into otehr
int1=5
float1=5.5
int2=str(int1)
print(type(int1))
print(type(int2))
str1="78"
str2=int(str1)
print(type(str1))
print(type(str2))
str3=float(str1)
print(type(str3))
###Covert tuple to list
tup1=(1,2,3)
list1=list(tup1)
print(list1)
print(tup1)
set1=set(list1)
print(set1)
#... |
1ce19d5cb26da9746196f25e75b1e160882ecdfb | mozshen/FundammentalsOfProgramming2020 | /Set2/S2Q5/S2Q5.py | 314 | 3.9375 | 4 | n = int(input())
isPrime = True
for i in range(2, n):
if n % i == 0:
isPrime = False
break
if n == 1:
isPrime = False
if isPrime:
print('*' * n)
for i in range(n - 2):
print('*' + (' ' * (n - 2)) + '*')
print('*' * n)
else:
for i in range(n):
print('*' * n)
|
ad2a60dc45edb022f18621011eb951d489e5eb3b | PND22/PND69 | /PND69/studentclass.py | 2,050 | 3.75 | 4 | #studentclass.py
class Student:
def __init__(self,name):
self.name = name
self.exp = 0
self.lesson = 0
#Call function
#self.AddExp(10)
def Hello(self):
print('สวัสดีจร้าาาาาาา เราชื่อ{}'.format(self.name))
def Coding(self):
print('{}: กำลังเขียน coding ..'.format(self.name))
self.... |
133c52aa66c9f8570d39762fd3d48a1ae40921aa | miriban/data-structure | /BFS.py | 1,716 | 3.921875 | 4 | """
Breadth First Search Implementation
We are implementing an indirect Graph
"""
class Graph:
verticies = {}
def addVertex(self,v):
if v not in self.verticies:
self.verticies[v] = []
def addEdge(self,u,v):
if u in self.verticies and v in self.verticies:
sel... |
876792dac3431422495d8b71eb97b5faf662f201 | risabhmishra/parking_management_system | /Models/Vehicle.py | 931 | 4.34375 | 4 | class Vehicle:
"""
Vehicle Class acts as a parent base class for all types of vehicles, for instance in our case it is Car Class.
It contains a constructor method to set the registration number of the vehicle to registration_number attribute
of the class and a get method to return the value stored in re... |
1e8c82926310308f2bee8e88db6f8cd8d37fdee2 | MdAbuZehadAntu/MachineLearning | /Regression/SimpleLinearRegression/SimpleLinearRegression.py | 841 | 3.796875 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
dataset=pd.read_csv("Salary_Data.csv")
X=dataset.iloc[:,:-1].values
y=dataset.to_numpy()[:,-1]
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=0)
from sklearn.li... |
68942d5915f9c4e3817d4148908a3973d7e74b23 | ryanwolters/pythonpdftools | /PDF Reverser.py | 510 | 3.828125 | 4 | import PyPDF2 as pp
sourceName = input("Name of the file you want to reverse (without .pdf): ")
sourceObj = open(sourceName + '.pdf','rb')
pdfReader = pp.PdfFileReader(sourceObj)
pdfWriter = pp.PdfFileWriter()
numPages = pdfReader.getNumPages()
for x in range(numPages):
page = pdfReader.getPage((numPag... |
4599ac546c4b04f6ea4fe36cfd32a64db8922756 | MasterOfBrainstorming/Python2.7 | /Simple_FTP_Client_Server/server.py | 6,971 | 3.546875 | 4 | import os
import sys
import socket
import logging
#if len(sys.argv) < 2:
# print "Usage: python ftp_server.py localhost, port"
# sys.exit(1)
logging.basicConfig(filename="server_log.txt",level=logging.DEBUG)
methods = [
"LIST",
"LISTRESPONSE",
"DOWNLOAD",
... |
32f0ac37600331beea535f75ea72f357d60f372c | jiangjunjie/study | /ahoCorasick/python/AhoCorasick.py | 4,271 | 3.546875 | 4 | #!/usr/bin/env python
#coding=gbk
'''
hashmapʵACԶ֧Ϊunicodeõƥ䵥pattern
'''
import sys
import time
class Node():
def __init__(self):
self.word = None
self.fail = None
self.end = False
self.next = {}
class AhoCorasick():
def __init__(self):
self.root = Node()
def ins... |
314bf18bb3b34897553034e709cdeb76387ce6ce | shantanu609/BFS-1 | /Problem1.py | 1,556 | 3.8125 | 4 | # Time Complexity : O(n)
# Space Complexity : O(h) Space | O(n) worst case.
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Your code here along with comments explaining your approach
class Node:
def __init__(self,x):
self.val = x
self.left = No... |
4f0436db5cb69c1f7cfa05baf51f38259d49918b | david8z/project_euler_problems | /problem2.py | 917 | 4.0625 | 4 | """
Link: https://projecteuler.net/problem=2
Author: David Alarcón Segarra
----------------------------------------
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 te... |
27e8ec33ff0f380bf54428032445ab8905d3164f | detjensrobert/cs325-group-projects | /ga1/assignment1.py | 2,273 | 4.40625 | 4 | """
This file contains the template for Assignment1. You should fill the
function <majority_party_size>. The function, recieves two inputs:
(1) n: the number of delegates in the room, and
(2) same_party(int, int): a function that can be used to check if two members are
in the same party.
... |
58e59338d5d1fc79374d0ce438582c4d73185949 | Neethu-Mohan/python-project | /projects/create_dictionary.py | 1,091 | 4.15625 | 4 | """
This program receives two lists of different lengths. The first contains keys, and the second contains values.
And the program creates a dictionary from these keys and values. If the key did not have enough values, the dictionary will have the value None. If
Values that did not have enough keys will be ignored.
... |
354a3b788af8b631b14b0389896dbb3a47e0a36d | SayedBhuyan/learning-python | /list.py | 999 | 4.03125 | 4 | presents = ["Sayed", "Tareq", "Sultan", "Hassan", "Alim", "Sohel", 'Rakib'] # came on time
presents.append("Muhammad") # coming late
presents.sort()
# presents.reverse()
presents.insert(0, "Teacher") # teacher came and set before everyone else
# presents.pop(-2)
# presents.remove("Teacher") # teacher or anyone can... |
8d7f256e42b25c9e70abb0d9a8f96ddddf15cce1 | SayedBhuyan/learning-python | /userInput.py | 230 | 3.71875 | 4 | name = input("Enter student name: ")
age = input("Enter student age: ")
gpa = input("Enter student GPA: ")
print("Student Information")
print("-------------------")
print("Name: " + name)
print("Age: " + age)
print("GPA: " + gpa) |
a99612c8ed99a9d0596c7a9f342e8831c21d0b63 | SayedBhuyan/learning-python | /if else.py | 781 | 4.1875 | 4 | #mark = int(input("Enter Mark: "))
# if else
mark = 85
if mark >= 80:
print("A+")
elif mark >= 70:
print("A")
elif mark >= 60:
print("A-")
elif mark >= 50:
print("B+")
elif mark >= 40:
print("B")
elif mark >= 33:
print("B-")
else:
print("Fail")
'''
if (mark % 2) == 0:
print("Even")
el... |
d6745c80fffeaf847daffb8c6ead53f2bec67b9c | SayedBhuyan/learning-python | /some range math.py | 130 | 4.125 | 4 | # Factorial n!
n = int(input("Enter factorial number: "))
sum = 1
for x in range(1, n + 1, 1) :
sum = sum * x
print(sum)
|
488675687a2660c01e9fd7d707bdf212f94abb62 | NM20XX/Python-Data-Visualization | /Simple_line_graph_squares.py | 576 | 4.34375 | 4 | #Plotting a simple line graph
#Python 3.7.0
#matplotlib is a tool, mathematical plotting library
#pyplot is a module
#pip install matplotlib
import matplotlib.pyplot as plt
input_values = [1,2,3,4,5]
squares = [1,4,9,16,25]
plt.plot(input_values, squares, linewidth = 5) #linewidth controls the thickness of the lin... |
83b59d267f64a9ea622498ffa254021848763bb2 | R1gp4/LearnX | /6001x/ansguess.py | 792 | 4.09375 | 4 | print("Please think of a number between 0 and 100!")
high = 100
low = 0
num_guesses = 0
flag = True
while flag == True:
guess = (high + low)/2.0
print('Is your secret number', int(guess), ' ?')
print("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to ind... |
2bfe26f13d9f1d92ea90d94a379ac0d805b342e2 | saelbakr/python-challenge | /PyFinances/main.py | 2,280 | 3.609375 | 4 | import os
import csv
csvpath = os.path.join("Finances.csv")
Date = []
Profits_Losses = []
with open(csvpath, encoding="utf8") as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
csv_header = next(csvreader)
for row in csvreader:
Date.append(row[1])
Profits_Losses.append(int(row[... |
74afc1b709da9c42b3b44766dc6738baefa692b2 | tanker0212/dailyCoding | /src/dc_181112/Solution.py | 887 | 3.53125 | 4 | NUM_LEN = 3;
def solution(baseball):
answer = 0
for i in range(123, 988):
if dup_check(i):
point = 0
for guess in baseball:
if (guess[1], guess[2]) == point_check(i, guess[0]):
point += 1
if point == len(baseball):
... |
35af5afe90a21ccac83503ccd6dd7cfa7fa4889f | josue-avila/OTS-ATP1 | /products.py | 9,049 | 3.875 | 4 | import os
from categories import Categories
class Product:
name: str
description: str
price: float
weigth: float
length: float
heigth: float
width: float
list_products: list = []
list_product: list = ['','','']
categories: list = []
def menu(self) -> int:
... |
b83f8959434d6ad11c371a680a742e0f394c0c8a | Patrick5455/InterviewPractice | /leetCode/PythonSolutions/27.py | 195 | 3.6875 | 4 | def removeElement(nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
m_set = set(nums)
return len(m_set)
test = [3,3]
print(removeElement(test, 3)) |
a9b49b0f5fa13d3392bdbaefb26416a028adf5e9 | Patrick5455/InterviewPractice | /leetCode/PythonSolutions/temp.py | 2,294 | 3.515625 | 4 | class Solution:
def spiralOrder(self, matrix):
if matrix is None or len(matrix) == 0:
return []
else:
self.m = matrix
curDir = "right"
visited = [[False for i in range(len(matrix[0]))] for j in range(len(matrix))]
totalCell = 0
for r in matr... |
e5d0634de86cac0cd99e2f395b85327c441f907f | Patrick5455/InterviewPractice | /leetCode/PythonSolutions/BasicIO.py | 1,039 | 3.65625 | 4 |
def file_io():
r_text = open("wuhao4u.txt", 'r')
for line in r_text:
print(line)
r_text.close()
with open("wuhao4u.txt", 'r') as r_file:
with open("test.txt", 'w') as w_file:
for line in r_file:
w_file.write(line.strip())
def console_io():
m_str = in... |
d1016e22ac19862a11837a2e5a01c55c6a8b12b3 | Patrick5455/InterviewPractice | /nineChapters/SearchForARange.py | 2,314 | 3.5 | 4 | class Solution:
"""
@param A : a list of integers
@param target : an integer to be searched
@return : a list of length 2, [index1, index2]
"""
def searchRange(self, A, target):
if len(A) == 0:
return [-1, -1]
start, end = 0, len(A) - 1
while start + 1 < end:
... |
df93b766db65419e0d4d70867a8dcaad28c83cf1 | Patrick5455/InterviewPractice | /reverseString.py | 257 | 3.6875 | 4 | def reverseWords(s):
temp = []
counter = 0
res = ''
s = s.split()
for i in s:
counter = counter + 1
temp.append(i)
while counter > 0:
counter = counter - 1
res = res + temp[counter] + ' '
return res.strip()
reverseWords("the sky is blue") |
12f4f9d67668cb09028421727ff1df56ebc94cab | tristaaa/learnpy | /professorTrial.py | 771 | 3.90625 | 4 | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
#
from MITPersonTrial import MITPerson
class Professor(MITPerson):
def __init__(self, name, department):
MITPerson.__init__(self, name)
self.department = department
def speak(self, utterance):
new = 'In course ' + self.department + ' we sa... |
859feadf6786c485248a9b30b5fca937543a81a5 | tristaaa/learnpy | /getLowestPaymentBisection.py | 1,221 | 3.921875 | 4 | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
balance = 320000
annualInterestRate = 0.2
def increment():
def getLowestPaymentBisection(balance, annualInterestRate):
'''
using bisection search
return: the lowest payment to pay off the balance within 12 months
will be the multiple of $0.01
... |
9ed2d0f9f15fde3e123ea8f30c2ffa714db1460a | tristaaa/learnpy | /getRemainingBalance.py | 819 | 4.125 | 4 | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
balance = 42
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
def getMonthlyBalance(balance, annualInterestRate, monthlyPaymentRate):
'''
return: the remaining balance at the end of the month
'''
minimalPayment = balance * monthlyPaymentRate
monthl... |
6df041ded350202d4e74f98a104fd3470e21683d | tristaaa/learnpy | /bisectionSearch_3.py | 910 | 4.46875 | 4 | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
# use bisection search to guess the secret number
# the user thinks of an integer [0,100).
# The computer makes guesses, and you give it input
# - is its guess too high or too low?
# Using bisection search, the computer will guess the user's secret number
low = 0
high ... |
478b3a83db292657743bcf383fff15d80a75514a | MAKMoiz23/DSA-codes | /scape_goat_tree_19B-028-069-CS.py | 9,569 | 3.921875 | 4 | import math
class TreeNode:
def __init__(self, data, parent=None, left=None, right=None):
self.data = data
self.parent = parent
self.left = left
self.right = right
class ScapegoatTree:
def __init__(self, root=None):
self.scape_goat = None
self.root = r... |
10d1145cc06d7213e50f70feea379dff8aa968c7 | sashaneo/tkinter | /1.py | 1,438 | 3.75 | 4 | import builtins
import tkinter as tk
def calculate_discount_percentage(total):
discount = 0
if total >= 100:
discount = 20
elif total > 0 and total < 100:
discount = 10
return discount
def calculate_discount(total):
discount_percentage = calculate_discount_percentage(total)
di... |
bcb7483e42583c33679376039e2665996125dd88 | uzuran/AutomaticBoringStuff | /Loops/fiveTimes.py | 289 | 4.0625 | 4 | # We use for i in range to print Jimmy print five times
#print('My name is')
#for i in range(5):
# print('Jimmy Five times(' + str(i) + ')')
# Here we used while to print the same thing
print('My name is')
i = 0
while i < 5:
print('Jimmy Five times(' + str(i) + ')')
i = i + 1 |
3be3d138268f4ebd54c28b119598324e76ab913a | uzuran/AutomaticBoringStuff | /Listst/list_To_str.py | 174 | 3.78125 | 4 | def list_to_string(some_of_list):
str1 = ', '
return (str1.join(some_of_list))
some_of_list = ['apples','bananas','tofu','cats']
print(list_to_string(some_of_list)) |
9626b538db9a129e0de190538bb381a2222cb31c | uzuran/AutomaticBoringStuff | /TestDrive/e_Shop_try/e_Shop.py | 2,748 | 3.859375 | 4 | # Python version 3.9.2
# Practice with some loops,dictionaries and json
import json
import os.path
import sys
storage = {"CPU": 10, "GPU": 10, "HDD": 10, "SSD": 10, "MB": 10,
"RAM": 10, "PSU": 10, "CASE": 10}
addToStock = {"CPU": 100, "GPU": 100, "HDD": 100, "SSD": 100, "MB": 100,
"RAM": 1... |
bed49525959742ff33513021cd308f5b78ed3b8f | willemhscott/CSCI-3104 | /homework7.py | 1,993 | 3.828125 | 4 |
class Graph():
def __init__(self, adjacency_matrix):
"""
Graph initialized with a weighted adjacency matrix
Attributes
----------
adjacency_matrix : 2D array
non-negative integers where adjacency_matrix[i][j] is the weight of the edge i to... |
87b1994cd10f98420c37a92626af829ee21b0afc | ynonp/gitlab-demos | /28-generators/03_comprehension.py | 194 | 3.625 | 4 | import itertools as it
def fib():
x, y = 1, 1
while True:
yield x
x, y = y, x + y
sqr_fib = (x * x for x in fib())
for val in it.islice(sqr_fib, 10):
print(val)
|
78ab19aa0d8932af345b7c8b99e1456a3945945d | Nick-Feldman/PythonExamples | /exercise6_9.py | 162 | 3.828125 | 4 | #Please write a program which prints all permutations of [1,2,3]
from itertools import permutations
perm = permutations([1,2,3])
print(len(list(perm)))
|
975470a53911f363dc8c39e40f9702b356d7551e | Nick-Feldman/PythonExamples | /exercise5_15.py | 169 | 3.75 | 4 | '''
Please write a program to shuffle and print the list [3,6,7,8].
'''
from random import shuffle
numbers = [3, 6, 7, 8]
shuffle(numbers)
print(numbers)
|
089215ea56d457043a141725898e84b5c78d4a02 | Nick-Feldman/PythonExamples | /exercise5_6.py | 168 | 3.78125 | 4 | '''
Please generate a random float where the value is between 5 and 95 using a Python math module.
'''
import random
num = random.uniform(5, 95)
print(num)
|
b404567086112e97274ef5f8ee4950b7241020f7 | Nick-Feldman/PythonExamples | /exercise5_11.py | 418 | 3.703125 | 4 | '''
Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7, between 1 and
1000 inclusive.
'''
import random
li = []
def ranGenerator():
for i in range(5):
x = 1
while not(x % 5 == 0 and x % 7 == 0):
x = random.randint(1, 1000)
... |
e42df4e0004243511bde5d9d4bf50f6250ab5394 | Nick-Feldman/PythonExamples | /exercise6_2.py | 105 | 3.640625 | 4 | theList = [12, 24, 35, 24, 88, 120, 155]
newList = [x for x in theList if x != 24]
print(newList)
|
32590a15e47f9ef40272430aa7090a75362699a6 | isradesu/israel-poo-info-p7 | /atividades/presenca/atividade2linklist.py | 1,709 | 4.03125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self._size = 0
def append(self, elem):
if self.head:
# inserção quando a lista j tem elemt
pointer = self.head
... |
86df8e8b9a2353a6dfcea830f6a1d7bb2bf5e0ed | jsterner73/MITx---6.00.1x | /PayingDebtOffInAYear.py | 532 | 3.671875 | 4 | balance = 3926
annualInterestRate = 0.2
lowestPayment = 10
while True:
monthlyInterestRate = annualInterestRate / 12.0
totalPaid = 0
previousBalance = balance
for x in range(1,13):
monthlyUnpaidBalance = previousBalance - lowestPayment
previousBalance = monthlyUnpaidBalance + (mo... |
83300d7433cdb8e4c83731394a8fa5f4fddb1c06 | anagorko/csg | /src/constraint.py | 1,062 | 3.734375 | 4 | #!/usr/bin/env python
class Constraint(object):
LT = 1
GT = 2
EQ = 3
def __init__(self):
self.type = Constraint.LT
self.bound = 0.0
self.var = {}
def addVariable(self, var, val):
# TODO: check if var exists and adjust accordingly
self.var[var] = val... |
bcd481d7bfd7c667f806a65f5cdbe14f04c06205 | sp00ks-L/LeetCode-Problems | /minStack.py | 669 | 3.640625 | 4 | from collections import deque
class MinStack:
'''
Design a stack that supports push, pop, top and get_min in constant time
'''
def __init__(self):
"""
Initialise data structure
Originally had stack=deque() as default arg but it threw wrong answers during submission
"""... |
19740d81e52aa421501c411105bbda801f613768 | sp00ks-L/LeetCode-Problems | /jumpGame.py | 512 | 3.9375 | 4 | class BackTracking:
def canJump(self, pos, nums):
'''
Where each int in nums[] is the maximum jump length
is it possible to reach the last index
'''
n = len(nums)
if pos == n - 1:
return True
farthestJump = min(pos + nums[pos], n - 1)
for... |
eb37a9e228f492ae7055c0945cb7a37d7c280ac5 | sp00ks-L/LeetCode-Problems | /moveZeroes.py | 530 | 3.703125 | 4 | class Solution:
def move_zeros(self, nums):
"""
Takes an array of ints and moves zeroes
to the end of the array while maintaining the order of the remaining ints
:param nums: List[int] [0, 1, 0, 3, 12]
:return: List[int] [1, 3, 12, 0, 0]
"""
n = ... |
3fe52541a718c44adf355ee92c4695128e36eabc | tachyon777/PAST | /PAST_1/D.py | 518 | 3.71875 | 4 | #第一回 アルゴリズム実技検定
#D
import sys
from collections import defaultdict
dic1 = defaultdict(int)
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0
n = int(readline())
lst1 = []
for i in range(n):
dic1[int(readline())] += 1
ans = [0,0]
flag = 0
for i in range(1,n+1):
if dic1[i]... |
682648dfae59da573cdd3a221eba8acb592a44f8 | tachyon777/PAST | /PAST_3/L_short.py | 2,286 | 3.515625 | 4 | #第三回 アルゴリズム実技検定
#L(書き直し)
"""
優先度付きキューのリストを3つ用意することでこの問題は解くことができる。
1.手前から1個だけ見たとき(a=1)のheap(hp1)
2.手前から2個見たとき(a=2)のheap(hp2)
3.hp1から使用されたものであって、hp2にはまだあるもの(hpres)
もう一つ、以下のヒープがあってもよいが、無いほうが簡単のため省略
(4.hp2から使用されたものであって、hp1にはまだあるもの)
場合分けをしっかり考えないと、辻褄が合わなくなるので注意。
"""
import sys
import heapq
readline = sys.stdi... |
f8e7e90a9dd5fb877b4374e970831c9344cd77c8 | tachyon777/PAST | /PAST_1/L.py | 2,398 | 3.546875 | 4 | #第一回 アルゴリズム実技検定
#L
"""
最小全域木
但し、達成すれば良いのは大きい塔のみ。
よって、各小さい塔を使う/使わないをbit全探索して、O(2**5)
全体のコストの最小値が答え。
各プリム法を用いた探索時間はO(ElogV)なので、
E=35**2,V=35として全体は
O(2**m*((n+m)**2)*log(n+m))となる
"""
import sys
import math
from copy import deepcopy
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0
... |
141ef23be3dc60cf8f7fd5dcbdacbc64722a0d0d | EduGame3/Experiment | /1.py | 260 | 4 | 4 | print('COMPARADOR DE NÚMEROS')
a = float(input('Escriba un número: ')) #¿cómo hacer para que acepte el 1/2?
b = float(input('Escriba otro número: '))
if (a < b):
print("hola")
elif (a > b):
print("adios")
else:
print('Los dos números son iguales')
|
39a54895a5bca11af5dd898533334de559fa0840 | MarineJoker/AlgorithmQIUZHAO | /Week_01/min-stack.py | 844 | 4 | 4 | class MinStack:
# 线性的话就要利用多一个栈去存当前栈内最小值
# 由于栈先进后出的特性栈中每个元素可以用作保存从自身到内部的那个阶段的状态
def __init__(self):
# self.index = 0
self.list = []
self.heap = [float('inf')]
"""
initialize your data structure here.
"""
def push(self, x: int) -> None:
self.list.a... |
67419b66475d1d64d889f3c1a757494556307dcc | VoraciousFour/VorDiff | /VorDiff/nodes/scalar.py | 6,417 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 15 13:09:28 2019
@author: weiruchen
"""
import numpy as np
class Scalar():
"""
Implements the interface for user defined variables, which is single value in this case.
So the scalar objects have a single user defined value (or it ... |
6aadd7fb383338cf30be946ec7b1db91e278f990 | AnnapurnaThakur/python_code | /anu2.py | 63 | 3.625 | 4 | a=input("enter your number :")
print(a)
print("you enter :",a)
|
b2bd2562584bc6c4966ea227428ff82a014d633b | AnnapurnaThakur/python_code | /bookS/ch2/bs2.py | 138 | 3.75 | 4 | my_dict={}
my_dict[(1,2,4)]=8
my_dict[(4,2,1)]=10
my_dict[(1,2)]=12
sum=0
for k in my_dict:
sum+=my_dict[k]
print(sum)
print(my_dict) |
25f09a2e54803140fcadac4daeb38572a232954f | AnnapurnaThakur/python_code | /All projects/anu15.py | 634 | 3.96875 | 4 | #nested for loop
sum=0
for i in range (1,6):
i2=str(i)
x1=input("enter the marks of subject number " + i2 +" : " )
x=int(x1)
if x==45:
print("pass")
elif x<45:
print("fail")
else :
print("pass")
sum=sum+x
print("the total value is :" , sum)
c=sum
if c >280 and c<32... |
0dc00b065c4e8460cb7e85db60d3bfea2189803a | AnnapurnaThakur/python_code | /anubreak19.py | 600 | 4.3125 | 4 | # for x in range (1,5):
# for i in range(1,5):
# if i==3:
# print("Sorry")
# print("loop2")
# break
# print("loop1")
# print("end")
####2nd example:
for x in range (1,5):
for i in range(1,5):
if i==3:
print("Sorry")
break
print("loop2... |
3b4184877f79b34315fb843b3faeb4cc9a27ecd2 | AnnapurnaThakur/python_code | /Nested_forLoop/nested_forloop10.py | 277 | 3.96875 | 4 | a=int(input("Enter a number : "))
for i in range(a,1,-1):
for j in range(1,i+1):
print(" " , end="")
for k in range(i-1,a,1):
print(k , end="")
print()
# Enter a number : 7
# 6
# 56
# 456
# 3456
# 23456
# 123456 |
9f708afd701c2a1d7a0b6ed36606d30b5924e8ca | AnnapurnaThakur/python_code | /Modules/str_join1.py | 260 | 3.796875 | 4 | # a="/".join("138")
# print(a)
a=int(input("Your date : "))
b=int(input("Your date : "))
for a in range (a,b+1):
d=str(a)
m="9"
y="2020"
a1="/".join((d,m,y))
print(a1)
# if a>30:
# print("error")
# else:
# print()
|
830687650d4b117cf56618de30d2b62926d37835 | AnnapurnaThakur/python_code | /anu20.py | 1,020 | 4.0625 | 4 | # a=int(input("Enter a number : "))
# for i in range (0,6):
# for j in range(0,i):
# print(j)
# print(i)
# a=int(input("Enter a number : "))
# for i in range(1,a+1,2):
# for j in range(1,i+2,2):
# print(j, end=" ")
# print()
# a=int(input("Enter a number : "))
# for i in range(0,a+1):... |
63d9745d1c449ac7c2f945516848d35d62d2b70d | AnnapurnaThakur/python_code | /List/list6.py | 462 | 3.609375 | 4 | # a=["Anu", "Anjali", "Ankita", "Sumit", "Sanjay"]
# print(a)
# print()
# b=["Thakur", "Sharma", "Singh", "Sinha", "Roy"]
# # add=(name[0])+(t[0]),(name[2])+(t[2])
# # print(add)
# add=(a[0])+(b[0]),(a[2])+(b[2])
# print(add)
# c=[]
# d=a[0:]+b
# print(d)
a=[1, 2, 3, 4]
print(a)
print()
b=[6,8,9,8]
[]
print(b)
for ... |
5bc2cd695264159aa44814e38a6e1f5db14e0584 | AnnapurnaThakur/python_code | /All projects/anubating.py | 713 | 3.796875 | 4 | import sys
while True:
a=int(input("How many amount you want add : "))
c=0
while True:
if a>0:
b=int(input("how many amount you want invest : "))
if a>=b:
a=a-b
print("your aval. bal : ",a)
c=c+b
... |
29240ab6e69652738d220283183acb439879ada0 | utsav-195/python-assignment | /problem1.py | 1,003 | 3.875 | 4 | def validate(password):
condition = [0, 0, 0, 0, 1] # for testing all the four criterias
for i in password:
if ord(i) >= ord('A') and ord(i) <= ord('Z'): # checking for capital alphabet
condition[0] = 1
elif ord(i) >= ord('a') and ord(i) <= ord('z'): # charcking for small alp... |
f1c745b6786930254c938f7be7afbab341253872 | roguishmountain/dailyprogrammer | /challenge228.py | 536 | 3.75 | 4 | lwords = ['billowy', 'biopsy', 'chinos', 'defaced', 'chintz', 'sponged', 'bijoux', 'abhors', 'fiddle', 'begins', 'chimps', 'wronged']
for word in range(len(lwords)):
bInOrder = True
bRInOrder = True
for char in range(len(lwords[word])-1):
if lwords[word][char] > lwords[word][char+1]:
bInOrder = False
elif ... |
6e39b7628ea2e62d8a0da616c94ccb8195d73cc6 | MalachiBlackburn/CSC121new | /functions.py | 1,597 | 4.0625 | 4 | def addition():
first=int(input("Enter your first number: "))
second=int(input("Enter your second number: "))
add=first+second
print(first, "+", second, "=", add)
def subtraction():
first=int(input("Enter your first number: "))
second=int(input("Enter your second number: "))
sub=fi... |
ed0df19d54dd286b6996146454fa108b3d73adf3 | tinayating/Leetcode | /Python/121. Best Time to Buy and Sell Stock.py | 465 | 3.53125 | 4 | import math
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) == 0:
return 0
minPrice, maxProfit = prices[0], -math.inf
for p in prices:
minPrice = min(p, minPrice)... |
195d83bbefa65c664cbbbc9446984ba007e3d81c | valerio-oliveira/edx_cd50_python_javascript | /03_python/loops.py | 78 | 3.734375 | 4 | # a basic loop
#for i in [0,1,2,3,4,5]:
for i in range(10,15):
print (i)
|
46af2af08a021f4a646df6debfe9a6fd28843d0d | awstown/PHYS200 | /Chapter12/Chapter12.py | 1,983 | 4.0625 | 4 | # -*- coding: utf-8 -*-
# Chapter 12 Exercises: 12.1, 12.2, 12.3
# Dwight Townsend
# Phys 400 - Spring 2012 - Cal Poly Physics
# imports
import random
# Exerise 12.1
def sumall(*args):
return sum(args)
print sumall(1, 3, 5, 7, 9)
# Exercise 12.2
def sort_by_length(words):
t = []
for word in words:
... |
537ddca25824fd995727cbb026fecefa5bdcaf8b | wkomari/Lab_Python_04 | /data_structures.py | 1,383 | 4.40625 | 4 | #lab 04
# example 1a
groceries = ['bananas','strawberries','apples','bread']
groceries.append('champagne')
print groceries
# example1b
groceries = ['bananas','strawberries','apples','bread']
groceries.append('champagne') # add champagne to the list of groceries
groceries.remove('bread') # remove bread from the lis... |
39c80f04366d2381fa04b4b851cca2ba58a1cb26 | Only8Bytes/Python-Programs | /Final Project.py | 1,837 | 3.703125 | 4 | import operator
def palindrome(a):
if str(a) == str(a)[::-1]:
return "yes"
return "no"
def nearPrime(a):
val = 0
for i in range(2, int(a) - 1):
if (int(a)/i) % 1 == 0 and int(a)/i != i:
val += 1
if val > 2:
return "no"
return "y... |
566a189b7b5fff577335764813be64f9dabfaaee | jayson-s/csci1030u | /Test1_Question4.py | 278 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 19 11:12:52 2017
@author: Jayson
"""
def drawParallelogram(numRows, numCols):
for rows in range(numRows, 0, -1):
print(' ' * (numRows - rows) + '*' * (numRows))
drawParallelogram(10, 8) |
3c4f2f635ffb56ddec52a1ea4b0fb59fc9dafad5 | jayson-s/csci1030u | /Test2_Question1a.py | 769 | 3.796875 | 4 | #Name: Jayson Sandhu
#Student ID: 100659589
#Question 1a
import math
class Rectangle:
def __init__(self, width, length):
self.width = width
self.length = length
def getLength(self):
return self.length
def getWidth(self):
return self.width
def getArea(self)... |
fcd2821ec8109d3270d9c73e4c06ace969bb7782 | jayson-s/csci1030u | /Jayson_Lab6.py | 5,276 | 3.921875 | 4 | #Jayson Sandhu, 100659589
#Declare Variables and Initialize with values
partyNames = ['Krogg', 'Glinda', 'Geoffrey']
partyHP = [180, 120, 150]
partyAttack = [20, 5, 15]
partyDefense = [20, 20, 15]
partyDead = [False, False, False]
bossAttack = 25
bossDefense = 25
bossHP = 500
round = 1
class Charact... |
fcbe70e27eaba61f35abb918ffcb7cc55bd11066 | nhan1361992/python | /helloworld.py | 137 | 3.671875 | 4 | print ("begin")
arrs = []
for i in range(20,35) :
if ((i%7 == 0) and (i%5 != 0)) :
arrs.append(str(i))
print(','.join(arrs)) |
84e31e9c440bdcc0b6e101ee8739a721f388ce07 | GurmanBhullar/hactoberfest-Projects-2020 | /Hackerrank-Python/designerdoormat.py | 512 | 3.890625 | 4 | # Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications:
# Mat size must be X. ( is an odd natural number, and is times .)
# The design should have 'WELCOME' written in the center.
# The design pattern should only use |, . and - characters.
n, ... |
555913911bc903f7d407f39009ac136e3e281f72 | GurmanBhullar/hactoberfest-Projects-2020 | /Hackerrank-Python/Find angle MBC.py | 210 | 3.96875 | 4 | from math import acos, degrees, sqrt
AB = int(input())
BC = int(input())
AC = sqrt(AB*AB + BC*BC)
BM = AC / 2
angel = round(degrees(acos((BC * BC + BM * BM - BM * BM) / (2.0 * BM * BC))))
print(str(angel)+'°') |
075c6e5733adf3dec09c3337f42806a51ed524ad | mohamed-minawi/KNN-LLS | /KNN.py | 1,310 | 3.84375 | 4 | import numpy as np
class KNN(object):
def __init__(self):
pass
def train(self, Data, Label):
""" X is N x D where each row is an example. Y is 1-dimension of size N """
# the nearest neighbor classifier simply remembers all the training data
self.train_data = Data
self.... |
db7b6be5a8c25fff421436696ad1d332fa367a66 | CamiloSaboA-csv/problemas_HackerRank | /Strings_Making_Anagrams.py | 352 | 3.609375 | 4 | def makeAnagram(a, b):
# Write your code here
from collections import Counter
a,b=list(sorted(a)),list(sorted(b))
a_count=Counter(a)
b_count=Counter(b)
x=((b_count-a_count)+(a_count-b_count)).values()
x=sum(x)
return x
a,b= 'faacrxzwscanmligyxyvym','jaaxwtrhvujlmrpdoqbisbwhmgpm... |
262ec8a9fc2241422d79720605e903e873c25d4e | BLOODMAGEBURT/exercise100 | /data-structure/sort-search/5.9.插入排序.py | 1,522 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: 5.9.插入排序
Description :
Author : Administrator
date: 2019/10/12 0012
-------------------------------------------------
Change Activity:
2019/10/12 0012:
--------------------------... |
b1ab6571086c0867dabdfee9970348aee716dbe5 | BLOODMAGEBURT/exercise100 | /exercise/exercise5.py | 532 | 3.9375 | 4 | # -*- coding: utf-8 -*-
def sort_method(alist):
"""
给一个list排序,从小到大
:param alist:
:return:
"""
assert isinstance(alist, list)
new_list = sorted(alist)
return new_list
if __name__ == '__main__':
print(sort_method([2, 7, 5, 10, 4]))
"""
按学生年龄大小排队,从小到大
"""
students =... |
3fb4a522861fca51b2f54d48c9cc9c28120280aa | BLOODMAGEBURT/exercise100 | /exercise/exercise12.py | 988 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: exercise12
Description :
Author : burt
date: 2018/11/7
-------------------------------------------------
Change Activity:
2018/11/7:
---------------------------------------------... |
4712a8abf07cb2927fbb8695e3764f0590e87dd9 | BLOODMAGEBURT/exercise100 | /exercise/exercise7.py | 583 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: exercise7
Description :
Author : burt
date: 2018/11/6
-------------------------------------------------
Change Activity:
2018/11/6:
----------------------------------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.