blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
6b582bf7eb3e5e3fc4ae9912c68cd2be5dccac6d | sashakrasnov/datacamp | /14-interactive-data-visualization-with-bokeh/1-basic-plotting-with-bokeh/08-plotting-data-from-pandas-dataframes.py | 1,796 | 4.21875 | 4 | '''
Plotting data from Pandas DataFrames
You can create Bokeh plots from Pandas DataFrames by passing column selections to the glyph functions.
Bokeh can plot floating point numbers, integers, and datetime data types. In this example, you will read a CSV file containing information on 392 automobiles manufactured in ... | true |
cf5ed84b81c429740decf635f089ce6cf2b1b1a4 | sashakrasnov/datacamp | /24-data-types-for-data-science/2-dictionaries--the-root-of-python/06-working-with-dictionaries-more-pythonically.py | 1,852 | 4.25 | 4 | '''
Popping and deleting from dictionaries
Often, you will want to remove keys and value from a dictionary. You can do so using the del Python instruction. It's important to remember that del will throw a KeyError if the key you are trying to delete does not exist. You can not use it with the .get() method to safely d... | true |
4ea71b51359e8486ed5c5e65bea639653363814b | sashakrasnov/datacamp | /19-machine-learning-with-the-experts-school-budgets/2-creating-a-simple-first-model/06-combining-text-columns-for-tokenization.py | 2,114 | 4.125 | 4 | '''
Combining text columns for tokenization
In order to get a bag-of-words representation for all of the text data in our DataFrame, you must first convert the text data in each row of the DataFrame into a single string.
In the previous exercise, this wasn't necessary because you only looked at one column of data, so... | true |
1b100714dada7b59a0ebab1e83f8de2d942aead0 | sashakrasnov/datacamp | /28-machine-learning-for-time-series-data-in-python/3-predicting-time-series-data/01-introducing-the-dataset.py | 1,453 | 4.53125 | 5 | '''
Introducing the dataset
As mentioned in the video, you'll deal with stock market prices that fluctuate over time. In this exercise you've got historical prices from two tech companies (Ebay and Yahoo) in the DataFrame prices. You'll visualize the raw data for the two companies, then generate a scatter plot showing... | true |
ff58963682d6b0c385af84e7cfd8e569ebb0f43c | sashakrasnov/datacamp | /21-deep-learning-in-python/2-optimizing-a-neural-network-with-backward-propagation/01-coding-how-weight-changes-affect-accuracy.py | 2,751 | 4.4375 | 4 | '''
Coding how weight changes affect accuracy
Now you'll get to change weights in a real network and see how they affect model accuracy!
Have a look at the following neural network: https://s3.amazonaws.com/assets.datacamp.com/production/course_3524/datasets/ch2ex4.png
Its weights have been pre-loaded as weights_0. ... | true |
c909f3767520223e6be10318e530cbc924ef2b76 | sashakrasnov/datacamp | /24-data-types-for-data-science/2-dictionaries--the-root-of-python/01-creating-and-looping-through-dictionaries.py | 1,832 | 4.90625 | 5 | '''
Creating and looping through dictionaries
You'll often encounter the need to loop over some array type data, like in Chapter 1, and provide it some structure so you can find the data you desire quickly.
You start that by creating an empty dictionary and assigning part of your array data as the key and the rest as... | true |
a31ee59404efdb8fa7481075543179c1fec6412b | sashakrasnov/datacamp | /08-pandas-foundations/1-data-ingestion-and-inspection/05-reading-a-flat-file.py | 1,610 | 4.4375 | 4 | '''
Reading a flat file
In previous exercises, we have preloaded the data for you using the pandas function read_csv(). Now, it's your turn! Your job is to read the World Bank population data you saw earlier into a DataFrame using read_csv(). The file has been downloaded as world_population.csv.
The next step is to r... | true |
341a39673f57049a3f28d111b7b4e46428714cc8 | sashakrasnov/datacamp | /26-manipulating-time-series-data-in-python/1-working-with-time-series-in-pandas/04-set-and-change-time-series-frequency.py | 1,210 | 4.1875 | 4 | '''
Set and change time series frequency
In the video, you have seen how to assign a frequency to a DateTimeIndex, and then change this frequency.
Now, you'll use data on the daily carbon monoxide concentration in NYC, LA and Chicago from 2005-17.
You'll set the frequency to calendar daily and then resample to month... | true |
5a33d4bb2add5882a2a6637aecf90330ed47776d | sashakrasnov/datacamp | /14-interactive-data-visualization-with-bokeh/1-basic-plotting-with-bokeh/09-the-bokeh-columndatasource.py | 1,733 | 4.125 | 4 | '''
The Bokeh ColumnDataSource (continued)
You can create a ColumnDataSource object directly from a Pandas DataFrame by passing the DataFrame to the class initializer.
In this exercise, we have imported pandas as pd and read in a data set containing all Olympic medals awarded in the 100 meter sprint from 1896 to 2012... | true |
f8cdaee2db28f409fc8bf13ea75d0abb9a509a99 | sashakrasnov/datacamp | /22-network-analysis-in-python-1/4-bringing-it-all-together/08-finding-important-collaborators.py | 1,909 | 4.125 | 4 | '''
Finding important collaborators
Almost there! You'll now look at important nodes once more. Here, you'll make use of the degree_centrality() and betweenness_centrality() functions in NetworkX to compute each of the respective centrality scores, and then use that information to find the "important nodes". In other ... | true |
21fce1ba844f4c7273ed86a18e21b7725bc92f5f | sashakrasnov/datacamp | /24-data-types-for-data-science/1-fundamental-data-types/06-determining-set-differences.py | 1,822 | 4.65625 | 5 | '''
Determining set differences
Another way of comparing sets is to use the difference() method. It returns all the items found in one set but not another. It's important to remember the set you call the method on will be the one from which the items are returned. Unlike tuples, you can add() items to a set. A set wil... | true |
8b9d573be4b1eebe8a6d3ee66252f8c3442890a0 | sashakrasnov/datacamp | /29-statistical-simulation-in-python/2-probability-and-data-generation-process/03-game-of-thirteen.py | 1,668 | 4.40625 | 4 | '''
Game of thirteen
A famous French mathematician Pierre Raymond De Montmart, who was known for his work in combinatorics, proposed a simple game called as Game of Thirteen. You have a deck of 13 cards, each numbered from 1 through 13. Shuffle this deck and draw cards one by one. A coincidence is when the number on t... | true |
d2f59c0803cbe2036e08d903216d7fb254a8fa1b | sashakrasnov/datacamp | /29-statistical-simulation-in-python/1-basics-of-randomness-and-simulation/05-simulating-the-dice-game.py | 1,556 | 4.46875 | 4 | '''
Simulating the dice game
We now know how to implement the first three steps of a simulation. Now let's consider the next step - repeated random sampling.
Simulating an outcome once doesn't tell us much about how often we can expect to see that outcome. In the case of the dice game from the previous exercise, it's... | true |
f8bf2d9477abd2cfef2629ad87f03ce171d34e26 | sashakrasnov/datacamp | /22-network-analysis-in-python-1/3-structures/01-identifying-triangle-relationships.py | 2,208 | 4.125 | 4 | '''
Identifying triangle relationships
Now that you've learned about cliques, it's time to try leveraging what you know to find structures in a network. Triangles are what you'll go for first. We may be interested in triangles because they're the simplest complex clique. Let's write a few functions; these exercises wi... | true |
fd12b8f0353d46fac24d7d2efd50ba1185a290a5 | sashakrasnov/datacamp | /07-cleaning-data-in-python/4-cleaning-data-for-analysis/06-custom-functions-to-clean-data.py | 2,461 | 4.21875 | 4 | '''
Custom functions to clean data
You'll now practice writing functions to clean data.
The tips dataset has been pre-loaded into a DataFrame called tips. It has a 'sex' column that contains the values 'Male' or 'Female'. Your job is to write a function that will recode 'Male' to 1, 'Female' to 0, and return np.nan f... | true |
b754d2966c71ec0c22f1af9caa7bdf933f8c3616 | sashakrasnov/datacamp | /11-analyzing-police-activity-with-pandas/1-preparing-the-data-for-analysis/03-dropping-rows.py | 1,300 | 4.46875 | 4 | '''
Dropping rows
When you know that a specific column will be critical to your analysis, and only a small fraction of rows are missing a value in that column, it often makes sense to remove those rows from the dataset.
During this course, the driver_gender column will be critical to many of your analyses. Because on... | true |
c6c9a3c3dc132e3cfb2cfc349f23350c9d163dba | sashakrasnov/datacamp | /04-python-data-science-toolbox-2/3-bringing-it-all-together!/07-writing-a-generator-to-load-data-in-chunks-3.py | 1,737 | 4.46875 | 4 | '''
Writing a generator to load data in chunks (3)
Great! You've just created a generator function that you can use to help you process large files.
Now let's use your generator function to process the World Bank dataset like you did previously.
You will process the file line by line, to create a dictionary of the co... | true |
5ca7c9d133c9dcf4a63deed0f3741827294f3203 | sashakrasnov/datacamp | /32-introduction-to-pyspark/2-manipulating-data/03-selecting.py | 1,895 | 4.5 | 4 | '''
The Spark variant of SQL's SELECT is the .select() method. This method takes multiple arguments - one for each column you want to select. These arguments can either be the column name as a string (one for each column) or a column object (using the df.colName syntax). When you pass a column object, you can perform o... | true |
6ed2d41343506384911094ba689c134531af95a4 | sashakrasnov/datacamp | /26-manipulating-time-series-data-in-python/4-putting-it-all-together-building-a-value-weighted-index/03-import-index-component-price-information.py | 1,973 | 4.125 | 4 | '''
Import index component price information
Now you'll use the stock symbols for the companies you selected in the last exercise to calculate returns for each company.
'''
import pandas as pd
import matplotlib.pyplot as plt
listings = pd.read_excel('../datasets/stock_data/listings.xlsx', sheet_name='nyse', na_value... | true |
7056ea7898204358ce56b6d531df2f3fe587ffcb | sashakrasnov/datacamp | /10-merging-dataframes-with-pandas/2-concatenating-data/04-concatenating-pandas-dataframes-along-column-axis.py | 2,317 | 4.15625 | 4 | '''
Concatenating pandas DataFrames along column axis
The function pd.concat() can concatenate DataFrames horizontally as well as vertically (vertical is the default). To make the DataFrames stack horizontally, you have to specify the keyword argument axis=1 or axis='columns'.
In this exercise, you'll use weather dat... | true |
0a7757a9fa33be538833f52f832c9872ff36c672 | sashakrasnov/datacamp | /10-merging-dataframes-with-pandas/1-preparing-data/04-sorting-dataframe-with-the-index-and-columns.py | 2,593 | 4.96875 | 5 | '''
Sorting DataFrame with the Index & columns
It is often useful to rearrange the sequence of the rows of a DataFrame by sorting. You don't have to implement these yourself; the principal methods for doing this are .sort_index() and .sort_values().
In this exercise, you'll use these methods with a DataFrame of tempe... | true |
32de5c51962ed107e39b8c67a51b85be88214d39 | sashakrasnov/datacamp | /27-visualizing-time-series-data-in-python/4-work-with-multiple-time-series/01-load-multiple-time-series.py | 1,332 | 4.125 | 4 | '''
Load multiple time series
Whether it is during personal projects or your day-to-day work as a Data Scientist, it is likely that you will encounter situations that require the analysis and visualization of multiple time series at the same time.
Provided that the data for each time series is stored in distinct colu... | true |
0b8caa4f6f082d1f8c456b94dc1e87903a66f69e | sashakrasnov/datacamp | /24-data-types-for-data-science/2-dictionaries--the-root-of-python/04-adding-and-extending-dictionaries.py | 2,763 | 4.65625 | 5 | '''
Adding and extending dictionaries
If you have a dictionary and you want to add data to it, you can simply create a new key and assign the data you desire to it. It's important to remember that if it's a nested dictionary, then all the keys in the data path must exist, and each key in the path must be assigned indi... | true |
bbfd20e82c8d9bfe591e3345ed94c2e94702eb7e | sashakrasnov/datacamp | /12-introduction-to-databases-in-python/4-creating-and-manipulating-your-own-databases/06-updating-individual-records.py | 2,179 | 4.28125 | 4 | '''
Updating individual records
The update statement is very similar to an insert statement, except that it also typically uses a where clause to help us determine what data to update. You'll be using the FIPS state code using here, which is appropriated by the U.S. government to identify U.S. states and certain other... | true |
9d47888970d4d2bba4d9555352eb0a23c2e17a2d | sashakrasnov/datacamp | /18-linear-classifiers-in-python/3-logistic-regression/01-regularized-logistic-regression.py | 1,519 | 4.1875 | 4 | '''
Regularized logistic regression
In Chapter 1 you used logistic regression on the handwritten digits data set. Here, we'll explore the effect of L2 regularization. The handwritten digits dataset is already loaded, split, and stored in the variables X_train, y_train, X_valid, and y_valid. The variables train_errs an... | true |
4d1c8c000e06f5459daf9ce36ffc09a46bab346d | sashakrasnov/datacamp | /17-supervised-learning-with-scikit-learn/1-classification/02-k-nearest-neighbors-predict.py | 2,532 | 4.28125 | 4 | '''
k-Nearest Neighbors: Predict
Having fit a k-NN classifier, you can now use it to predict the label of a new data point. However, there is no unlabeled data available since all of it was used to fit the model! You can still use the .predict() method on the X that was used to fit the model, but it is not a good indi... | true |
eda2584a11a3e4fb1a77f8082ce455df3b4c4713 | Xinyuan-wur/algorithms-in-bioinformatics | /clustering/assignment_kmeans_skeleton.py | 1,917 | 4.25 | 4 | #!/usr/bin/env python
"""
Author:
Student number:
Implementation of the k-means clustering algorithm
Hints:
- write a function to obtain Euclidean distance between two points.
- write a function to initialize centroids by randomly selecting points
from the initial set of points. You can use the random.sample() me... | true |
c162c550ba25f29822159f0c4fca5421e1dedd37 | 12reach/PlayWithPython | /primary/functions.py | 1,622 | 4.6875 | 5 | #!/usr/bin/python3
# functions and parameters are two important part of a program
# a function do the repetitive job so that we need not write same thing more and more
# functions do many things
# we will see it later in our detailed functions series
# let us define a function that pass two parameters and those param... | true |
47abb2cb7a63f713e2e3e6ef9f501cbaf080bfc0 | 12reach/PlayWithPython | /classes/fish.py | 2,156 | 4.78125 | 5 | #!/usr/bin/python3
# this is fish class and we will have some base classes from it
class fishClass:
pass
class ChildFish(fishClass):
print("Hi I am a child fish and I came from troubled water.")
fan1 = ChildFish()
print(fan1)
# the output looks like thsi Hi I am Salman Khan and I am a fish from troubled w... | true |
0f7c3256ea06e9ebc2ce49911531b2ded494fdc8 | genesisazor/homework | /Chapter6/question3.py | 408 | 4.25 | 4 | def day_num(day_name):
"""takes a day name and returns a number 0-6"""
if day_name == "Sunday":
return 0
elif day_name == "Monday":
return 1
elif day_name == "Tuesday":
return 2
elif day_name == "Wednesday":
return 3
elif day_name == "Thursday":
return 4
... | true |
36b7883049cca2cb6cbeb6eb35f5ebf4bd6cabda | ddmin/CodeSnippets | /PY/Playground/strip.py | 466 | 4.21875 | 4 | import re
def strip(string, chr = '\s'):
"""
Implementation of Python's Strip Method.
Parameters:
string (String): Target string.
chr (String): Character(s) to strip. Defaults to whitespace character.
Returns:
String: A string with the ch... | true |
1e4468fbb0a6bbcd95737b3edfc77e7c51299e55 | yasir-web/pythonprogs | /recursion.py | 202 | 4.25 | 4 | #wap to find the factorial of given number using recurssion
def fact(n):
if n==0 or n==1:
return 1
else:
return n*fact(n-1)
x=int(input("Enter the number: "))
f=fact(x)
print(f)
| true |
c65d07396bfd58be933ca0edc17e9cbb02920471 | yasir-web/pythonprogs | /hierarchial.py | 503 | 4.46875 | 4 | #WAP to demonstrate concept of hierarchial Inheritence
class figure:
def setvalue(self,s):
self.s=s
class square(figure):
def area(self):
return self.s*self.s
class cube(figure):
def volume(self):
return self.s*self.s*self.s
#Now we test the class
sq=square()
cu=cube()
side=int(input... | true |
3a238c088626cbea712db233924a841d90a616d2 | Z3DDev/DatabaseManagement | /Assignment2/assign2.py | 2,459 | 4.21875 | 4 | # Zach Jagoda
# Student ID: 2274813
# Student Email: jagod101@mail.chapman.edu
# CPSC408 Database Management
# Assignment 2: SQLite Lab
import sqlite3
conn = sqlite3.connect('studentdb.db')
c = conn.cursor()
loop = 1
while loop == 1:
print("Please Select An Option")
text = input("1. Display All Stude... | true |
7bbff704ba253fb8419225cf47ba7be3b17c15bb | nayyanmujadiya/ML-Python-Handson | /src/pandas/dict_to_pd.py | 982 | 4.21875 | 4 | import pandas as pd
#dict is given
sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000}
obj3 = pd.Series(sdata)
print(obj3)
'''
When you are only passing a dict, the index in the resulting Series will
have the dict’s keys in sorted order. You can override this by passing
the dict keys in the order yo... | true |
728c03ca26f01391b06c7ffed4708ff07bd9c2a1 | nayyanmujadiya/ML-Python-Handson | /src/basic_index_np.py | 688 | 4.34375 | 4 | import numpy as np
arr = np.arange(10)
print(arr)
print(arr[5])
print(arr[5:8])
# assign scalar to slice
arr[5:8] = 12
print(arr)
'''
An important first distinction from Python’s built-in lists is that array slices are views on the original array. This means that the data is not copied, and any modifications to the v... | true |
64c894b1c64a64cfd791de76e4e17e99abda7750 | nayyanmujadiya/ML-Python-Handson | /src/ml/baseball_mult_reg.py | 2,785 | 4.125 | 4 | #Step 1: Import libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
'''
data source:
https://college.cengage.com/mathematics/brase/understandable_... | true |
c0fe2894662d81ae0bd815acee999bdc4b2684ed | rtduany/personal-development | /Insert.py | 459 | 4.5625 | 5 | # Dash Insert
# Using python, have the function DashInsert(str) insert dashes ('-') between each two odd numbers in string.
# For example: if str is 454793 the output should be 4547-9-3. Don't count zero as an odd number.
def DashInsert(str):
#first lets iterate thru the function
for i in str:
#turn the string to i... | true |
09c8ec2a5c0dc092337fa7337f399533d0f3cf7a | macknilan/Cuaderno | /Python/Code_examples/05_iterators/iterator_basics.py | 1,581 | 4.34375 | 4 | from dataclasses import dataclass
@dataclass
class Item:
name: str
weight: float
def main() -> None:
inventory = [
Item("laptop", 1.5),
Item("phone", 0.5),
Item("book", 1.0),
Item("camera", 1.0),
Item("headphones", 0.5),
Item("charger", 0.5),
]
i... | true |
41068a9aa46eb97b3cee209cef947c9f52538a54 | harut0601/youtube-videos | /video2/problem3.py | 459 | 4.25 | 4 | temperature = int(input("The outside temperature: "))
unit = input("(C)elsius or (F)ahrenheit: ")
if unit.upper() == "C":
final_temperature = (temperature * 1.8 + 32)
elif unit.upper() == "F":
final_temperature = ((temperature - 32) * 5/9)
else:
print("Please try again!")
final_temperature = "Not defin... | true |
7ef4b9293d5060777f8d3a4b424c025e7d10180f | rajilaxmi/python | /functions/6.cases.py | 450 | 4.34375 | 4 | # to coount the number of uppercase and lowercase alphabet in a string
def counting(str1):
d={"upper":0,"lower":0}
for c in str1:
if c.isupper():
d["upper"]+=1
elif c.islower():
d["lower"]+=1
else:
pass
print "Number of uppercase alphabets: %d"%d["upper"]
print "Number of lowercase alphabets: %d"%d["... | true |
a27469903e1dd03705ad938807acbfac708fe8c8 | halasdhowre/TTA-halasdhowre | /HLT 3.py | 2,237 | 4.15625 | 4 | #################################Home Learning Task 3
#Q1
#Write a program that allows you to enter 4 numbers and stores them in a file called “Numbers”
#• 3
#• 45
#• 83
#• 21
#Have a go at ‘w’ ‘r’ ‘a’
file_1 = open("GitHub/TTA-halasdhowre/Submitted HLT/Numbers.txt", "r")
print(file_1.read())
file_1.close... | true |
86f49db5f9e996f883c843ed8457b49dfd679963 | KavitaPatidar/100DaysPythonCode_BeginnerLevel | /HangMan.py | 869 | 4.1875 | 4 | import random
from design import word_list, logo, stages
print(logo)
word= random.choice(word_list)
print(word)
display=[]
for letter in word:
# or display+= "_"
display.append("_")
# print(display)
guess_continue= True
lives=6
while guess_continue:
guess= input("guess a letter: ").lower()
if guess... | true |
50aaa7b8ea7b522fa3bdf039ac413149a0798500 | choisoonsin/python3 | /design_pattern/decorators/classmethod.py | 697 | 4.375 | 4 | class Person:
population = 0
def __init__(self, name, age):
self.name = name
self.age = age
Person.population += 1
@classmethod
def get_population(cls):
return cls.population
if __name__ == '__main__':
"""
In this example, we define a Person class with a p... | true |
6b84eabc00ee49c5a3334f182865ac48ed1d015e | JingYiTeo/2019_ALevel_CP_Notes | /Sorting/Bubble Sort (Not Optimized).py | 714 | 4.21875 | 4 | def bubble_sort(A):
#assume not sorted
swapped = True
#while swapped: as long as its not swapped
while swapped:
swapped = False
#for loop: iterate through all the elements from index 1 to end
for i in range(1, len(A)):
#if the previous element > elem... | true |
95270ce3b015709f114eb1fda9eac6dbad6394a2 | JingYiTeo/2019_ALevel_CP_Notes | /Searching/Binary Search.py | 926 | 4.34375 | 4 | #binary search needs the data/array/list to be sorted before it can search.
def binary_search(elements, target, low, high):
#define the middle item index
mid = (high + low) // 2
if low > high: # not found
return -1
#target is exactly in the middle of array
elif elements[mid] == ... | true |
f8809724342461be3a1269d8bc275ed4e1fa82c9 | srusher/Python-for-Data-Science-and-Machine-Learning | /4. Pandas/6_Pandas_GroupBy.py | 861 | 4.25 | 4 | import numpy as np
import pandas as pd
from numpy.random import randn
np.random.seed(101)
# think of the GroupBy function in Pandas as the GroupBy clause in SQL
## In SQL: typically used for aggregate functions and returns values for each distinct row
# Create dataframe
data = {'Company':['GOOG','GOOG'... | true |
15fe34a8bf17cad25a3d2c9af5d34abb2f23d96a | abhi8893/Intensive-python | /exercises/get_initials.py | 757 | 4.15625 | 4 | # Write a program that takes a full name, prints the initials of the first,
# middle, and last name. If the middle name is “NA”, then the program
# should print only the initials of the first and the last name.
def get_initials(name):
""" Return initials of first, last and middle name.
If the middle na... | true |
315d4db0cfcf49ba4a8ea2f389a91df1cf48d257 | abhi8893/Intensive-python | /exercises/3D_to_2D_lists.py | 1,097 | 4.5 | 4 | ''' Define a function that takes a 3-D list and
converts it to a 2-D list in-place. '''
def get_2D(lst):
""" Convert the list to 2-D in-place.
my_list = [[['item1','item2']],[['item3', 'item4']]]
>>> get_2D(my_list)
[['item1', 'item2'], ['item3', 'item4']]
"""
lst = lst.copy()
... | true |
df49417c2647d7e197a6965086c38432c65b69b3 | abhi8893/Intensive-python | /exercises/conv_to_unqouted_str.py | 791 | 4.125 | 4 | # Convert a string such that it is not surrounded by quotes.
def unquoted_str(s: str):
'''Converts a string into an unquoted string'''
# TODO: use regex
# NOTE: Not requiring an s argument, as it seems cleaner
# and also unneccesary if function is just for
# internal consumption.
... | true |
b9b2511443d106aaf24b70eacd9a46936ad55375 | DRMPN/PythonCode | /CS50/ProblemSet6/dna/dna.py | 2,496 | 4.15625 | 4 | # program that identifies a person based on their DNA
import sys
import csv
def main():
# correct usage check
if len(sys.argv) != 3:
sys.exit("Usage: python dna.py data.csv sequence.txt")
# list of dictionaries
database = []
# read people's dna from a database
with open(sys.argv[1])... | true |
58c4b69005958b9e0045fe641743d35de724104d | Hassan-Farid/PyTech-Review | /Python Intermediate/Sequences and Iterables/Naming Slices.py | 2,775 | 4.28125 | 4 | '''
Assume that we want to extract a certain slice from a particular long list
'''
#Suppose we are provided a large list with lots and lots of numbers and you want to get the sum of a particular bunch
#We can take a random list of numbers using the random.randint() method and then sum the specified slices
#Normally w... | true |
74ca3e8d21e709ac9128421aaed93259e8081059 | Hassan-Farid/PyTech-Review | /Python Intermediate/Sequences and Iterables/Implementing Priority Queue.py | 1,794 | 4.375 | 4 | '''
Assume you want to implement a priority queue that sorts items in a queue based on their priority
'''
#A priority queue is an ADT similar to a queue which functions the same way as a queue (FIFO order) but pops/deques elements based on priority
#We will now create a class PriorityQueue and use another class Marks... | true |
de812795776b9ea6083669adb85e0002bb8d7e27 | Hassan-Farid/PyTech-Review | /Python Intermediate/Sequences and Iterables/Sorting List of Dictionaries using Common Key.py | 1,298 | 4.40625 | 4 | '''
Assume you want to sort a list of dictionaries with one or more of its keys
'''
#Suppose an institute conducts a test based on Maths and English marks and assigns positions to students based on their marks in these two subjects
#Suppose we are provided a list containing the json data for the students and the marks... | true |
fac8e73dca7850bef6a22dfc2794756083c10686 | Hassan-Farid/PyTech-Review | /Python Basics/Iteration Statements/NestedLooping.py | 1,713 | 4.5625 | 5 | '''
Sometimes a single loop is not enough for the application we have to peform, thus, we need to use loops within loops
This use of loops within loops is known as Nested Looping and is quite used in application development
'''
#Using nested looping to find a palindrome
text = "level"
isPalindrome = False
for ... | true |
237de905fac906dea8f4fd0439a4ebe71e79ab9c | Hassan-Farid/PyTech-Review | /Python Intermediate/Text Processing/String Matching using WildCard Patterns.py | 1,777 | 4.25 | 4 | '''
Assume you want to match text using commonly used Unix wildcard characters
'''
#Suppose a company has a list of different file formats and they want to obtain only the ones with .csv in the end
#We can use the Unix wildcard pattern with the list of files using the fnmatch module
#fnmatch provides functionaliti... | true |
a7792b1a3a562cd2acca963f99822b16d0de629f | aggressiveapple5/problemSet0 | /ps0.py | 2,118 | 4.1875 | 4 | #0
def is_even(number):
''' Takes user input and returns True if number is even and False if odd'''
while number > 1:
number -= 2
if number == 1:
even = False
else:
even = True
return(even)
#1
def number_digits(number):
'''Takes a non-negative number as input and returns the number of digits in the number'... | true |
9687dd20d0579cb75056693ad133d32fded15488 | rahulgupta020/bscit-practical | /4c.py | 271 | 4.15625 | 4 | #Write a Python program to clone or copy a list
#Method1
original_list=[1,2,3,4,5]
print("Original List = ",original_list)
new_list=list(original_list)
print("New List = ",new_list)
print()
#Method
og=[6,7,8,9,10]
print("OG = ",og)
copy=og.copy()
print("COPY = ",copy) | true |
2351a19868108f4b61bd32fcf805f16ae0b6ae8e | eranandagarwal/callbacks | /more_callback.py | 1,909 | 4.28125 | 4 | import time
def slow_calculation(cb = None):
res = 0
for i in range(5):
res += i * i
time.sleep(1)
if cb:
cb(i)
return res
# what if we do not define a function for callback, instead use lambda for same
slow_calculation(lambda num: print (f"Yay !! we hav... | true |
ccee0cfb15b744983325e9557b73dfc55f99f63e | group6bse1/BSE-2021 | /src/chapter3/exercise2.py | 749 | 4.28125 | 4 | #handling any errors that might occur during execution if user input is wrong
try:
# accepting Hours from user which is an integer
hours = float(input('Please enter hours: '))
# accepting rate per hour from the user which is float value-
rate = float(input('please enter rate :'))
if hours > 40:
... | true |
37613fa2186eaa07a55b0fbf99bf7164165fe78c | group6bse1/BSE-2021 | /src/chapter2/excercise5.py | 341 | 4.40625 | 4 | # x is the temperature in degrees celsius to be input
x = float(input('Enter temperature in \N{DEGREE SIGN}C :'))
#y is the temperature in fahranheit
# formula for computing the conversion
y = (9/5)*x+32
print("Converting...", x, "\N{DEGREE SIGN}C to Fahrenheit")
print("Temperature is: ", y, "\N{DEGREE SIGN}F") #prin... | true |
a5a47ec2a87e4db6d6e284b99f6ae38ae5634d29 | group6bse1/BSE-2021 | /src/chapter3/exercise1.py | 465 | 4.28125 | 4 | #accepting Hours from user which is an integer
hours = float(input('Please enter hours: '))
#accepting rate per hour from the user which is float value-
rate = float(input('please enter rate :'))
if hours > 40:
#calculating the gross pay if hours worked are more than 40
pay = hours * (1.5 * rate)
else:
#calculati... | true |
31e06eb0baf27a658a4637eff8fd38c5878d0d28 | ariana124/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/6-print_sorted_dictionary.py | 277 | 4.1875 | 4 | #!/usr/bin/python3
"""
Module that contains the function print_sorted_dictionary
"""
def print_sorted_dictionary(a_dictionary):
""" prints a dictionary by ordered keys """
for key in sorted(a_dictionary.keys()):
print("{}: {}".format(key, a_dictionary[key]))
| true |
ca3516edbf5c86ed923c27a7f870f43da53dc6f0 | ariana124/holbertonschool-higher_level_programming | /0x03-python-data_structures/10-divisible_by_2.py | 432 | 4.375 | 4 | #!/usr/bin/python3
"""
Module containing the function divisible_by_2
"""
def divisible_by_2(my_list=[]):
""" returns a new list with True or False, depending on whether the integer
at the same position in the original list is a multiple of 2 """
new_list = []
for number in my_list:
if number %... | true |
4d2ee71bb0efbec3cdab08b8d4f04f88dad574d6 | arya-hemanshu/algorithms | /merge_sort.py | 1,387 | 4.375 | 4 |
"""
A python implementation of merge sort,
complexity of merge sort is O(NlogN)
Args:
unsorted array of numbers or letters
Output:
sorted array of number or letters
How to use:
python merge_sort.py <space seperated numbers or letters>
"""
def merge_sort(list_to_sort):
if len(list_to_sort) == 1:
... | true |
6465a846fcbb8d5f07f0e54f2a6069b0d0603e15 | arthurDz/algorithm-studies | /leetcode/binary_tree_paths.py | 670 | 4.125 | 4 | # Given a binary tree, return all root-to-leaf paths.
# Note: A leaf is a node with no children.
# Example:
# Input:
# 1
# / \
# 2 3
# \
# 5
# Output: ["1->2->5", "1->3"]
# Explanation: All root-to-leaf paths are: 1->2->5, 1->3
def binaryTreePaths(self, root):
if not root: return
def pa... | true |
a0a67d39beea8a413918c846ebc0c188f8797a6c | arthurDz/algorithm-studies | /linkedin/binary_tree_upside_down.py | 1,247 | 4.21875 | 4 | # Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.
# Example:
# Input: [1,2,3,4,5]
# 1
# / \
#... | true |
94ab33ed9269014316effea13fc61a468cbac5bb | arthurDz/algorithm-studies | /leetcode/valid_palindrome.py | 502 | 4.1875 | 4 | # Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
# Note: For the purpose of this problem, we define empty string as valid palindrome.
# Input: "A man, a plan, a canal: Panama"
# Output: true
def isPalindrome(s):
if s == "":
return True
s... | true |
454abe0ec9c3efc65f263290f62d498ad6311a83 | arthurDz/algorithm-studies | /leetcode/number_of_operations_to_make_network_connected.py | 2,209 | 4.15625 | 4 | # There are n computers numbered from 0 to n-1 connected by ethernet cables connections forming a network where connections[i] = [a, b] represents a connection between computers a and b. Any computer can reach any other computer directly or indirectly through the network.
# Given an initial computer network connection... | true |
204096f4c74c5445b2d154f8d086102530108a9d | arthurDz/algorithm-studies | /leetcode/display_table_of_food_orders_in_a_restaurant.py | 2,957 | 4.46875 | 4 | # Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders.
# Return the restaura... | true |
01232d78e27044360a9bc8d0cb3c3a8f158266f6 | arthurDz/algorithm-studies | /linkedin/print_binary_tree.py | 2,633 | 4.28125 | 4 | # Print a binary tree in an m*n 2D string array following these rules:
# The row number m should be equal to the height of the given binary tree.
# The column number n should always be an odd number.
# The root node's value (in string format) should be put in the exactly middle of the first row it can be put. The colu... | true |
f65a9d54eb9db6eb1b51e4b4732f3dcad8d65e34 | arthurDz/algorithm-studies | /CtCl/Bit Manipulation/conversion.py | 741 | 4.28125 | 4 | # Conversion: Write a function to determine the number of bits you would need to flip to convert integer A to integer B.
# EXAMPLE
# Input: 29 (or: 11101), 15 (or: (1111) Output: 2
def conversion(num1, num2):
count = 0
while num1 and num2:
if (num1 & 1) ^ (num2 & 1) == 1:
count += 1
... | true |
0778a363d71d0d111be0d516ca5368f76a439f32 | arthurDz/algorithm-studies | /leetcode/path_with_minimum_effort.py | 2,138 | 4.21875 | 4 | # You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can mov... | true |
bd332ff87b40738895782ee99864ea8b7142ed71 | arthurDz/algorithm-studies | /amazon/most_common.py | 2,449 | 4.21875 | 4 | # Amazon is partnering with the linguistics department at a local university to analyze important works of English literature and identify patterns in word usage across different eras. To ensure a cleaner output, the linguistics department has provided a list of commonly used words (e.g., "an", "the", etc.) to exclude ... | true |
a4b5e62a31da15b84ddef1a9fa93ceae17f41d45 | arthurDz/algorithm-studies | /leetcode/subtree_of_another_tree.py | 1,395 | 4.28125 | 4 | # Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
# Example 1:
# Given tree s:
# 3
# ... | true |
5e8dd2b8d5369f05f43d508e96517d7eea2cfede | arthurDz/algorithm-studies | /leetcode/N-ary_tree_level_order_traversal.py | 872 | 4.1875 | 4 | # Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
# For example, given a 3-ary tree:
# We should return its level order traversal:
# [
# [1],
# [3,2,4],
# [5,6]
# ]
# Note:
# The depth of the tree is at most 1000.
# The ... | true |
6493d4b06546bc81380bb48ed82e1e01b791044c | arthurDz/algorithm-studies | /leetcode/reverse_string.py | 617 | 4.25 | 4 | # Reverse String
# Write a function that reverses a string. The input string is given as an array of characters char[].
# Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
def reverse_string(str1):
i = 0
j = len(str1) - 1
while i... | true |
e337a457a6c871894ffe9afa713297dc1c44fc3f | arthurDz/algorithm-studies | /leetcode/sort_colors.py | 1,486 | 4.1875 | 4 | # Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
# Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
# Note: You are not suppose to use the... | true |
de1508b94a92598f03f91b60797d12fcf0d4edca | arthurDz/algorithm-studies | /leetcode/intersection_of_two_arrays_2.py | 1,022 | 4.15625 | 4 | # Given two arrays, write a function to compute their intersection.
# Example 1:
# Input: nums1 = [1,2,2,1], nums2 = [2,2]
# Output: [2,2]
# Example 2:
# Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
# Output: [4,9]
# Note:
# Each element in the result should appear as many times as it shows in both arrays.
# The res... | true |
1cc2990421174b6a7161da1fbe745a8d3c73ca25 | arthurDz/algorithm-studies | /bloomberg/insertion_sort_list.py | 2,481 | 4.34375 | 4 | # Sort a linked list using insertion sort.
# A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
# With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
# Algorithm of Insertion Sort:... | true |
0e6a395dff87b5199a26b8594f6920d6c3265f99 | arthurDz/algorithm-studies | /linkedin/find_leaves_of_binary_tree.py | 978 | 4.25 | 4 | # Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.
# Example:
# Input: [1,2,3,4,5]
# 1
# / \
# 2 3
# / \
# 4 5
# Output: [[4,5,3],[2],[1]]
# Explanation:
# 1. Removing t... | true |
fd27e4a692f2fa5a901f68b255bcca58bf830d36 | arthurDz/algorithm-studies | /CtCl/Bit Manipulation/binary_to_string.py | 572 | 4.28125 | 4 | # Binary to String: Given a real number between 8 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print "ERROR:'
def printBinary(num):
if num <= 0 or num >= 1: return "ERROR"
init = '0.'
... | true |
80624c401ab0cbc7c815b486db5f341432a97c71 | arthurDz/algorithm-studies | /leetcode/largest_multiple_of_three.py | 2,126 | 4.25 | 4 | # Given an integer array of digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order.
# Since the answer may not fit in an integer data type, return the answer as a string.
# If there is no answer return an empty string.
# Example 1:
# Input: digits =... | true |
462d331a410f7020f847e42ca27e4799f5041c34 | arthurDz/algorithm-studies | /amazon/solve_the_equation.py | 1,698 | 4.15625 | 4 | # Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.
# If there is no solution for the equation, return "No solution".
# If there are infinite solutions for the equation, return "Infinite solutions".
# ... | true |
16aa4d50a4366e29bddf4f01626e3db25fbd352d | adargut/CompetitiveProgramming | /BinaryTrees/Trie/trie.py | 1,327 | 4.125 | 4 | class Trie(object):
def __init__(self):
"""
Represents root node.
"""
self.sons = {}
self.val = None
self.mark = False # means a word ends there
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: No... | true |
f7451bae519ecb3dcb8a39c5b024bed4bee80f3f | clarizamayo/JupyterNotebooks | /Class Material/Week-07/script.py | 1,847 | 4.21875 | 4 | # from random import randint
# class GuessingGame:
# """
# max_guess = 3
# guesses = 0
# """
# def __init__(self):
# self.max_guess = 3
# self.guesses = 0
# self.random_number = randint(1,3)
# @staticmethod
# def welcome_message():
# print("Welc... | true |
90afb3429e48cb3102abd07693897319ba2a644f | singularitea/python-programming-exercises | /question_002.py | 401 | 4.40625 | 4 | # Write a program which can compute the factorial of a given numbers.
# The results should be printed in a comma-separated sequence on a single line.
# Suppose the following input is supplied to the program:
# 8
# Then, the output should be:
# 40320
print('Enter your factorial:')
print('')
f = input()
fa = 1
if f == 0... | true |
09aa834efc0a24c6edffa4bbd2b93305a3ce7e93 | GiulianoSoria/CS50x | /pset6/sentimental/caesar/caesar.py | 1,609 | 4.34375 | 4 | from cs50 import get_string
import sys
# Converts into an integer the value entered as a key in the command-line
k = int(sys.argv[1])
# Checks if the key is greater than zero
if k > 0:
# Prompts the user to enter the text that wants ciphered
s = get_string("plaintext: ")
print("ciphertext: ", end="")
... | true |
c6e27c4d4212035ac6a3161db72021e4443515ab | TheNoobProgrammer22/Birthday-Recorder | /main.py | 718 | 4.34375 | 4 | dict = {}
while True:
print("------------Birthday App----------")
print("1.Show Birthday")
print("2.Add to Birthday List")
print("3.Exit")
choice = int(input("Enter the choice"))
if choice == 1:
if len(dict.keys())==0:
print("Nothing to show")
else:
... | true |
62b242b7c7a76663b380b7c8e29930db58c12149 | Muhammed-Moinuddin/Python1 | /beginner.py | 2,679 | 4.25 | 4 | a = int(input("Please enter first number: "))
b = int(input("Please enter Second number: "))
if a > b : print('{0} is the largest'.format(a))
else : print('{0} is the largest'.format(b))
#First input Positive or negative
if a > 0 : print('{0} is Positive'.format(a))
else : print('{0} is Negative'.format(a))
#First... | true |
47c1ef429d4b92e975304a5140678a7a7bea0bac | k18a/algorithms | /classical_algorithms/sort_insertion.py | 1,718 | 4.5 | 4 | """
insertion sort
"""
def insertion_sort(array, verbose=False):
# define verboseprint function
verboseprint = print if verbose else lambda *a, **k: None
verboseprint('array to be sorted is {}'.format(array))
# iterate over unsorted array, first element is always sorted
for unsorted_index, unsorted_... | true |
7d3c4d3a9c5384f83bdb3468d686ec4731de7758 | k18a/algorithms | /classical_algorithms/sort_radix.py | 2,224 | 4.21875 | 4 | """"
radix sort
"""
from sort_counting import counting_sort
def radix_sort(array, verbose = False):
# get array maximum
maximum = max(array)
# initialize exponent
exponent = 1
# check if exponent is greater than max
while exponent < maximum:
# count sort array for the given exponent
... | true |
917637e7e8823fbcf0d920386dd405dbed14843a | delta94/Code_signal- | /Arcade/Intro/Smooth Sailing/commonCharacterCount.py | 498 | 4.3125 | 4 | """"
Given two strings, find the number of common characters between them.
Example
For s1 = "aabcc" and s2 = "adcaa", the output should be
commonCharacterCount(s1, s2) = 3.
Strings have 3 common characters - 2 "a"s and 1 "c".
""""
def commonCharacterCount(s1, s2):
count = 0
for ch1 in s1 :
line = s2... | true |
26b8671c5e2844257179cf441f1152ac658d3d33 | delta94/Code_signal- | /Arcade/Intro/Dark Wilderness/digitDegree.py | 676 | 4.25 | 4 | """
Let's define digit degree of some positive integer as the number of times we need to replace this number with the sum of its digits until we get to a one digit number.
Given an integer, find its digit degree.
Example
For n = 5, the output should be
digitDegree(n) = 0;
For n = 100, the output should be
digitDegre... | true |
09c38e6dd37874bf0abaaec9b37c8cf37cc9c56c | delta94/Code_signal- | /Arcade/Intro/Dark Wilderness/bishopAndPawn.py | 659 | 4.21875 | 4 | """
Given the positions of a white bishop and a black pawn on the standard chess board, determine whether the bishop can capture the pawn in one move.
The bishop has no restrictions in distance for each move, but is limited to diagonal movement. Check out the example below to see how it can move:
https://codesignal.s3... | true |
81b52cb363dea20d99e8fcf563ef763b8510df13 | delta94/Code_signal- | /Arcade/Intro/Erruption of light/mac48Address.py | 1,239 | 4.71875 | 5 | """
A media access control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment.
The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits (0 to 9 or A to F), separated by hyphens... | true |
31d79443971ae591803b9bdefe61e8dc8c6fc129 | delta94/Code_signal- | /Arcade/The core/Intro Gates/3. LargestNumber.py | 325 | 4.15625 | 4 | """
Given an integer n, return the largest number that contains exactly n digits.
Example
For n = 2, the output should be
largestNumber(n) = 99.
"""
def largestNumber(n):
p = 0
for i in range(n):
if i != n-1:
p += 9*(10**(n-i-1))
if i == n-1:
p +=9
return p
... | true |
1789d3e8b1376870bfe428e08381b26ce1b8fb21 | nervig/Starting_Out_With_Python | /Chapter_2_programming_tasks/task_7.py | 323 | 4.21875 | 4 | #!/usr/bin/python
covered_destination = float(input("Enter the covered destination: "))
fuel_consumption_in_liters = float(input("Enter the fuel consumption in liters: "))
fuel_consumption =float(fuel_consumption_in_liters / covered_destination)
print("The fuel consumption of your car equals {}".format(fuel_consumption... | true |
75d9f72c5c9b9a6108ba02b6fc63e6ef047058aa | nervig/Starting_Out_With_Python | /Chapter_6_programming_tasks/record_students_list.py | 759 | 4.25 | 4 | # creating a file and adding some records
def main():
# create a variable for manage of cycle
the_flag = 'y'
# open the students.txt file in adding mode
adding_students = open("students.txt", "a")
while the_flag == 'y' or the_flag == 'Y':
print("Enter an information are students about: ")
... | true |
4e3c43805358f8cd12750a3ceb93535032198f90 | DarishkaAMS/Py_Bootcamp_Task-COAX_Tryout | /question1_reversed_string.py | 494 | 4.21875 | 4 | #direct reversing
s = "string"
print(s[::-1])
#using length and slicing
s = "string"
reversed_s = s[len(s)::-1]
print (reversed_s)
#using function call
s = "string"
def reversing_function(x):
return x[::-1]
print(reversing_function(s))
#using join and reversed
s = "string"
s_reversed=''.join(reversed(s))
pri... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.