blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
68195f3174efafe1c753778fccdad78ad6fd21ca | ungtsuhan/data-structures-and-algorithms | /Algorithms/Sorting/SelectionSort.py | 939 | 4.34375 | 4 | def selectionsort(unsorted_list):
print(unsorted_list)
# iterating the whole unsorted list
for i in range(len(unsorted_list)):
# keep track of the index of minimum value, so that we can move it to sorted size
smallest_index = i
for j in range(i+1, len(unso... |
909589506e76b65ca6bc1f1488defe528376b7bd | bbkregmi/python-learning | /hangman/hangman.py | 2,884 | 3.828125 | 4 | from __future__ import print_function
from random import randint
randomshades = [
"You are a few hundred years too young to take on this challenge",
"You lost! But don't feel bad. There are many people who have no talent",
"Sorry you lost. Maybe you should take a break. You might sprain your br... |
a33001e71f08cb090fdc23c51bdc17c0372e362c | chetho/python-learning | /hackerrank/Interview Preparation Kit/Warm-up Challenges/3.py | 981 | 3.765625 | 4 | #!/bin/python3
# Jumping on the Clouds
import math
import os
import random
import re
import sys
import pdb
# Complete the jumpingOnClouds function below.
def jumpingOnClouds(c):
counter = 0
i,j = 0,1
while (j < n):
if (j == n - 1) and c[j] != 1:
counter += 1
return counter
... |
5b2a251f8965c9be9b62ee41794b2d5d54a213ff | concretesteelbond/python-4.2 | /problem_4.2.py | 304 | 3.5 | 4 | import random
import statistics
numList = []
random.seed(150)
for i in range(0,25):
numList.append(round(100*random.random(),1))
def problem4_2(numList):
""" Compute the mean and standard deviation of a list of floats """
print(statistics.mean(numList))
print(statistics.stdev(numList))
|
b67dc4d0c879a645b5bca36cbf87dd6ce663ce1b | TuftsVALT/snowcat | /tools/csv_to_d3m.py | 2,232 | 3.515625 | 4 | import sys
import os
import json
import pandas as pd
ARGS = sys.argv[1:]
if (len(ARGS) < 2):
print("This script converts single csv files (with headers) into D3M datasets.")
print("If no output folder is provided, the dataset name is used.")
print("Usage: <input csv><dataset name>[<output folder>]")
s... |
b51c44618813b1d9c2033d4df445ecd5691f57b7 | i-am-Shuvro/Project-GS-4354- | /Main File.py | 8,972 | 3.96875 | 4 | def greet(str):
name1 = input("[N.B: Enter your name to start the program.] \n\t* First Name: ")
name2 = input("\t* Last Name: ")
return "Hello, " + str(name1) + " " + str(name2) + "! Welcome to this program, sir!"
print(greet(str))
print("This program helps you with some information on tax-rate on... |
4018ac42ce1d681945482d29d820c6adc8c1bb5b | mlmldata2017/course-notes | /scripts/convert.py | 452 | 3.875 | 4 | #!/usr/bin/env python3
'''class demonstration'''
def temp_f2c(f):
''' This function converts Fahrenheit to Celcius
Input: temperature in degrees F
Output: Celcius
'''
c = (f - 32.0)*(5.0/9.0)
return(c)
def temp_c2f(c):
''' This function converts C to F
Input: temperature in degrees C
Output: F
'''
f = c*... |
a769cfc4f1120c65afdfd3dd9e2ba377fe0a9c0f | SwitchTLL/pyt_int_course | /Lesson4/List_tuple_dictionary_set.py | 1,513 | 3.953125 | 4 | # Тип скобок для этих комманд критичен!
# LIST[] - изменяемый
# TUPLE() - не изменяемый
# DICT{} -
# SET{} - frozen
empty_string = ""
print(type(empty_string))
empty_list = []
print(type(empty_list)) # empty_list = [1234, 1234.56, "some string", True, None, [1234,"new_string", False]]
# print(some_list)
# print(som... |
c813cd93d6906dc201fa7deaf315fa27a45497b7 | SwitchTLL/pyt_int_course | /lesson5/ex5_2.py | 671 | 3.8125 | 4 | # counter = 0
# while counter <1000001: # while False: - exits without result / while True - forever loop
# print("I can't stop!!! " + str(counter) + ' times')
# counter += 1
condition = True
counter = 3 # Try's counter for 3 times
while condition and counter > 0:
user_input = input('Please enter your... |
303ba0e583f0e00b1fd4e57ecf661a8da804845d | SwitchTLL/pyt_int_course | /lesson6/ex6_1.py | 1,183 | 3.671875 | 4 | #id_code = input("Please enter your ID code: ")
#1, 2, 3, 4, 5, 6, 7, 8, 9, 1,
#3, 4, 5, 6, 7, 8, 9, 1, 2, 3,
#result = 1 * int(id_code[0] + 2 * int(id_code[1]))
# or method
id_code = input('Please enter you EE ID code: ')
def check_id(id_code)
def count_check_number(id_code, chk_list):
result = 0
... |
5e8968e0d3e2f64c921f0054f993734ffe7f2e22 | artisb45/PythonCourse2017 | /Exercise_2/random_sorted.py | 116 | 3.671875 | 4 | import numpy as np
a = np.random.rand(5, 5)
print(a.reshape(5,5))
a = a[a[:, 1].argsort()]
print(a.reshape(5, 5))
|
67cba6077c4baf1f725c40271d62922afa36e453 | artisb45/PythonCourse2017 | /Exercise_2/inverse_matrix.py | 202 | 3.671875 | 4 | import numpy as np
print('Enter n:')
n = int(input());
a = np.random.rand(n,n)
print('\nGenerated matrix:')
print(a.reshape(n,n))
a = np.linalg.inv(a)
print('\nInverse matrix:')
print(a.reshape(n,n)) |
8fe25f9556cee566ed758f2e0fb0dbf48a2c4151 | artisb45/PythonCourse2017 | /Exercise_2/matrix_eig.py | 267 | 3.515625 | 4 | import numpy as np
print('Enter n:')
N = int(input())
A = np.random.randint(0, 2*N, N**2).reshape(N, N)
print('\nGenerated matrix:')
print(A)
e_vals, e_vecs = np.linalg.eig(A)
print('Matrix eigenvalues:')
print(e_vals)
print('Matrix eigenvectors:')
print(e_vecs)
|
8543dd6427c887eaa1ce82d88a57782a95fb224f | smj007/Basic-Classification-and-Regression | /Breast Cancer Identification - Coursera Method of Regression + Normal Method.py | 5,772 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 06:17:20 2020
@author: saimi
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv("data.csv")
print (data.head)
data.info()
data = data.drop(['Unnamed: 32', 'id'], axis = 1)
data.diagnosis = [1 if eac... |
2e0e1639c32a14d31a07b5044edb6908f8edeef5 | 12LightningFlash12/python | /rock-paper-scissors.py | 757 | 3.828125 | 4 | import random
uCh = raw_input('Rock, paper, or scissors? ')
cCh = random.randint(0, 30)
if(cCh < 10):
cCh = 'rock'
elif(cCh < 20):
cCh = 'paper'
else:
cCh = 'scissors'
def compare(uCh, cCh):
if(uCh == cCh):
print 'The result is a tie'
elif(uCh == 'rock'):
if(cCh == 'scissors'):
... |
3a4f003863faaf3b886057a3e9c3853215cd5947 | ethanl267/task1-2 | /integers/marks.py | 254 | 4.09375 | 4 | name_and_surname = input("enter your name and surname")
grade1 = int(input("%"))
grade2 = int(input("%"))
grade3 = int(input("%"))
avg = int((grade1 + grade2 + grade3) /3)
if avg >=50:
print("you pass")
if avg <50:
print("you fail")
|
7fc0acbd25aa8a5e77afc259dfd7d5be37cc72fc | lineshthakre/python_tutorial | /Python_Basics/userinput_rectangle_area.py | 149 | 3.953125 | 4 | a = float(input("enter the value of length = "))
b = float(input("enter the value of breath = "))
area = a*b
print ("rectangle area is",area,"Sq.m")
|
ebad2a58569bd4724c46921bea7304ef892f3c41 | lineshthakre/python_tutorial | /Python_Basics/tuple.py | 762 | 4.28125 | 4 | #Tuple Data Type/Data Structure
#Tuple is same as list, list is mutable tuple is immutable.
#immutable = unchangeable
#tuples allows duplicate values
#tuples allows heterogenious daa types
mytyuple = ("one", "two", 1, True)
print(mytyuple)
mytuple1 = ("one", "two","three","one")
print (mytuple1)
#Diff of tuples f... |
1e58724dc974a1c3b3b6ff9b69972bc5cef9fb9b | lineshthakre/python_tutorial | /Python_Basics/Task/Area_of_traingle.py | 154 | 3.859375 | 4 | a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
Area_Traingle = (a*b)/2
print ("Area of trangle is = " ,Area_Traingle) |
fafb4c304c3454d7b360fb6b627a09e323272a72 | BrendenBe1/Business-Analytics | /createDashboard.py | 2,097 | 3.53125 | 4 | import requests, json
class createDashboard:
"""
Combines graphs from Plotly API into a single webpage using Dashboardly
"""
def __init__(self, graph_URLs, date_range):
"""
Generate needed data and create dashboard
:param graph_URLs: list of strings
:param ... |
4570abd765801432c2f6fa34ff84a804b9571f65 | BenyDZ/TP-ALGO | /generalFunctions.py | 3,817 | 4.15625 | 4 | def isPrime(number):
"""
Function that verify if a number is a prime number
"""
counter = 2
test = True
#test if the number is egal to 0 or 1
if number == 0 or number == 1:
#change the value of test from true to false
test = False
#test if the number is even
if number... |
d7fae855826583bb9543ac3de2e5b1e3b0d3e796 | Shuvo31/Python_Projects | /Rock_Paper_Scissor.py | 1,104 | 4.09375 | 4 | import random
player_score = []
computer_choice = ["R","P","S"]
message = '''Welcome to Rock Paper Scissor game.
The game has 5 rounds.
Whover with maximum number wins.
Enjoy!
'''
print(message)
for i in range(5):
player_choice = input("Press R f... |
2f657dd6cda9cc5ee4e9aa6bf726bbd9c6dde8fa | Phyks/replot | /replot/helpers/render.py | 3,246 | 3.734375 | 4 | """
Various helper functions for plotting.
"""
import numpy as np
def set_axis_property(group_, setter, value, default_setter=None):
"""
Set a property on an axis at render time.
:param group_: The subplot for this axis.
:param setter: The setter to use to set the axis property.
:param value: The... |
07a79484e1d29925da6dba21362b426a3a2ed6a9 | Phyks/replot | /replot/helpers/plot.py | 1,557 | 3.859375 | 4 | """
Various helper functions for plotting.
"""
import numpy as np
from replot import adaptive_sampling
from replot import exceptions as exc
def plot_function(data, *args, **kwargs):
"""
Helper function to handle plotting of unevaluated functions (trying \
to evaluate it nicely and rendering the p... |
624b05c52af5bddf730b7c780cc6c71f6bdb3d98 | csyml/CARTON | /annotate_csqa/action_annotators/logical.py | 5,556 | 3.828125 | 4 | """
Logical Reasoning (All):
- Logical|Difference|Multiple_Relation - Done
- Logical|Union|Single_Relation - Done
- Logical|Union|Multiple_Relation - Done
- Logical|Intersection|Single_Relation|Incomplete - Done
- Logical|Difference|Single_Relation|Incomplete - Done
- Logical|Difference|Single_Relation - Done
- Logical... |
205e0bcbe44d90f10518992a9373e4dda4f9028c | raman-lab/biosensor_design | /mutateproteintodnapy2.py | 20,066 | 3.8125 | 4 | # python2 script for converting protein to DNA sequence and checking for restriction enzyme digest sites
from Bio import SeqIO
from Bio import Restriction
from Bio import Seq
from Bio.Alphabet import IUPAC
from Bio.SeqRecord import SeqRecord
from CodonUsage import sorted_codon_table
import re
import sys
base_file = s... |
237b232b0d1b117ba4d0c169b3866d4894bca26c | changdaniel/google-competition-solutions | /hashcode/book2-2020/q1.py | 2,271 | 3.640625 | 4 | from sys import argv, stdin
from statistics import mean
"""
num_books = number of books
num_libraries = number of libraries
num_days = number of available days
book_score List[int] = index: id of book, value: score of book
library_info List[(int, int)] = (signup_time, books_per_day)
library_books[set(int)] = [which bo... |
4e6fe563662b4df05b512676d995a8a965c03030 | CamdenShaw/Becoming-A-Programer-LinkedIn-Learning | /Programming-Foundations/Ch07/07_02/start_07_02_sorting_friends.py | 989 | 3.75 | 4 | """ Sorting Friends into Sets """
# set of all friends
friends = set(['Mark', 'Rae', 'Verne', 'Richard',
'Aaron', 'David', 'Bruce', 'Garry',
'Bill', 'Connie', 'Larry', 'Jim',
'Landon', 'Dillon', 'Frank', 'Tom',
'Kyle', 'Katy', 'Olivia', 'Brandon'])
... |
76e17441f6773a47b3f293acaffe3a642908f10e | IshchenkoMaksim/lab4 | /primer3.py | 279 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
if __name__ == '__main__':
n = int(input("Value of n? "))
x = float(input("Value of x? "))
S = 0.0
for k in range(1, n + 1):
a = math.log(k * x) / (k * k)
S += a
print(f"S = {S}")
|
30befc5d9fcdc645c0f907776eba62a0eaa77a50 | ClaireGMIT/GMIT-Problem-Set-2019-CN | /squareroot.py | 916 | 4.28125 | 4 | # Claire Nolan March 2019
# squareroot.py
# Question 7 of Problem Set
# Ref: Lecture Notes and Python Tutorial, coders apprentice, "python in easy steps" by Mike Mcgrath"
number = input( "Please enter a positive number: " )
l = float( number )
x = input("Please give an estimate of square root: ")
estimate = float(x)... |
bde69bb9246e37b089ac371d23ab0b20bed1d46c | ClaireGMIT/GMIT-Problem-Set-2019-CN | /collatz.py | 981 | 4.15625 | 4 | # Claire Nolan March 2019
# collatz.py
# Question 4 of Problem Set
# Ref: Lecture Notes and Python Tutorial, coders apprentice, "python in easy steps" by Mike Mcgrath"
x = int(input("Please enter a positive integer: "))
while x > 1:
if x % 2 == 0:
x = x / 2 # ie if X is divisible by 2 then provide a ne... |
1d11077f46b2b20babfb7d7c021ab31332eefbd9 | fboleandro/Getting_started_with_Python | /Following_Links_in_HTML_Using_BeautifulSoup.py | 1,671 | 4.03125 | 4 | # Write a Python program that expands on http://www.py4e.com/code3/urllinks.py.
# The program will use urllib to read the HTML from the data files below, extract the href= vaues from the anchor tags,
# scan for a tag that is in a particular position relative to the first name in the list,
# follow that link and repe... |
6f6f12d2d9dd692aeb6a2c9ca8833ca2be95362c | willseff/TeamTreehouse | /Flask Basics/simple_app.py | 1,131 | 3.625 | 4 | from flask import Flask
from flask import request
from flask import render_template
app = Flask(__name__)
# define our routes
@app.route('/')
# apps can have multiple routes!
# this dcorator sends the name varaiable thru the url, dont need request.args anymore
@app.route('/<name>')
def index(name="Treehouse"):
#name ... |
9cf079cd94caefc99d188b4b6b8e931c27386b57 | willseff/TeamTreehouse | /Object Oriented Python/songs.py | 712 | 3.6875 | 4 | class Song:
def __init__(self, artist, title, length):
self.artist = artist
self.title = title
self.length = length
def __int__(self):
return self.length
def __eq__(self,other):
return int(self) == other
def __ne__(self,other):
return int(self) != other
... |
15ccf319a1c9bda9c1047a35e610ebf3969813e5 | willseff/TeamTreehouse | /Working with Dictionaries/working-with-dictionaries.py | 1,214 | 4.03125 | 4 |
course = {'teacher': 'Ashley', 'title': 'Introducing Dictionaries', 'level':'Beginner'}
print(course['teacher'])
print(course.keys())
print(course.values())
print(sorted(course.keys()))
print(sorted(course.values()))
#changing values
course['teacher'] = 'treasure'
course['level'] = 'intermediate'
print(sorted(course.... |
d693651b1faa21fab3416410cb165decaaa3493e | willseff/TeamTreehouse | /Working with Lists/shopping_list.py | 964 | 4.34375 | 4 | #create a new empty list named shopping list
shopping_list=[]
#create a new function named add_to_list that declares a parameter named item
#add the item to the list
def add_to_list(item):
shopping_list.append(item)
# notify the user that item was added and state the number of items in the list currenty
print('It... |
9256ff9b2b98fe919f8dd90300c71ddcfea8abf9 | kommisar5150/spartacus-compiler | /mathParser.py | 9,764 | 4.4375 | 4 | #!/usr/bin/env python
from constants import L_PARENTHESES, \
R_PARENTHESES, \
OPERATIONS, \
INSTRUCTIONS, \
TOKEN_SEPARATOR, \
REGISTERS, \
REGISTER_NAMES
def tokenize(expression):
... |
e631c550bcad30b50b7a56b2615a99bc39a3f6a4 | L200184040/Praktikum-AlgoPro | /Practicum 8 Activity 1.py | 583 | 3.875 | 4 | #Activity 1
h=('b','N','a','A','K','p','f')
p={'b':'''Pilihan yang tersedia:
b menampilkan bantuan ini
N menampilkan NIM
a menampilkan Nama
A menampilkan Alamat
K menampilkan Kode Pos
p menampilkan Program Studi
f menampilkan Fakultas''',
'N':'NIM: L200184040',
'a':'Nama: Aqshal Fatwa Ibrahim',
'A':'Alamat: Ge... |
2919ef57c20894ca2c749ef5c526f67beb40737e | IamAmeySalvi109/consultaddassignment | /Assignment_2/Assignment_2_Part_7.py | 270 | 3.90625 | 4 | x=[10,"Python",4.0,25]
y=[3, 20, 12, 1878]
print ("Given List: ",x)
if all(type(num)==int for num in x):
print("True")
else:
print("False")
print()
print ("Given List: ",y)
if all(type(num)==int for num in y):
print("True")
else:
print("False") |
d669af68f439fd26ecacc7bd6654c62888b824b6 | IamAmeySalvi109/consultaddassignment | /Assignment_1/Assignment_1_Part_4.py | 181 | 4 | 4 | x = input("Enter a number: ")
print("Number entered: ",x)
if (int(x) % 2 == 0) and (int(x) % 5 == 0):
print("Hurrah it is what I am looking for")
else:
print("Wrong input") |
d275d0f6551288a101fd0a36ff295a72bbdeb845 | thesamprice/clang_to_json | /src/TextFormat.py | 1,537 | 3.53125 | 4 | import re
#TODO count tabs?
def AlignRegex(text, regex):
"""Aligns some text based on a regular expression. Spaces are inserted until proper alignment is reached."""
max_spot = {}
max_spot['start'] = 0
#Step 1 figure out max position
lines = text.split('\n')
regex = '(\s*)' + regex
spots =... |
bf190d2f59549efe50d41d5aa06cb8e7ac10c983 | ShyZhou/LeetCode-Python | /367.py | 689 | 4.125 | 4 | # Valid Perfect Square
"""
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Returns: True
Example 2:
Input: 14
Returns: False
"""
class Solution(object):
def isPerfectSqua... |
73d01a09ead9c16082a94e4304667f5c83fe413c | ShyZhou/LeetCode-Python | /506.py | 1,138 | 4.15625 | 4 | # Relative Ranks
"""
Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal".
Example 1:
Input: [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
Explanation: The ... |
c6a69f881634277af73531c5e300e1a6ea8fceeb | ShyZhou/LeetCode-Python | /405.py | 1,387 | 4.46875 | 4 | # Convert a Number to Hexadecimal
"""
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
All letters in hexadecimal (a-f) must be in lowercase.
The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represent... |
edb1f6b6665f1afb000afde8f180bc742c17cb9d | ShyZhou/LeetCode-Python | /343.py | 2,288 | 4.03125 | 4 | # Integer Break
"""
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
Example 1:
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 ... |
9fbebb493b52f82fd953e1c79c4a05747a4a08da | ShyZhou/LeetCode-Python | /415.py | 1,549 | 4 | 4 | # Add Strings
"""
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library... |
74db4a54ac91e0f3b1e4966dc214ecf2fbaaa6cf | ShyZhou/LeetCode-Python | /43.py | 1,646 | 4.1875 | 4 | # Multiply Strings
# Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
# Example 1:
# Input: num1 = "2", num2 = "3"
# Output: "6"
# Example 2:
# Input: num1 = "123", num2 = "456"
# Output: "56088"
# Note:
# The length of both num... |
26d5225d6017f8ebfbfc9f4160bc1c818c06901a | ShyZhou/LeetCode-Python | /153.py | 644 | 3.84375 | 4 | # Find Minimum in Rotated Sorted Array
"""
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
You may assume no duplicate exists in the array.
"""
class Solution(object):
def findMin(self, nu... |
bb7b222dcbbdef4eb086d240ef8f45c07e17c5fa | ShyZhou/LeetCode-Python | /84.py | 3,163 | 3.796875 | 4 | # Largest Rectangle in Histogram
# Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
# Example:
# Input: [2,1,5,6,2,3]
# Output: 10
# 向前遍历所有的值,算出共同的矩形面积,每次对比保留最大值
# 只要对局部峰值处理!
class Solution(object):
def la... |
1c3caa4804d058b79f2721f4932db83861b74a4c | ShyZhou/LeetCode-Python | /152.py | 2,816 | 4.15625 | 4 | # Maximum Product Subarray
"""
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
"""
# Space limit exceeds, O(n*n) space, O(n*n) time
class Solution(object):
... |
211becd6f23e6f38fe04e913e56966d536994428 | ShyZhou/LeetCode-Python | /287.py | 1,826 | 4.09375 | 4 | # Find the Duplicate Number
"""
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,... |
0da40e9771748b3b3989b8ccada5131abb99400d | ShyZhou/LeetCode-Python | /49.py | 639 | 4.15625 | 4 | # Group Anagrams
# Given an array of strings, group anagrams together.
# Example:
# Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
# Output:
# [
# ["ate","eat","tea"],
# ["nat","tan"],
# ["bat"]
# ]
import collections
class Solution(object):
def groupAnagrams(self, strs):
"""
:type str... |
b46eb159591b45433e02b31e7dfed77f5f51288f | ShyZhou/LeetCode-Python | /279.py | 1,713 | 3.859375 | 4 | # Perfect Squares
"""
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
"""
# DP
import math
class Solution(object):
... |
7da87667b5877abd17550b05ee63cf8ee56cf466 | ShyZhou/LeetCode-Python | /121.py | 5,395 | 4.21875 | 4 | # Best Time to Buy and Sell Stock
# Say you have an array for which the i-th element is the price of a given stock on day i.
# If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
# Note that you cannot sell a ... |
a29f8661324b74c54f26150e14541434f40a9695 | ShyZhou/LeetCode-Python | /41.py | 839 | 3.671875 | 4 | # First Missing Positive
# Given an unsorted integer array, find the smallest missing positive integer.
# Example 1:
# Input: [1,2,0]
# Output: 3
# Example 2:
# Input: [3,4,-1,1]
# Output: 2
# Example 3:
# Input: [7,8,9,11,12]
# Output: 1
# Note:
# Your algorithm should run in O(n) time and uses constant extra spa... |
8c339196087403b44c7dc0ac3d2128062802bc38 | ShyZhou/LeetCode-Python | /298.py | 889 | 3.90625 | 4 | # Binary Tree Longest Consecutive Sequence
# Given a Binary Tree find the length of the longest path which comprises of nodes with consecutive values in increasing order. Every node is considered as a path of length 1.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# ... |
c692f323d9e90881ba1920b76033a4f58fe23409 | ShyZhou/LeetCode-Python | /743.py | 2,566 | 3.890625 | 4 | # Network Delay Time
# There are N network nodes, labelled 1 to N.
# Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target.
# Now, we send a signal from a certain node K. Ho... |
e7348549768cc59204c3bd7607a1478b9549acc8 | ShyZhou/LeetCode-Python | /179.py | 754 | 4.15625 | 4 | # Largest Number
"""
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
"""
class Solution:
def largestNu... |
3c49df52e92632ec2dc3233d86e5e5115645c753 | prithivraj-rajendran/PythonProjects | /stone_paper_scissor.py | 1,109 | 4.03125 | 4 | import random
# This method will return score value
def score(com_guess, user_guess):
a = {
'stone': {
'paper': 1,
'scissor': -1,
'stone': 0
},
'scissor': {
'paper': -1,
'stone': 1,
'scissor': 0
},
'pape... |
144bf5d585a62c45a221223ecd242e1cfa85f560 | chengwenhua626/data_structure | /10.19/作业.py | 2,385 | 3.8125 | 4 | # init的作用
# 让一个呈结构化分布的代码文件(以文件夹形式组织)变成可以被导入import的软件包
# 最大公约数
def max_common_divisor1(a,b):
if a-b == 0:
return a
max1 = max(a,b)
min1 = min(a,b)
if max1%min1 == 0:
return min1
return max_common_divisor1(min1,max1%min1)
# print(max_common_divisor1(12,8))
# (75)给定一个包含红色、白色... |
54de778c0db1012bcf1b3399bb0d1b1390c37b39 | chengwenhua626/data_structure | /10.14/三数之和,等于规定值.py | 782 | 3.703125 | 4 | def twosums(nums,target):
nums.sort()
print(nums)
aaa = []
for a in range(len(nums)-2):
if nums[a]==nums[a-1] and a>0:
continue
left = a+1
right = len(nums)-1
while left < right:
he=nums[a]+nums[left]+nums[right]
if he < target:
... |
0604f0bdf02ab1dbeb98620274b9fb06609fb508 | chengwenhua626/data_structure | /10.21/归并排序.py | 507 | 3.8125 | 4 |
def mergeSort(ilist):
if len(ilist)<=1:
return ilist
middle = len(ilist)//2
left,right = ilist[0:middle],ilist[middle:]
return merge(mergeSort(left),mergeSort(right))
def merge(left,right):
mlist=[]
while left and right:
if left[0]>=right[0]:
mlist.append(right.pop... |
1951440c683bf86d49f38265dff19532bd69f51b | chengwenhua626/data_structure | /10.9/1有序列表去重(快慢指针).py | 394 | 3.5625 | 4 | class solitional:
def removeDuplicated(self,nums:list)->int:
slow=0
fast=1
while fast<len(nums):
if nums[fast]==nums[slow]:
fast+=1
else:
slow+=1
nums[slow]=nums[fast]
fast+=1
return slow+1
s=... |
a24cfb62619d2d5a5aff2e5681751269a729e4de | chengwenhua626/data_structure | /10.7/创建链表类.py | 2,431 | 3.71875 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
def __repr__(self):
return "Node({})".format(self.data)
class Linklist:
def __init__(self):
self.head=None
self.tail=None
self.size=0
def get(self,index):
curr=self.head
fo... |
c67ad45c43a9b3b39a73960a8da1642b4fcab20c | chengwenhua626/data_structure | /10.9/列表实现栈.py | 758 | 3.9375 | 4 | class stack:
def __init__(self,limit=10):
self.stack=[]
self.size=0
def __str__(self):
return str(self.stack)
# 压栈
def push(self,data):
self.stack.append(data)
self.size+=1
# 弹栈
def pop(self):
temp=self.stack.pop()
self.size-=1
ret... |
01fdc86ccdaa5ff488cd57c3abd5699bf6947a9b | Eugenumber1/OpenCV_learning2 | /draw/draw.py | 1,334 | 4.0625 | 4 | import cv2 as cv
import numpy as np
blank = np.zeros((500, 500, 3), dtype='uint8') #make an array of zeros which will make a blank picture
cv.imshow('blank picture', blank)
img = cv.imread('/Users/zhenyabudnyk/PycharmProjects/OpenCV_learning2/images/cat.jpg')
cv.imshow("Cat", img)
# 1. paint image with certain color... |
a9f67c1db7b78d613bc0816226927542ae0fa9a5 | Eugenumber1/OpenCV_learning2 | /reading/rescale.py | 1,552 | 3.640625 | 4 | import cv2 as cv
#videos and images has different unuseful information so when we resize/rescale them we get rid of this info
#we can also change the height and width of the video
#the reason for
img = cv.imread('/images/woman.jpg')
cv.imshow('Woman', img)
#rescaling photos
def changeRes(width, height):
#live vi... |
1ce2ff762d31dad48b1a8bbf56face3eb63b5d2f | BlackShad0w95/Blockchain | /Test_files/my_file10.py | 325 | 3.703125 | 4 | class person:
def __init__(self):
self.__name=''
def setname(self, name):
print('setname() called')
self.__name=name
def getname(self):
print('getname() called')
return self.__name
name=property(getname, setname)
p1=person()
p1.name="Steve"
print(property().__dic... |
dee5ec05c427eeba000ef1ad0067330ee89cc29c | BlackShad0w95/Blockchain | /Assignemnts/assignment4.py | 966 | 4.09375 | 4 | # 1) Write a normal function that accepts another function as an argument. Output the result of that other function in your “normal” function.
def normal_function(dodane_wartosci):
print(dodane_wartosci(10))
# 2) Call your “normal” function by passing a lambda function – which performs any operation of your cho... |
39b2f0cd0004819d633dcabd1b195a72d24e7f13 | sigma7i/PythonLessons | /Lesson01/hard.py | 1,349 | 4.03125 | 4 | # задание 1 из hard
# решил облегчить задачу себе и проверяющего, добавив тестовые примеры и поочередно проходя их в цикле
# кроме функций за рамки не выходил
def medicine_anketa(name, age, weight):
person_info = name + ', ' + str(age) + ' год, вес ' + str(weight) + ' - '
out_of_normal_weight = weight < 50 or ... |
e786079366a90f95e3c63a0a98c3e1cdc264d189 | RIESUBTYR/MLWorkZone | /Regression/Linear/BikeReg.py | 1,429 | 3.53125 | 4 | import csv
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
Bike_file=open("bikedata.csv")
bike_x=[]
bike_y=[]
chk=True
for row in Bike_file:
rw=row.split(',')
if chk:
chk=False
... |
8a49ec03f43d1a43c2f08a1898c35f2dc0df6845 | rjwebb/life | /life.py | 2,995 | 3.515625 | 4 | from repoze.lru import lru_cache
import itertools
import numpy as np
import random
three_bar = [
(0,-1),
(0,0),
(0,1)
]
def probably(p):
if p != None:
return random.random() < p
else:
return False
def get_neighbours(x, y, shape):
width, height = shape
cells = []
if x ... |
81d971e20af805ff8de846acc9e52041928b3d75 | eaglclaws/JSONTOOL | /JSONTOOL.py | 3,022 | 3.515625 | 4 | import json
"""
The database is structured as follows
productdb.json
{
"product name" :
{
"name" : "product name",
"info" :
{
"manufacturer" : "string", > name of manufacturer
"price" : int, > price of product
"laundry" : [list of strings], > laundry instructions, null if not clothing
"allergens" :... |
73b9d385a96550638da1ed48c7a7ccea13889daa | vpopovic/project-euler | /4-palindrome.py | 534 | 4.28125 | 4 | """
A palindromic number reads the same both ways.
The largest palindrome made from the product of two 2-digit numbers
is 9009 = 91 × 99. Find the largest palindrome made from the product
of two 3-digit numbers.
"""
def check_palindrome(number):
return True if str(number) == str(number)[::-1] else False
biggest... |
7a50d136088c71974f4bc327afacbf73ffe200a3 | rishikumarr/Python | /Data Structures and Algorithms/Data Structures/Tree/Tree Exercise - 3.py | 1,952 | 4.09375 | 4 | class Location:
def __init__(self, place):
self.place = place
self.parent = None
self.children = []
def add_child(self, child):
child.parent=self
self.children.append(child)
def get_level(self):
level = 0
p = self.parent
while p:
... |
90a213198e18a31714a9493d26b9395b800987cc | rishikumarr/Python | /Data Structures and Algorithms/Algorithms/Sorting Techniques/Selection Sort.py | 443 | 3.796875 | 4 | # Selection Sort
def selection_sort(elements):
i=0
while i<len(elements):
min_index=i
for j in range(i,len(elements)):
if elements[j]<elements[min_index]:
min_index=j
elements[i],elements[min_index]=elements[min_index],elements[i]
i+=1
elements=[38,9,... |
d4e5d6ad865467eebf0ba4d65e962236358aa227 | rishikumarr/Python | /Data Structures and Algorithms/Data Structures/Tree/Tree Implementation.py | 1,376 | 3.65625 | 4 | import colorama
class Tree:
def __init__(self, data):
self.data = data
self.parent = None
self.children = []
def add_child(self, child):
child.parent=self
self.children.append(child)
def get_level(self):
level = 0
p = self.parent
while p:
... |
9bc92a8dd13322d0a25919748934478715485fd0 | rishikumarr/Python | /Beautiful Soup/toscrape.py | 4,113 | 3.71875 | 4 | import requests
from bs4 import BeautifulSoup
import csv
url="https://books.toscrape.com/"
request_page=requests.get(url) # requesting the page to scrap data
page=BeautifulSoup(request_page.content,features="lxml") # converting the scraped data into Beautiful soup object to work with scraped data
# print(page.pretti... |
f9a5ef445342b1643852b37d0401b9cc3cc82cb8 | rishikumarr/Python | /Data Science/Seaborn/Categorical Plots/Categorical Plots.py | 2,923 | 3.546875 | 4 | import seaborn as sns
import numpy as np
from matplotlib import pyplot as plt
tips=sns.load_dataset("tips")
########################################################### Bar Plot #######################################################################
# sns.barplot(x="smoker",y="total_bill",data=tips) # this will sho... |
78f29f93a10f8b1a7c6ea5e935a36dfb7045aae4 | casterbn/my_program | /python_/list_max_test.py | 119 | 3.625 | 4 | list = ["dai",1,2,3,"hehe"]
list_1 = [5,6,7,8]
list.extend(list_1)
list.insert(1,"chenghe")
print list
print max(list)
|
c23fec03db14d6da7c80a9968391c50c0ec35f6f | zacwoll/holbertonschool-web_back_end | /0x03-caching/4-mru_cache.py | 2,806 | 3.5 | 4 | #!/usr/bin/env python3
""" Basic Cache implementing MRU """
# imports
BasicCache = __import__('0-basic_cache').BasicCache
class CacheItem:
""" Implementation of a cache item """
def __init__(self, key, value):
""" Cache Item """
self.key = key
self.value = value
class MRUCacheItem(Cac... |
5567c1185ef83bc48da1ea5c0e4f54c506915294 | Woonyung/RWET-Assignments | /week 4/test2.py | 1,134 | 3.59375 | 4 | #
# RWET Assignment #2
# Feb 25, 2015
# making digital cutup
###################################################
import sys
import re
# arguments passed on command line
bestReview = sys.argv[1]
worstReview = sys.argv[2]
# make a blank list
bestList = list()
worstList = list()
mashUp = list()
# bestWords = bestLi... |
776ba83f4291a53921df11f67cdc78f60292956b | Delon-Wu/doubanMovieTop250_crawler | /game.py | 1,964 | 3.5625 | 4 | # -*- codeing = utf-8 -*-
# @Time: 2021/6/4 0004 9:38
# @Author: Delon
# @File: game.py
# @software: PyCharm
from random import randint
print('我们来玩个游戏吧!')
toBegin = True
def justify(userinput, num):
"""用户赢了输出True,计算机赢了输出False,平手输出0"""
lit = ['石头', '剪刀', '布']
if userinput not in lit:
print('输入不正确... |
4243aacb23669e9129ecb786782e6f45cd3685c3 | MaxLindblom/project_euler | /pe1.py | 449 | 4.25 | 4 | #If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.
from modules.result_writer import update_results
def main():
mul_sum = 0
for i in range(1000):
if i % 3 == 0:
... |
355ac5517b6481209274073eef8ff8d5fcdf0eb1 | AIFFEL-coma-team01/Yongho | /week_11/Invert Binary Tree_226.py | 992 | 3.984375 | 4 | '''
## 226. Invert Binary Tree
---
이진 트리의 루트가 주어지면 트리를 반전하고 루트를 반환합니다.
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
from collections import deque
class Solution:
def inver... |
5e3ae6aa72ca713aefc1b23d82bfd961089bc2c4 | AIFFEL-coma-team01/Yongho | /week_02/Rearrange Words in a Sentence_1451.py | 317 | 3.640625 | 4 | # 36ms
# leetcode Rearrange Words in a Sentence 1451
class Solution:
def arrangeWords(self, text: str) -> str:
sort_text = sorted(text.split(' '), key = len)
return ' '.join(sort_text).capitalize()
s1 = "Leetcode is cool"
s2 = "Keep calm and code on"
res = Solution.arrangeWords(0,s1)
print(res) |
67bf5fbfa1ed8c97e34b9b0de77bb4313138b5ce | jinurajan/CLRS | /chapter_2/1_insertion_sort.py | 1,573 | 4.21875 | 4 | """
Insertion Sort
Remember Insertion sort is like managing cards in a game. compare with each one and inser it in a proper location
psuedocode
1. start with second element in the array.
2. look backwards and compare & exchange
3. keep doing it for each element in the array
i = 1 to n
j = i-1 to 0 (backwards)
Best... |
d768877bd133a0c8b969b48a410c1fd9e2e0fd0d | turlapatykaushiksharma/Programs-and-codes | /problems/count_word_string.py | 218 | 3.96875 | 4 | /*
* @turlapatykaushik
* github url : github.com/turlapatykaushik
* problem description : Count the number of words in a string
*/
x = raw_input("Enter the string to count the words ")
y = x.split()
print len(y)
|
1cc20e6219d6b3fc816560d65badc46eb177dc65 | turlapatykaushiksharma/Programs-and-codes | /Spoj/problem-5.py | 271 | 3.640625 | 4 | /*
* @turlapatykaushik
* github url : github.com/turlapatykaushik
*/
from fractions import gcd
from functools import reduce
def lcm(a,b):
"Calculate the lowest common multiple of two integers a and b"
return a*b//gcd(a,b)
k = reduce(lcm, range(1,20+1))
print k
|
bc217a15962a84ce31fe48556bb2b78a1becffe8 | turlapatykaushiksharma/Programs-and-codes | /HackerRank/Basic_calculator.py | 285 | 3.78125 | 4 | /*
* @turlapatykaushik
* github url : github.com/turlapatykaushik
* problem description : Basic calculator in Python
*/
x = float(input())
y = float(input())
p = x+y
o = x-y
r = x*y
s = x/y
t = x//y
print "%.2f" %p
print "%.2f" %o
print "%.2f" %r
print "%.2f" %s
print "%.2f" %t
|
59a3d18ad3bd59865cb010b865cd10210d92bf98 | turlapatykaushiksharma/Programs-and-codes | /HackerEarth/The_Best_internet_Explorer.py | 428 | 3.5 | 4 | /*
* @turlapatykaushik
* github url : github.com/turlapatykaushik
* problem description : This program is 'The best internet explorer' from Hacker Earth
*/
t = input()
while(t):
t = t-1
x = list(raw_input())
y = len(x)
count = 0
for i in range(4,len(x)):
if(x[i]=="a")or(x[i]=="e")or(x[i]=="i")or(x[i]=="o")or... |
2c7801ecf6b66f3144d4b3ea543f7a2bbad03074 | mbrimmer83/pythonexercises | /dictionary.py | 561 | 3.703125 | 4 | aditi = {
'name': 'Aditi',
'email': 'aditi@gmail.com',
'interests': ['movies', 'tennis'],
'friends': [
{
'name': 'Jasmine',
'email': 'jasmine@yahoo.com',
'interests': ['photography', 'tennis']
},
{
'name': 'Jan',
'email': 'jan@hotmail.com',
'interests': ['movies',... |
d79731831d09fa9a64cf26384dbd9dd153cb1a10 | joaopmgd/LogisticRegression | /LogisticRegressionNumpy.py | 5,487 | 4.03125 | 4 | # Logistic Regression is a form of Machine Learning where we can make predictions based on a discovered function.
# The function can be drawn based on the input X, where the cost/error/loss is minimized given all the datapoints.
# The imports are Numpy for the math calculations an matplotlib for plotting the data and t... |
d87b5f6a6a97d1db52694a7b32602f6ddb6a7d0d | EmotionlessHank/COMP9517 | /lab1/lab1-Q2.py | 846 | 3.5 | 4 | # Copyright 2020 Asako Kagurazaka
# importing package
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Question2 Histogram
# Read the image
image1 = cv2.imread("imageQ21.jpg")
# Using plt.hist to plot histogram (really don't want to write it myself)
plt.hist(image1.ravel())
plt.show() # Display the hi... |
26b3ea053fa04cb5abe75d5a36613bc3d1b922dc | gitgeorgec/python-learning | /Loop/first_example.py | 181 | 4.125 | 4 | for char in "hello":
print(char)
for x in range(1, 10):
print(x * x)
print(list(range(10)))
print(list(range(1, 10)))
print(list(range(1, 10, 2)))
print(list(range(10, 0, -1)))
|
b3e48b100860c161ac96dc5345e484e25b2290ae | gitgeorgec/python-learning | /OOP/muti-inheritance.py | 1,041 | 4.25 | 4 | class Aquatic:
def __init__(self, name):
print("Aquatic init")
self.name = name
def swim(self):
return f"{self.name} is swimming"
def greet(self):
return f"I am {self.name} of the sea!"
class Ambulatory:
def __init__(self, name):
print("Ambulatory init")
... |
26d696505825ce2b3ca4a21ab951cc70f8d2c47e | gitgeorgec/python-learning | /Errors_and_Debug/debugging.py | 327 | 3.90625 | 4 | import pdb
first = "FIRST"
second = "SECOND"
pdb.set_trace()
result = first + second
third = "THIRD"
result += third
print(result)
# common PDB Commands:
# l (list)
# n (next line)
# p (print)
# c (continue - finishes debugging)
def add_numbers(a,b,c,d):
import pdb; pdb.set_trace()
return a+b+c+d
add_numbers(1,... |
f3f24eb265f1db49e50b8e7d059fac60170df68a | gitgeorgec/python-learning | /Lists/list_comprehension.py | 637 | 3.84375 | 4 | num = [1,2,3]
ten_times_num = [ x* 10 for x in num]
print(num)
print(ten_times_num)
name = "hello"
print([char.upper() for char in name])
firends = ["alex", "jason", "peter"]
print([name[0].upper() + name[1:] for name in firends])
numbers = [1,2,3,4,5,6]
even = [num for num in numbers if num%2 == 0]
odd = [num ... |
92377b46f598f52febe781f5f207327720cf05f5 | gitgeorgec/python-learning | /Http/dad_joke.py | 728 | 3.5625 | 4 | import requests
from pyfiglet import figlet_format
from random import choice
from termcolor import colored
header = figlet_format("DAD JOKE 3000")
header = colored(header, color="yellow")
print(header)
term = input("what whould you like to search for?")
url = "https://icanhazdadjoke.com/search"
res = requests.get(url... |
ebc7d2a547ffe699e0073f1fbc30677d41c3dd57 | 140378476/BigDataSummer | /HW2/mlp/model.py | 1,378 | 3.546875 | 4 | # -*- coding: utf-8 -*-
import torch
from torch import nn
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
drop_rate = 0.2
units = 512
# TODO: implement input -- Linear -- BN -- ReLU -- Dropout -- Linear -- loss
# Your Linear Layer
self.lin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.