blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
f98c112ce647f1db4844ab7ff43b0ca9e5d343d4
humboldt/ubcsailbots.control
/control/piardio/mockarduino.py
6,483
4.03125
4
''' Created on Feb 2, 2013 Mock Arduino which should simulate changing wind conditions and return simulated boat data that can be used by the control logic and gui. - By creating a mock arduino object, you may call functions which will return mock data. All of the data will be simulated to show relative wind co...
a7da15548f87fbd1d78a04e561bd5f3b9723f1e7
zhengshengyu/DataAnalysis
/pydata-book-master/ch09.py
6,358
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division from numpy.random import randn import numpy as np import os import matplotlib.pyplot as plt np.random.seed(12345) plt.rc('figure', figsize=(10, 6)) from pandas import Series, DataFrame import pandas as pd np.set_printoptions(precision=4) # ...
e836acdb95b7acd45aa10f287170bc89f0dc908f
delzadbamji/Object-Detection-Pytorch
/cnn_model.py
2,047
3.546875
4
import torch.nn as nn import torch.nn.functional as f class cnn_model(nn.Module): ''' The CNN model contains three convolutional layers, one fully connected layer and one output layer with 4 nodes. A kernel of size 5 with stride 1 is applied in each convolution layer. The first two convolutional layers are foll...
7d6edeaf2cf628ac6c9fdeb855fec712f92e35ea
monda00/AtCoder
/Contest/ABC126/B.py
225
3.609375
4
s = input() first = int(s[:2]) second = int(s[2:]) if 1 <= first <= 12 and 1 <= second <= 12: print('AMBIGUOUS') elif 1 <= first <= 12: print('MMYY') elif 1 <= second <= 12: print('YYMM') else: print('NA')
0ea2a09c2b2d69e34a47774562d08928abc85523
monda00/AtCoder
/Contest/ABC062/A.py
286
3.578125
4
group_a = [1, 3, 5, 7, 8, 10, 12] group_b = [4, 6, 9, 11] group_c = [2] x, y = map(int, input().split()) if x in group_a and y in group_a: print('Yes') elif x in group_b and y in group_b: print('Yes') elif x in group_c and y in group_c: print('Yes') else: print('No')
0b0b1fb83664b036eb037640e46d7395cbf09e6d
monda00/AtCoder
/Contest/ABC160/A.py
144
3.859375
4
coffee = "coffee" input_str = input() if input_str[2] == input_str[3] and input_str[4] == input_str[5]: print('Yes') else: print('No')
eae53051a1fbd475872ada6923ca8d94b295469f
monda00/AtCoder
/AtCoderProblem/Difficulty900/abc057_c_904.py
336
3.625
4
''' [C - Digits in Multiplication](https://atcoder.jp/contests/abc057/tasks/abc057_c) ''' import math n = int(input()) sqrt_n = int(math.sqrt(n)) ans = 10**10+1 for i in range(1, sqrt_n+2): a = i b = n//a if a * b == n: cur = max(len(str(a)), len(str(b))) if ans > cur: ans = ...
cd53f885766abf65a42fcdf58b77bec21a3c45d6
monda00/AtCoder
/Sample/bs_abc192.py
907
3.609375
4
x = list(input()) m = int(input()) X = int(''.join(x)) max_x = int(max(x)) def change_nto10(num, b): n = 0 numlist = list(str(num)) while(numlist): n *= b n += int(numlist.pop(0)) return n def is_ok(mid): """二分探索中の判定 Parameters ---------- mid : int Returns -...
a8db7cbafc8be1182e79ff08c99a95d95aaf05dd
monda00/AtCoder
/Contest/ABC171/C.py
226
3.546875
4
n = int(input()) def num2alpha(num): if num<=26: return chr(96+num) elif num%26==0: return num2alpha(num//26-1)+chr(122) else: return num2alpha(num//26)+chr(96+num%26) print(num2alpha(n))
0473e9124925a1e466f006022892e2a2a141e764
monda00/AtCoder
/Contest/ABC023/B.py
983
3.515625
4
n = int(input()) s = input() if n % 2 == 0: print(-1) else: half_index = n // 2 if s[half_index] != 'b': print(-1) exit() s_first = s[:half_index] while(len(s_first) > 1): if ((s_first[0] == 'a' and s_first[1] == 'b') or \ (s_first[0] == 'b' and s_first[1] ==...
3d546a25650c21afb062b64d38e0e7f8abc49777
Amruta-deshpande/Sentiment-Analysis-for-Predicting-Quality-of-Service
/DataCleaning.py
2,746
3.71875
4
import csv import re file_name = "dataset/results_computer_with_stars.csv" cleaned_file_name = "program_output/cleaned_results_computer_with_stars.csv" # file_name = "dataset/results_business_with_stars.csv" # cleaned_file_name = "program_output/cleaned_results_business_with_stars.csv" # file_name = "da...
7e776d80ade377fa2bbf3ee0236be71e35966043
MarceloDL-A/Python
/10-Introduction_to_Pandas/Select_Rows_with_Logic_I_equal.py
704
4.375
4
import codecademylib import pandas as pd df = pd.DataFrame([ ['January', 100, 100, 23, 100], ['February', 51, 45, 145, 45], ['March', 81, 96, 65, 96], ['April', 80, 80, 54, 180], ['May', 51, 54, 54, 154], ['June', 112, 109, 79, 129]], columns=['month', 'clinic_east', 'clinic_north', 'clinic_so...
3b74a5f0b532198a85d79480fbc2fc06a4fbd896
MarceloDL-A/Python
/15-Statistics_with_NumPy/Statistics_in_NumPy/Mean_and_Logical_Operations.py
2,192
4.5
4
""" INTRODUCTION TO STATISTICS WITH NUMPY Mean and Logical Operations We can also use np.mean to calculate the percent of array elements that have a certain property. As we know, a logical operator will evaluate each item in an array to see if it matches the specified condition. If the item matches the given condition...
c5fc95f5a95b433bbb69945e8f83c03c400c9f4f
MarceloDL-A/Python
/13-Data_Visualization/Introduction_to_Matplotlib/Line_with_Shaded_Error.py
1,840
4.0625
4
import codecademylib from matplotlib import pyplot as plt hours_reported =[3, 2.5, 2.75, 2.5, 2.75, 3.0, 3.5, 3.25, 3.25, 3.5, 3.5, 3.75, 3.75,4, 4.0, 3.75, 4.0, 4.25, 4.25, 4.5, 4.5, 5.0, 5.25, 5, 5.25, 5.5, 5.5, 5.75, 5.25, 4.75] exam_scores = [52.53, 59.05, 61.15, 61.72, 62.58, 62.98, 64.99, 67.63, 68.52, 70.29, ...
63ed7e096dda66d088a284ebf383a8e6d7d27f67
MarceloDL-A/Python
/16-Hypothesis_Testing_with_SciPy/Hypothesis_Tests.py
1,547
3.5625
4
STATISTICAL CONCEPTS Hypothesis Tests When observing differences in data, a data analyst understands the possibility that these differences could be the result of random chance. Suppose we want to know if men are more likely to sign up for a given programming class than women. We invite 100 men and 100 women to this c...
db96f54eb8dab41492a4e9fbb4d3072e96eec934
MarceloDL-A/Python
/13-Data_Visualization/Introduction_to_Seaborn/Understanding_Aggregates.py
943
4.28125
4
import codecademylib3_seaborn import pandas as pd from matplotlib import pyplot as plt import numpy as np gradebook = pd.read_csv("gradebook.csv") #Next, take a minute to understand the data youll analyze. The DataFrame gradebook contains the complete gradebook for a hypothetical classroom. Use print to examine gradeb...
801604eed56381f44cf18f885ac7f3a9ea8eba39
MarceloDL-A/Python
/14-Statistics_with_Python/Quatiles,_Quantiles,_and_Interquartile_Range/Quartiles_Interquartile.py
1,597
4.71875
5
""" Quartiles The interquartile range is the difference between the third quartile (Q3) and the first quartile (Q1). For now, all you need to know is that the first quartile is the value that separates the first 25% of the data from the remaining 75%. The third quartile is the opposite it separates the first 75% of...
cf2293fa6dc26162ce73a2c33cbc8bdd6c580d22
MarceloDL-A/Python
/14-Statistics_with_Python/Histograms/Bins_and_Count I.py
2,238
4.28125
4
""" Bins and Count I In the previous exercise, you found that the earliest transaction time is close to 0, and the latest transaction is close to 24, making your range nearly 24 hours. Now, we have the information we need to start building our histogram. The two key features of a histogram are bins and counts. Bins A...
04c97880d4fee65117627e674f1323fd109c2854
MarceloDL-A/Python
/14-Statistics_with_Python/Histograms/Range.py
2,173
4.59375
5
""" HISTOGRAMS Range Histograms are helpful for understanding how your data is distributed. While the average time a customer may arrive at the grocery store is 3 pm, the manager knows 3 pm is not the busiest time of day. Before identifying the busiest times of the day, its important to understand the extremes of your...
80b1669509b72ce5219a27ab27d7af53c0887503
MarceloDL-A/Python
/13-Data_Visualization/Introduction_to_Matplotlib/Modify_Ticks.py
870
4.125
4
import codecademylib from matplotlib import pyplot as plt month_names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep","Oct", "Nov", "Dec"] months = range(12) conversion = [0.05, 0.08, 0.18, 0.28, 0.4, 0.66, 0.74, 0.78, 0.8, 0.81, 0.85, 0.85] plt.xlabel("Months") plt.ylabel("Conversion") plt.plot(m...
d6c07151daabf0c745ea0b53d3309a2a5408d995
MarceloDL-A/Python
/19-Beautiful_Soup/10_of_11_Reading_Text.py
2,953
4.53125
5
""" WEB SCRAPING WITH BEAUTIFUL SOUP Reading Text When we use BeautifulSoup to select HTML elements, we often want to grab the text inside of the element, so that we can analyze it. We can use .get_text() to retrieve the text inside of whatever tag we want to call it on. <h1 class="results">Search Results for: <span c...
8e8c22f5ae1f42fafdeea4aaa32af32a85fc434e
MarceloDL-A/Python
/20-Machine_Learning_-_Supervised_Learning/5-K_Nearest_Neighbor_Regression/01_of_04_Regression.py
2,121
4.46875
4
from movies import movie_dataset, movie_ratings def distance(movie1, movie2): squared_difference = 0 for i in range(len(movie1)): squared_difference += (movie1[i] - movie2[i]) ** 2 final_distance = squared_difference ** 0.5 return final_distance def predict(unknown, dataset, movie_ratings, k): distances...
4a1813de2a687280ab1d0a56f759f9e5cb49588a
MarceloDL-A/Python
/20-Machine_Learning_-_Supervised_Learning/1-Introduction_to_Machine_Learning/03_de_05_-_Supervised_Learning.py
2,666
4.0625
4
""" ********************************** WHY USE MACHINE LEARNING? Supervised Learning Machine learning can be branched out into the following categories: Supervised Learning Unsupervised Learning Supervised Learning is where the data is labeled and the program learns to predict the output from the input data. For insta...
1118eca63a9f6b4d06db8d7abef1851fc16bde02
MarceloDL-A/Python
/19-Beautiful_Soup/05_of_11_Object_Types.py
1,433
4.28125
4
""" WEB SCRAPING WITH BEAUTIFUL SOUP Object Types BeautifulSoup breaks the HTML page into several types of objects. Tags A Tag corresponds to an HTML Tag in the original document. These lines of code: soup = BeautifulSoup('<div id="example">An example div</div><p>An example p tag</p>') print(soup.div) Would produce o...
3188748c671f6807855aeaf6254a1dd0e8cfba48
MarceloDL-A/Python
/16-Hypothesis_Testing_with_SciPy/1_Sample_T-Testing.py
3,540
4.34375
4
""" HYPOTHESIS TESTING 1 Sample T-Testing Let's imagine the fictional business BuyPie, which sends ingredients for pies to your household so that you can make them from scratch. Suppose that a product manager wants online BuyPie orders to cost around 1000 Rupees on average. In the past day, 50 people made an online pur...
2be072ab38c419634143e9f2cc8bba6513b1368d
MarceloDL-A/Python
/14-Statistics_with_Python/Quatiles,_Quantiles,_and_Interquartile_Range/Q1_and_Q3.py
2,292
4.71875
5
""" QUARTILES Q1 and Q3 Now that weve found Q2, we can use that value to help us find Q1 and Q3. Recall our demo dataset: [-108, 4, 8, 15, 16, 23, 42][-108,4,8,15,16,23,42] In this example, Q2 is 15. To find Q1, we take all of the data points smaller than Q2 and find the median of those points. In this case, the point...
411cca8bb2bb3cc260b6aa707ddf80951c04faa8
MarceloDL-A/Python
/16-Hypothesis_Testing_with_SciPy/ANOVA.py
2,472
3.859375
4
""" HYPOTHESIS TESTING ANOVA In the last exercise, we saw that the probability of making a Type I error got dangerously high as we performed more t-tests. When comparing more than two numerical datasets, one way to preserve a Type I error probability of 0.05 is to use ANOVA. ANOVA (Analysis of Variance) tests the null...
a4181a44e4275296d819894ef81abec72d61ac10
MarceloDL-A/Python
/14-Statistics_with_Python/Quatiles,_Quantiles,_and_Interquartile_Range/Quantiles.py
2,260
4.5
4
""" QUANTILES Quantiles Quantiles are points that split a dataset into groups of equal size. For example, lets say you just took a test and wanted to know whether youre in the top 10% of the class. One way to determine this would be to split the data into ten groups with an equal number of datapoints in each group and ...
c222544f8e38d9372ddd061d71c7d3467b29c009
MarceloDL-A/Python
/Calculating Financial Statistics/08_of_11_-_Standard_Deviation.py
784
3.71875
4
from utils import calculate_variance import numpy as np # Import library here from math import sqrt def display_as_percentage(val): return '{:.1f}%'.format(val * 100) returns_disney = [0.22, 0.12, 0.01, 0.05, 0.04] returns_cbs = [-0.13, -0.15, 0.31, -0.06, -0.29] stddev_disney = np.std(returns_disney) stddev_cbs =...
0c0a07201252b64bcb0e7c39a48e32a31649f6ff
MarceloDL-A/Python
/14-Statistics_with_Python/Mean,_Median,_and_Mode/Central_Tendency_for_Housing_Data.py
5,464
4.4375
4
""" LEARN STATISTICS WITH PYTHON Central Tendency for Housing Data In this project, you will find the mean, median, and mode cost of one-bedroom apartments in three of the five New York City boroughs: Brooklyn, Manhattan, and Queens. Using your findings, you will make conclusions about the cost of living in each of th...
ec29f3e59f81646bf22b6fefb780636964429175
MarceloDL-A/Python
/14-Statistics_with_Python/Histograms/Histograms.py
2,291
4.34375
4
""" Histograms While counting the number of values in a bin is straightforward, it is also time-consuming. How long do you think it would take you to count the number of values in each bin for: an exercise class of 50 people? a grocery store with 300 loaves of bread? Most of the data you will analyze with histograms i...
59064843397400bf09881ad09bbf9cfd95c8947c
MarceloDL-A/Python
/16-Hypothesis_Testing_with_SciPy/Chi_Square_Test.py
3,348
4.4375
4
""" HYPOTHESIS TESTING Chi Square Test In the last exercise, we looked at data where customers visited a website and either made a purchase or did not make a purchase. What if we also wanted to understand if the probability of making a purchase depends on some other categorical variable, like gender? If we want to unde...
44774e0e6115992fe42608c6da39b77fbeb94f58
MarceloDL-A/Python
/17-Data_Cleaning_with_Pandas/Part II/08_de_12_-_Looking_at_Types.py
1,679
4.375
4
""" DATA CLEANING WITH PANDAS Looking at Types Each column of a DataFrame can hold items of the same data type or dtype. The dtypes that pandas uses are: float, int, bool, datetime, timedelta, category and object. Often, we want to convert between types so that we can do better analysis. If a numerical category like "n...
557043185e919883ce22896537949df1cb4552e5
MarceloDL-A/Python
/15-Statistics_with_NumPy/Statistics_in_NumPy/Percentiles,_Part_II.py
1,940
4.5625
5
""" INTRODUCTION TO STATISTICS WITH NUMPY Percentiles, Part II Some percentiles have specific names: The 25th percentile is called the first quartile The 50th percentile is called the median The 75th percentile is called the third quartile The minimum, first quartile, median, third quartile, and maximum of a dataset a...
966982276859555b22cf9bc7914b5886a0073e3a
MarceloDL-A/Python
/10-Introduction_to_Pandas/Selecting_Multiple_Rows.py
697
3.953125
4
import codecademylib import pandas as pd df = pd.DataFrame([ ['January', 100, 100, 23, 100], ['February', 51, 45, 145, 45], ['March', 81, 96, 65, 96], ['April', 80, 80, 54, 180], ['May', 51, 54, 54, 154], ['June', 112, 109, 79, 129]], columns=['month', 'clinic_east', 'clinic_north', 'clinic_so...
1d7378dc2e5fadcb2bbc7149bd3f92c1d5f0028c
MarceloDL-A/Python
/20-Machine_Learning_-_Supervised_Learning/7-Logistic_Regression/Logistic_Regression/10_of_11_-_Feature Importance.py
1,542
4.25
4
import codecademylib3_seaborn import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from exam import exam_features_scaled, passed_exam_2 # Train a sklearn logistic regression model on the normalized exam data model_2 = LogisticRegression() model_2.fit(exam_features_scal...
a6adb1f4db142b73d6c89558951a59e6c009ca93
MarceloDL-A/Python
/13-Data_Visualization/Introduction_to_Matplotlib/Stacked_Bars_School_Grades.py
1,770
3.859375
4
import codecademylib from matplotlib import pyplot as plt import numpy as np unit_topics = ['Limits', 'Derivatives', 'Integrals', 'Diff Eq', 'Applications'] As = [6, 3, 4, 3, 5] Bs = [8, 12, 8, 9, 10] Cs = [13, 12, 15, 13, 14] Ds = [2, 3, 3, 2, 1] Fs = [1, 0, 0, 3, 0] x = range(5) #The Bs bars will go on top of the ...
74b85c2e4f72ccd242c08730e8826ade41d8a3e5
KingPiggy/MyStudy
/Python/자료형/리스트 함수.py
655
3.796875
4
# l.append(a) a를 삽입한다. booksan = ["강백호", "송태섭", "채치수", "서태웅"] booksan.append("정대만") print(booksan) # l.sort() : nlogn "Tim sort" 알고리즘 nums = [1, 4, 5, 3 , 2] nums.sort(); print(nums); # l.reverse() nums2 = [5, 4, 3, 2, 1] nums2.reverse() print(nums2) # l.index(a), a가 있는 인덱스를 반환 print(booksan.index("...
33531b7ae39264a8499c9611f075f1a3b394a6bd
Gaon-Choi/Basic_ML
/3_1_2차원 그래프 그리기_2.py
813
3.8125
4
import numpy as np import matplotlib.pyplot as plt def end(): print() # 3.1.6 그래프를 장식하기 def f2(x, w): return (x-w) * x * (x+2) x= np.linspace(-3, 3, 100) plt.plot(x, f2(x, 2), color='black', label='$w=2$') plt.plot(x, f2(x, 1), color='cornflowerblue', label='$w=1$') plt.legend(loc="upper left") plt.ylim(-15,...
a87a4352cc3ded4edb85685ed75de803849d5281
Mygithub-projects/python_programs
/functions/changeme.py
421
3.90625
4
def changeme( mylist ): "This changes a passed list into this function" # call by reference # mylist.append([1,2,3,4]); #local variable mylist = [5,6,7] print ("Values inside the function: ", mylist) return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist )...
d559a7a19a385be0b0d3c34e7b0edec4a4511c45
Mygithub-projects/python_programs
/classes/Example.py
1,172
3.984375
4
''' class Car(): company="Honda" def __init__(self,vid_number,registration_number): self._vid_number = vid_number self.registration_number = registration_number def displayInformation(self): return ("The car\'s VIN is {0} and Registration Number is {1}" ...
ad92cae9b188e4b9293d67599fc2812fe62c6936
Mygithub-projects/python_programs
/mcqtest/test1.py
1,643
3.859375
4
''' for i in range(5): print(i) ''' ''' myList = [lambda x: x ** 2, lambda x: pow(x, 3), lambda x: x **4] for func in myList: print(func(3), end='') ''' ''' num = 1 def func(): global num print("first", num) num = num + 1 print(num) func() print("last=",num) '...
f8c42fde4fe3537c4c5055dc7aed3b83650b6773
Mygithub-projects/python_programs
/threads/helothread.py
633
3.71875
4
import threading import time class HelloThread(threading.Thread): def __init__(self,name,id): threading.Thread.__init__(self) self.name=name self.id=id def run(self): time.sleep(10) print( "Hello {}, I am Thread - {} \n".format(self.name,self.id)) ...
4cb1f51b8297cfb6feb84af9b8c3946913b5083c
Mygithub-projects/python_programs
/Python_Part_3/iterators_generators/iterator_test.py
752
3.640625
4
class HundredMultiples(): def __init__(self,start=1,max=1000,value=0): self.max = max self.start = start self.value=0 def __iter__(self): return self def __next__(self): self.value = self.start*100 if self.value > 1000: raise ...
d72beb72ccb213367a3dd1aea29869fdf4cd73f1
Mygithub-projects/python_programs
/Python_Part_2/modules_n_packages/global_statement.py
278
3.71875
4
length = 0 breadth = 0 def area(l,b): length = l # creates a local variable length breadth = b # creates a local variable breadth return l * b print("area= {} ".format(area(10,5))) print("length = {} and breadth = {} ".format(length,breadth))
ed64fb7fda73284aedae84a2b22e249a62752a58
Mygithub-projects/python_programs
/regular_expression/test.py
140
3.65625
4
import re xx = "Hello 123 how are you?" r1 = re.findall(r"^\w",xx) r2 = re.split(r's',"this is example of split") print(r2) print(r1)
879790d85a86c2ce4393f279b130fcbd2a5f11e5
Mygithub-projects/python_programs
/listsamples/slicing.py
205
4.09375
4
even_list=[2,4,6,8,10,12,14,16,18,20] #print 2nd to 5th item print(even_list[2:5]) #print last item to 5th last item print(even_list[-5]) #print elements begining to end print(even_list[:])
55223bb86f0896d6201306080bd4ec9d4085bcf1
Mygithub-projects/python_programs
/Python_Part_2/modules_n_packages/calc.py
172
3.78125
4
from calculator import add,diff x=22 y=11 print("sum of {} and {} = {}".format(x,y,add(x,y))) print("difference between {} and {} = {}".format(x,y,diff(x,y)))
6d66614b0761b0f208813992a870c5b0fa78e9a1
hkellyanne/CS22
/Fraction.py
2,365
3.609375
4
__author__ = 'Kelly' def gcd(m,n): while m%n != 0: oldm = m oldn = n m = oldn n = oldm%oldn return n class Fraction: def __init__(self, n, d): self.num = n self.den = d assert n % 1 == 0, "Error! this is not an integer!" assert d % 1 == 0,...
c6647ef02f7801e4ce8516fd1299e3f463738663
ThiagoAugustoSM/hackerRank
/Tutorials/30 Days of Code/Day 5: Loops/solution.py
120
3.578125
4
#!/bin/python3 import sys n = int(input().strip()) for x in range(1,11): print("{} x {} = {}".format(n, x, n*x))
47660e2c977797d1b137b95cc784f6c331b48f6c
wallind/PythonZork
/weapon.py
1,418
3.796875
4
from random import * #################################################################### #This is a class that creates the weapons in the player inventory #at random and also randomizes the attack multiplier of each weapon. #################################################################### class Weapon(object): "...
07097ec4eebec7c04984fe26835e8c868976f17c
manika1511/interview_prep
/linked_list/palindrome.py
2,717
4.40625
4
"""Implement a function to check if a linked list is a palindrome.""" # Node class to define linked list nodes class Node(object): # constructor to initialise node def __init__(self, data=None, next=None): self.data = data self.next = next # Linkedlist class class LinkedList(object): #met...
336f51c6456087da98c1e508fec295c019f2484c
manika1511/interview_prep
/array_and_strings/is_unique.py
1,703
4.34375
4
"""The complexity of converting a string to a set is O(n) as time to traverse a string of 'n' characters is O(n) and the time to add it to the hash map is O(1) and the is else loop is again O(1). Assumption: the lowercase and uppercase letters are considered same""" def all_unique(s): s = s.lower() #conv...
f5fe31c9f62de93f9a22a16080f37fb8d37e9e8b
manika1511/interview_prep
/linked_list/partition.py
2,083
4.1875
4
"""Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the "right partitio...
0eb7a3a1cfe7b428d088065a1e0797e45501d0a1
manika1511/interview_prep
/array_and_strings/second_smallest.py
283
3.890625
4
def second_smallest(numbers): m1, m2 = None, None for x in numbers: if x <= m1: m1, m2 = x, m1 elif x < m2: m2 = x return m2 def main(): a = [2,3,1,5,6] print (second_smallest(a)) if __name__ == "__main__": main()
73615d63c76c02bf9b97f0d3d44124e0e89c57f7
manika1511/interview_prep
/rotate_image.py
1,578
3.65625
4
class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. """ n = len(matrix) # transpose matrix for i in range(n): for j in range(i, n): ...
ba4383bbb680281d45a5e3e2aac4564dd6eca329
manika1511/interview_prep
/copy_list_random_pointer.py
1,770
3.65625
4
""" # Definition for a Node. """ class Node: def __init__(self, x, next=None, random=None): self.val = int(x) self.next = next self.random = random class Solution(object): def __init__(self): self.visited = {} def copyRandomList(self, head): #O(n) space and O(n) time ...
0b3700d00afcfeffe61127c0f8bd14d419c7d631
manika1511/interview_prep
/array_and_strings/double_occurrence.py
653
3.875
4
def double_occurrence(arr): count = 0 digits = 0 for i in range(len(arr)): if arr[i] != None: if arr[i] % 2 == 0: count = count + 1 digits = digits + 1 else: digits = digits + 1 last_index = digits + count i = last_inde...
5634e611b68725c687f54aee3ea30a13331caeb9
mwnachman/dataStructures
/python/gcd.py
1,890
3.796875
4
# Find the greatest common denominator of two numbers # gcd(a, b) == gcd(|a|, |b|), so we will restrict ourselves # to positive inputs. import random import timeit # Efficient -- this algorithm is known as Euclid's algorithm def gcd(higher, lower): # make sure higher and lower really are higher and lower if ...
b602a79c5a03718d4297b50a2043990bd6bb4d89
LucianoCarbonera/CursoPython
/jogos.py
467
3.78125
4
import forca import adivinhacao def escoha_jogo (): print("*****************") print("Escolha seu jogo") print("*****************") print("(1) - Adivinhacao") print("(2) - Forca" ) jogo = int(input("Digite 1 ou 2 : ")) if(jogo==1): print("Jogando adivinhacao") adivinhacao....
021a9b37886734a11ca8fd084c319891ea770156
DicleD/bootcamp
/1_comprehensions.py
3,713
3.953125
4
# 1 giris = "hi my name is john and i am learning python" sonuc = "Hi My NaMe Is JoHn AnD i Am LeArNiNg PyThOn" def change(metin): # new_metin tanımlamazsak da yazdırır ama o zaman bir cümle içinde yazdırmıyor new_metin = "" for i in range(0, len(metin)): if i % 2 == 0: new_metin = new_...
657f1b92433771769361b4ec626e8f033631a066
kostyabaranov2004/test
/Something.py
340
3.875
4
'''def red (R): if R < 0: return "ошибка" if R < 10: return R else: return red(R // 10) + (R % 10) print(red(123))''' def red (A): F = 2 if A == 1: return False while F < A: if A % F == 0: return False F += 1 return True print(red(...
f9dea3061af3bc34056fd3819d54bbe222c7924e
kuroitenshi9/Python-compendium
/05/list/2.py
308
3.71875
4
''' Pobierz od użytkownika 10 liczb, wyświetl tylko te, które są nieparzyste. ''' numbers = input("Podaj 10 liczb po przecinku: ") numbers = numbers.split(",") # print(numbers) odd_numbers = [] for n in numbers: n = int(n) if n % 2 == 1: odd_numbers.append(int(n)) print(odd_numbers)
e1d4ba597f293fd4a3c3d45dc3839e52caa485ca
kuroitenshi9/Python-compendium
/06/3.py
432
3.875
4
''' 3▹ Napisać funkcję, która przyjmuje listę liczb i zwraca sumę wszystkich elementów na liście. ''' # def avg(): # numbers = input("Insert numbers and divide them by comma: ") # numbers = numbers.split(", ") # for n in numbers: # n = float(n) truth = "beauty" index = 0 letters = [] while index < ...
5a226286b401e79de7b972a526253ab97e3757ed
kuroitenshi9/Python-compendium
/04/for/silnia.py
528
4.09375
4
''' Napisz program, który wyświetli kolejne wyniki dla silni liczby naturalnej N (N podane przez użytkownika, ale nie większe niż 8). ''' number = int(input("Choose number in range between 1 and 8: ")) wynik = 1 if number <= 8: print(f"{number}!=") for step in range(1, number+1): wynik = wynik * step ...
0a1ffc9df1c48dcfba8aa3ec1a145e1241223bbd
kuroitenshi9/Python-compendium
/06/notatki.py
142
3.671875
4
def absolute_value(num): if num >= 0: return num else: return -num print(absolute_value(4)) print(absolute_value(-5))
af75641e06d65f3562eb4258849710ad0288ce41
wise700/PythonRep
/Excersises/ex30.py
132
3.796875
4
people=10 cats=40 dogs=80 if people>cats: print("people>cats") elif cats<dogs: print("cats<dogs") else: print("wtf")
ddece68b5100b4c2c8e596e23f2812fb528dcd2f
wise700/PythonRep
/Excersises/ex31.py
789
4
4
print("You enter a dark room with two doors. Do you go through doors #1 or #2?.") door=input(">") if door=="1": print("There is a gaint bear here eating a cheese cake.What do you do?") print("1. Take the cake") print("2. scream at the bear.") bear=input(">") if bear=="1": print("The bear...
335dad732a5d54c2aa30b50ee6ff2ad33c499deb
wise700/PythonRep
/Excersises/ex21.py
355
3.9375
4
def add(a,b): print("Adding %d+%d"%(a,b)) return a+b def subtract(a,b): print("Subtracting %d-%d"%(a,b)) return a-b def multiply(a,b): print("Multiplying %d,%d"%(a,b)) return a*b print("lets do some math function") age=add(1,2) height=subtract(3,1) weight=multiply(4,3) print("Age:%d,height:...
ab9381e0fff4613ca9f3f168b14cd65424969a3f
creynolds247/CW
/q1.py
750
3.765625
4
id=['Swim','Bike','Running'] speed=[1.77,14.66,5.1] distance=[] def input(): for i in range(len(id)): distance.append(float(raw_input("Disance for "+id[i]))) if distance[i]<0: print "Error disance cannot be less than 0" exit(0) def Display(): print "======"*3 def C...
dd001dc0a2f962d539b98ee9e7c7d1e53120d131
nickzdeb/Senior-Design-Python-Code
/light.py
1,439
3.59375
4
import time import RPi.GPIO as GPIO GPIO.setwarnings(False) # Function used to convert binary to digit def convert_to_tens(digit_array): result = 0 length = len(digit_array) t0 = 0 while (t0<length): t1 = digit_array[t0] t2 = length - 1 t2 = t2 - t0 while(t2>0): t1 = t1 *...
34381649e0af4d65e9f7b6d7df2fef93f90be41e
revathy1234/SocketsAndThreadManagement
/fclient.py
2,548
3.734375
4
#Revathy Ramamoorthy #https://realpython.com/python-sockets/ #https://www.geeksforgeeks.org/socket-programming-multi-threading-python/ #https://www.geeksforgeeks.org/socket-programming-python/ #https://stackabuse.com/basic-socket-programming-in-python/ #https://www.youtube.com/watch?v=SepyXsvWVfo #https://stackoverflow...
a24b726ae8f12ec3e8259348c002b61fc4dc1888
trb/instagram_challenge
/unshredder.py
14,737
3.59375
4
"""Unshreds a shredded image. In the documentation, "strip" refers to a verticle line of pixels from top to bottom of the image. A shred is a consecutive collection of strips that "belong together" (i.e. are found in the same order in the source image). This module attempts to identify various shreds in the image of v...
c5a6fcd2a08ac7787c2a94e65b1e3c93217119b0
VictorFavreau/Python-Project
/SearchData.py
4,654
3.75
4
import sqlite3 import json """ Function retrieving all cities associated with a zip code. :return: returns a list of city """ def city_dictionary(zip): """ Opening the database connection. """ conn = sqlite3.connect("python_project.db") c = conn.cursor() """ ...
c474537887d0c81e76194f4e4666ee72fa434bce
impks27/python-training
/day2/d13.py
363
3.640625
4
#lambda. For small functions instead of going to the function and executing # and coming back, it is better to copy the code at the pace of the call. # This is inline function in C++ or lamnda in python s=lambda x:x**2 print (s(10)) r=s(10) print (r) x=[('a',3),('c',2),('b',1)] y=sorted(x) print (y) ...
0c2c62418dbfaafe32d94dfea42120ff4e3c823b
impks27/python-training
/day1/w6.py
262
3.5625
4
#find the sum of sizes of python files #find the count of files and sub-dirs import os s=0 #picking and storing the directory entries x=os.listdir('.') for m in x: if os.path.isfile(m) and m[-3:]=='.py': t=os.path.getsize(m) s+=t print (s)
866b542822348c4b5b45888ec6af6a3e0b3f231b
impks27/python-training
/day3/oo2.py
363
3.71875
4
#Predefined class 'object' in python. Every class we create inherits object #class definition class temp(object): def accept(self,a,b): #self is object ref. self.eno=a self.ename=b def display(self): print (self.eno, self.ename) #object creation x=temp() #calling methods...
c3d61cd13a6b981803ad8bbc16c34ea8d844b735
impks27/python-training
/day2/d11.py
154
3.5625
4
#Map def f1(x): return (x**2) print (list(map(f1,[1,2,3,4,5]))) def f2(x,y): return (x*y) print (list(map(f2,range(1,10),range(11,20))))
7fd4179611e06f7d4924f7781d80275c75c30f46
jackbarrell/puzzler
/puzzle_solver.py
1,705
3.796875
4
def load_words(): with open('words_alpha.txt') as word_file: valid_words = set(word_file.read().split()) with open('first_names.all.txt') as word_file: first_names = set(word_file.read().split()) with open('last_names.all.txt') as word_file: last_names = set(word_file.read().split(...
da1e5e64b6aee2bb491e5a4b6d2cd57ec8e8a155
MondaleFelix/ARCHIVE-CS-2-Tweet-Generator
/histogram_tuple.py
546
4.03125
4
text = "one fish two fish red fish blue fish" def create_tuple(text): text = text.split() count_list = [] for word in text: count = text.count(word) word_count = (word, count) if word_count not in count_list: count_list.append( word_count) return count_list def unique_words(list): return len(list) def ...
0bbd773d72894e56a2b29f66bd64b7efe8542c18
zhaoguohan2020/CLAIRE
/SWMMandStratego/pond_online_control.py
8,850
3.515625
4
import csv import datetime import strategoutil as sutil import yaml def create_weather_forecast(rain_data_file, weather_forecast_file, start_date, horizon, uncertainty): """ Create a weather forecast from historical rain data. """ rain_data = read_rain_data(rain_data_file) ...
b9f3b5d9bbb11e292ad04ee507959a2294cedfca
janderson412/Test
/google-python-exercises/test1.py
191
3.75
4
#!/usr/bin/python -tt import sys def add(n1, n2): print float(n1) + float(n2) def main(): if (len(sys.argv) >= 3) : add(sys.argv[1],sys.argv[2]) if __name__ == '__main__': main()
559e1acb0a48a295e99ae2aa83eaab8a6b91d2ee
sparekh315/Data-Structures
/linked_list/linked_list.py
1,358
3.71875
4
""" Class that represents a single linked list node that holds a single value and a reference to the next node in the list """ class Node: def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def get_value(self): return self.value def get_next(self): retu...
6edecfd5ccd91ad570c0f60553079cf892687af7
kesh7644/cricquiz
/V4/v4_instructions.py
808
3.96875
4
##Asking if user wants instructions def inst(): inst = input("do you want to read the instructions if you enter anything except y it will not print the instructions :{}?: \na. Yes \nb. No \n=>") if inst == 'yes' or inst == 'Yes' or inst == 'y' or inst == 'Y' or inst == 'a' or inst == 'A': pr...
fdbb68de8e1bc356975e67067388bc7fb6357b47
kesh7644/cricquiz
/V1/v1_instructions.py
442
4.0625
4
#Ask if the user wants instructions ruel = input ("do you want instructions? Please enter y for yes or enter n for no : ") if ruel == 'y' or 'Y': print("Welcome to the quiz.") print("This quiz will ask you questions about the subject of sports") print("There will be one correct answer per question. E...
6fe4db70f82a7164f19156938f97834fdb66828d
Padmabala/Basic-DS
/GraphAdjacencyMatrix.py
3,558
3.59375
4
class Graph: def __init__(self,size): #self.adjMatrix={[]for i in range(size)} # for i in range(size): # self.adjMatrix.append([0 for i in range(size)]) self.adjList={} self.vCount=0 self.adjMatrix = {} for i in range(size): self.adjMatrix[i] =...
42a2c566db41e788c7ef4f3f3fefad21e07a457a
mehran-47/google_trace_analysis
/traceAnalyzer/correlation/temp.py
2,359
3.9375
4
import random as rand from pydoc import help from scipy.stats.stats import pearsonr import matplotlib.pyplot as plt import numpy as np """ pearsonr(x, y) Calculates a Pearson correlation coefficient and the p-value for testing non-correlation. The Pearson correlation coefficient measures the linear rel...
901a0be5cbea7c9f0ee6294e5950ab2550e392d5
nathan5280/ndl-tools
/src/ndl_tools/list_sorter.py
2,910
4.21875
4
""" ListSorters used to control if and how Lists are sorted. Really there are only two choices. Sort or don't sort. The sorter can be applied to the List elements by the Selector that is associated with the sorter. """ from abc import abstractmethod from pathlib import Path from typing import List, Optional, Union ...
27844e27421becf655c93e94893fc4eeb11e8193
cal-smith/Class
/COMP1005/a7/a7q4.py
999
3.59375
4
from __future__ import division import pygame # initialize pygame pygame.init() # set up the screen width = 640 height = 480 size = (width, height) screen = pygame.display.set_mode(size) class Ball(object): def __init__(self): self.ball = pygame.image.load("ball.png") self.ballrekt = self.ball.get_rect() self...
3f7860050a9d07e5c0b95c59ba79a28c338b2178
cal-smith/Class
/COMP1005/a5/a5.py
2,207
3.546875
4
def unique(a): b = set(a) y = [] for x in a: if x in b: y.append(x) b.remove(x) return y print "unique:", unique([2,1,3,1,4]) print "unique:", unique(map(int, str(12323523562234146890724)))#map(int, str()) returns a list of ints print "unique:", unique(map(int, str(1230462987546783159347860))) print "uniqu...
af7e87c3314092bb6a28a9b9287e83fcd359e495
latha-mada/algorithms
/sorting/factorial.py
143
4.09375
4
#!/usr/bin/python def factorial(n): if n==0: return 1 else: return n*factorial(n-1) n=3 print "factorial of 3=%d " %factorial(3)
660965aa9e1cd4869a1e4d149594a849a632ca1a
Fiinall/UdemyPythonCourse
/Advanced Functions & Decorators/InterbeddedFunctionsandFunctionParameters.py
2,869
3.8125
4
""" """ def a(*args): for i in args: print(i) a(1,2,3) print("----") def b(*xyz): for i in xyz: print(i) b(4,5,6) # As you can see, "agrs" is not necesserily. print("------------------") def c(string,*numbers): for i in numbers: print(string,i) c("Any String",4,7,3,12) print("-...
c472563f3f05f70fa12cbf772f3d8deacf2f2424
Fiinall/UdemyPythonCourse
/Embaded Functions/zipFunction.py
997
4.21875
4
""" Combining lists into one list. """ liste1 = [1, 2, 3, 4, 5] liste2 = [6, 7, 8, 9, 10, 11] liste3 = ["Python","Php","Java"] # sonucu [(1,6),(2,7),(3,8),(4,9),(5,10)] yapmaya çalışalım. #-------without zip funciton----- i = 0 sonuç = list() while (i < len(liste1) and i < len(liste2)): sonuç.append((liste1[i], ...
b14de33186c8d3f6d2f3b07602d41e34d40633cd
Fiinall/UdemyPythonCourse
/Conditional Statement/Hesap Makinesi.py
1,023
4.3125
4
print("""Welcome to Calculator Here are the operations that you can do 1. Summation 2. Extraction 3. Multiplication 4. Division Please Selecet the Operatiıon with + , - , * or / """) First_Number = float(input("What is your first number")) Operation = input("What...
c2aa28ef1639e050fe92756f1a7c6834d69b75f5
Fiinall/UdemyPythonCourse
/Advanced Data Structures and Object/AdvancedListsAndItsMethods.py
2,397
4.625
5
# extend() method is like append method but this help you for add whole list into another list; print("extend method; \n") list1 = [1,2,3,4] list2 = [45,6893,245,667,"asd"] list1.extend(list2) print(list1) print("---------") # insert(index,element) method inserts an element into specified index print("insert method; \n...
bd0fb25069d3ccbdedc101f4f55bd5dcf963bc6a
achiodza/MAWS
/HMAC SCRIPT/hmac_for_text.py
628
3.515625
4
import hashlib def _msg(): print("Select 1 for Hashing your Message") print("Select 2 to check integrity your Message") def decision(): number=int(input()) return(number) #Function to hash def _hash(x): sha256 = hashlib.sha256() sha256.update(x) msg_digest=sha256.digest() _thevalue=m...
e48af00582fb77a5b85a6f1512d2ab46f028fc6d
EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions
/Chapter8/8.8.py
732
3.921875
4
#8.8 #Permutations with Dups: #Write a method to compute all permutations of a string whose characters are not necessarily unique. #The list of permutations should not have duplicates. def permutations(string): return partial_permutations("", sorted(string)) def partial_permutations(partial, letters): if len(...
2c2b81072cc28becd38279d44792a6bd949e6e42
EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions
/Chapter5/5.4.py
529
3.546875
4
#5.4 #Next Number: Given a positive integer, #print the next smallest and the next largest number that have the same number of 1 bits in their binary representation. def get_next(number): #compute c0 and c1 c = n c0 = 0 c1 = 0 while(c&1) ==0 and c!=0: c0+=1 c>>=1 while(c&1 ==1):...
3ae1a7a089d9054ca47a6412d6834d35be1448de
EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions
/Chapter1/1.9.py
582
4.4375
4
#String Rotation; Assume you have a method i s S u b s t r i n g which checks if one word is a substring of another. #Given two strings, si and s2, write code to check if s2 is a rotation of si using only one call to isSubstring # [e.g., "waterbottle" is a rotation oP'erbottlewat"), def string_rotation(s1, s2): i...
12cc78a6ac3cfb8c8c6bfd220941b01cd2b1d0db
EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions
/Chapter8/8.4.py
658
3.9375
4
#8.4 Power Set: Write a method to return all subsets of a set. def getSubsets(set): allSubsets = [] #result array to return all subsets max = 1 << len(set) #len = 4 if do left shift it is 16 for k in range(max): subset = convertIntToSet(k, set) allSubsets.append(subset) return allSubse...