blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
68caebc77b00e0e9bb67cee90754127961f4a52b | RohanMiraje/DSAwithPython | /DSA/string/find_permutation_pattern_in_given_string.py | 2,231 | 4.3125 | 4 | """
find if permutation of given pattern exist in given string text
-->use sliding window technique + any algo to check window string and pattern anagram(use xor approach)
"""
def find_pattern(string, pat):
"""
this is naive approach
it takes O((n-m+)*m)
:param string:
:param pat:
:return:
... | true |
8a02fb81626d3dc35b9905c837a9d1d0f41b1652 | RohanMiraje/DSAwithPython | /DSA/arrays/find_missing_no.py | 1,736 | 4.40625 | 4 | """
Given two array
e.g. arr_1 = [1, 2, 3, 4, 5, 6, 7]
arr_2 = [3, 7, 2, 1, 4, 6]
Find a missing element second array
Method 1:
Using sum of elements of two arrays
missing_element = sum_of_elements_of_first_array - sum_of_elements_of_second_array
TC: O(n)
Method 2:
Using XOR op... | true |
3329a0079cc277ed5ba8c8924422e273fece5e37 | RohanMiraje/DSAwithPython | /DSA/pythonhackerrank/2d_pattern_traversal.py | 1,987 | 4.34375 | 4 | """
Objective
Today, we are building on our knowledge of arrays by adding another dimension. Check out the Tutorial tab for learning materials and an instructional video.
Context
Given a 2D Array, :
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
We define an hourglass in to be a subset of v... | true |
1af3a729f861abcff1571e8e072d4a47192d4950 | Baidaly/datacamp-samples | /8 - statistical thinking in python - part 1/quantitative exploratory data analysis/computing the covariance.py | 869 | 4.21875 | 4 | '''
The covariance may be computed using the Numpy function np.cov(). For example, we have two sets of data x and y, np.cov(x, y) returns a 2D array where entries [0,1] and [1,0] are the covariances. Entry [0,0] is the variance of the data in x, and entry [1,1] is the variance of the data in y. This 2D output array is ... | true |
8639c4b242ad4ca6d530956a7209d1fdc260692e | Baidaly/datacamp-samples | /5 - merging dataframes with pandas/reindexing DataFrame from a list.py | 1,256 | 4.1875 | 4 | '''
Sorting methods are not the only way to change DataFrame Indexes. There is also the .reindex() method.
In this exercise, you'll reindex a DataFrame of quarterly-sampled mean temperature values to contain monthly samples (this is an example of upsampling or increasing the rate of samples, which you may recall from ... | true |
a1b25fdb0d749055443b04c29d4cc229f35b7684 | Baidaly/datacamp-samples | /16 - building recommendation engines in python/chapter 1/6 - Making your first movie recommendations.py | 1,034 | 4.5625 | 5 | '''
Now that you have found the most commonly paired movies, you can make your first recommendations!
While you are not taking in any information about the person watching, and do not even know any details about the movie, valuable recommendations can still be made by examining what groups of movies are watched by the... | true |
82056af0d3e8c1088a430db57fa499199ab620e6 | Baidaly/datacamp-samples | /8 - statistical thinking in python - part 1/quantitative exploratory data analysis/computing the Pearson correlation coefficient.py | 1,130 | 4.46875 | 4 | '''
As mentioned in the video, the Pearson correlation coefficient, also called the Pearson r, is often easier to interpret than the covariance. It is computed using the np.corrcoef() function. Like np.cov(), it takes two arrays as arguments and returns a 2D array. Entries [0,0] and [1,1] are necessarily equal to 1 (ca... | true |
70698a3667ae95b48d495f3e41fce0161608e3e4 | Baidaly/datacamp-samples | /6 - introduction to databases in python/calculating a Difference between Two Columns.py | 1,204 | 4.15625 | 4 | '''
Often, you'll need to perform math operations as part of a query, such as if you wanted to calculate the change in population from 2000 to 2008. For math operations on numbers, the operators in SQLAlchemy work the same way as they do in Python.
You can use these operators to perform addition (+), subtraction (-), ... | true |
50c2176c301e9e92b5f464c753eecf03bebcff30 | Baidaly/datacamp-samples | /5 - merging dataframes with pandas/reindexing using another DataFrame Index.py | 1,696 | 4.4375 | 4 | '''
Another common technique is to reindex a DataFrame using the Index of another DataFrame. The DataFrame .reindex() method can accept the Index of a DataFrame or Series as input. You can access the Index of a DataFrame with its .index attribute.
The Baby Names Dataset from data.gov summarizes counts of names (with g... | true |
8ed1dda8908d4c11aba7bb38b1465e86546d28b9 | Baidaly/datacamp-samples | /3 - pandas foundation/austin case study/8.py | 1,070 | 4.21875 | 4 | '''
Sunny or cloudy
On average, how much hotter is it when the sun is shining? In this exercise, you will compare temperatures on sunny days against temperatures on overcast days.
Your job is to use Boolean selection to filter out sunny and overcast days, and then compute the difference of the mean daily maximum temp... | true |
377045ef9c1b7b105fb1f45bd7a6eea02d2adf7e | Baidaly/datacamp-samples | /9 - statistical thinking in python - part 2/case study/7 - Displaying the linear regression results.py | 1,208 | 4.28125 | 4 | '''
Now, you will display your linear regression results on the scatter plot, the code for which is already pre-written for you from your previous exercise. To do this, take the first 100 bootstrap samples (stored in bs_slope_reps_1975, bs_intercept_reps_1975, bs_slope_reps_2012, and bs_intercept_reps_2012) and plot th... | true |
cbe1c065f7b93dff30bf9f5ecff730b0b53d9582 | Baidaly/datacamp-samples | /5 - merging dataframes with pandas/broadcasting in arithmetic formulas.py | 1,118 | 4.3125 | 4 | '''
In this exercise, you'll work with weather data pulled from wunderground.com. The DataFrame weather has been pre-loaded along with pandas as pd. It has 365 rows (observed each day of the year 2013 in Pittsburgh, PA) and 22 columns reflecting different weather measurements each day.
You'll subset a collection of co... | true |
8fae0fa1a1965830f5ea449962361513e58cd8ac | Baidaly/datacamp-samples | /4 - manipulating dataframes with pandas/Extracting and transforming data/using apply to transform a column.py | 907 | 4.65625 | 5 | '''
The .apply() method can be used on a pandas DataFrame to apply an arbitrary Python function to every element. In this exercise you'll take daily weather data in Pittsburgh in 2013 obtained from Weather Underground.
A function to convert degrees Fahrenheit to degrees Celsius has been written for you. Your job is to... | true |
c66a3aae3ebb29310a7aa3d92f9a712fde5a1c2f | Baidaly/datacamp-samples | /8 - statistical thinking in python - part 1/thinking probabilistically/will the bank fail.py | 782 | 4.53125 | 5 | '''
Plot the number of defaults you got from the previous exercise, in your namespace as n_defaults, as a CDF. The ecdf() function you wrote in the first chapter is available.
If interest rates are such that the bank will lose money if 10 or more of its loans are defaulted upon, what is the probability that the bank w... | true |
4d8391a0ff32748e16dbb0888595c912930200b9 | Baidaly/datacamp-samples | /13 - Supervised Learning with scikit-learn/chapter 1/5 - Train-Test Split + Fit-Predict Accuracy.py | 930 | 4.28125 | 4 | '''
Now that you have learned about the importance of splitting your data into training and test sets, it's time to practice doing this on the digits dataset! After creating arrays for the features and target variable, you will split them into training and test sets, fit a k-NN classifier to the training data, and then... | true |
e00dc38228b9dfa2206e9dddaaa3eeda9e6fba61 | Baidaly/datacamp-samples | /15 - joining data with pandas/chapter 2/4 - Using outer join to select actors.py | 1,134 | 4.6875 | 5 | '''
One cool aspect of using an outer join is that, because it returns all rows from both merged tables and null where they do not match, you can use it to find rows that do not have a match in the other table. To try for yourself, you have been given two tables with a list of actors from two popular movies: Iron Man 1... | true |
54b5f02e53d3efd052db0afc45090a8fe64afeaf | Baidaly/datacamp-samples | /4 - manipulating dataframes with pandas/Advanced indexing/indexing multiple levels of a MultiIndex.py | 1,251 | 4.40625 | 4 | '''
Looking up indexed data is fast and efficient. And you have already seen that lookups based on the outermost level of a MultiIndex work just like lookups on DataFrames that have a single-level Index.
Looking up data based on inner levels of a MultiIndex can be a bit trickier. In this exercise, you will use your sa... | true |
1a38c16fa5871fa4e14d901d5cae75f840d35a42 | rbanders/ThinkPython2 | /Exercise 5.14.5.py | 712 | 4.34375 | 4 | """Exercise 5
Read the following function and see if you can figure out
what it does (see the examples in Chapter 4).
# infinite recursion?
Then run it and see if you got it right.
def draw(t, length, n):
if n == 0:
return
angle = 50
t.fd(length*n)
t.lt(angle)
draw(t, length, n-1)
t.r... | true |
44201a93658037168faeeec995f51ef1f99190d1 | tony-andreev94/codewars_repo | /22. Rot13 5 kyu.py | 697 | 4.5625 | 5 | # Rot13
# https://www.codewars.com/kata/530e15517bc88ac656000716
# ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it.
# If there are numbers or special characters included in the string, they should be returned as they are.
def rot13(message):
encrypted = ""
... | true |
5211e6de8bed6e07e67cee03fce7443a464f8059 | tarungoyal1/practice-100 | /8 - sort words.py | 519 | 4.25 | 4 | # Question 8
# Level 2
#
# Question:
# Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically.
# Suppose the following input is supplied to the program:
# without,hello,bag,world
# Then, the output should be:
# bag,h... | true |
8707c1e9c1b96dc9ddf8742bb947b2c224632821 | kush-x7/Python-notes | /for_loops/for_loop.py | 660 | 4.125 | 4 | ruits = ["Apple", "Peach", "Pear"]
for fruit in fruits: ->fruit is a new variable which will store particular list item one by one
print(fruit)
print(fruit + " Pie")
print(fruits)
for number in range(1, 11): ->range 1-10
print(number, end=' ')
print('\n')
# Don't change the code ... | true |
6cde8b9df6e948c1b6830e07d1ca0846077d76e0 | kush-x7/Python-notes | /creating_function/creating_function.py | 640 | 4.28125 | 4 |
def my_function(): ->definning my function
print("Hello")
print("Bye")
sum=2+3
return sum
my_function() ->calling my function
--------------------------------------------------
def greet_with(name, location): ->definning a function which takes input while calling
print(f'... | true |
7a0a7e4d604364966952cf5c3b9b50d751e5b31d | zkhorozianbc/LRU-Cache | /linked_list.py | 2,896 | 4.125 | 4 | from typing import Optional
from node import Node
class LL:
"""
Full implementation of doubly linked list
"""
def __init__(self):
self.head = None #type: Optional[Node]
self.tail = self.head #type: Optional[Node]
self.ref_map = {} #type: Dict[str,Node]
def size(self):
... | true |
bd518c71964b3fa7e781c99a875f45d185d3e247 | akshaypawar2508/Coderbyte-pythonSol | /19-second-greatlow.py | 693 | 4.15625 | 4 | # Have the function SecondGreatLow(arr) take the array of numbers stored in arr and return the second lowest and second greatest numbers, respectively, separated by a space. For example: if arr contains [7, 7, 12, 98, 106] the output should be 12 98. The array will not be empty and will contain at least 2 numbers. It c... | true |
d11a452772714eed086ceb911cd0fab19c945c84 | akshaypawar2508/Coderbyte-pythonSol | /50-three-five-multiple.py | 244 | 4.21875 | 4 | def ThreeFiveMultiples(num):
return sum(i for i in range(num) if i % 3 == 0 or i % 5 == 0)
# keep this function call here
# to see how to enter arguments in Python scroll down
print ThreeFiveMultiples(raw_input())
| true |
99364aa2876cf534ed45a313d6da945047a6c77c | dondreojordan/cs-guided-project-python-basics | /src/demonstration_2.py | 1,800 | 4.5 | 4 | """
You have been asked to implement a line numbering feature in a text editor that
you are working on.
Write a function that takes a list of strings and returns a new list that
contains each line prepended by the correct number.
The numbering starts at 1 and the format should be `line_number: string`. Make
sure to p... | true |
9db9306349d2159e68a24c5551b5bd4a13744d38 | CodetoInvent/interviews | /word_search.py | 1,649 | 4.125 | 4 | # Word Search
# Given a 2D board and a word, find if the word exists in the grid.
# The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
# Example:
board = [
["A","B","C"... | true |
ad246fd89117552e84c3a63900b0767fd9a17532 | SarmenSinanian/Sorting | /src/insertion_sort.py | 826 | 4.15625 | 4 | def insertion_sort(items):
# Split the list into sorted and unsorted
# For each element in unsorted...
counter = 0
for i in range(1, len(items)):
# Insert that element into the correct place in sorted
# Store the elements in a temp variable
temp = items[i]
# Shifting all ... | true |
bdae5a540d52899874f83a56c7ebb42e1199a3d4 | Ebi-aftahi/Python_Solutions | /Print multiplication table/multi_table.py | 514 | 4.1875 | 4 | user_input= input()
lines = user_input.split(',')
# This line uses a construct called a list comprehension, introduced elsewhere,
# to convert the input string into a two-dimensional list.
# Ex: 1 2, 2 4 is converted to [ [1, 2], [2, 4] ]
mult_table = [[int(num) for num in line.split()] for line in lines]
for item i... | true |
0a11b0f40cd3576d71a598dd2a695851ddf4ed16 | kawasaki2013/Python-4 | /Python Basic Syntax/Quotation in Python.py | 368 | 4.125 | 4 |
#****************** Quotation in Python **********************
# Python accepts single ('), double (") and triple (''' or """)
# For example
print(' Quotation ')
print(" Quotation ")
# The triple quotes are used to span the string across multiple lines
print("""
Quotation
Python
"... | true |
8e122e1a7bf635f0333301f95ac9b9b14ecb691b | karthikaManiJothi/PythonTraining | /Assignment/19-06-2021Assignment/BMIvalidation.py | 911 | 4.1875 | 4 | from BMIcal import BMI
class validation:
@staticmethod
def validate(weight,height):
# by using bmical module
bmi_value = BMI.bmi_calculate(weight, height)
if bmi_value < 18.5:
print("your BMI is",bmi_value,"which means you are underweight person")
elif bmi_value >=... | true |
cb4943dee987a69256fab4c643b299e097b3e2c2 | sinderpl/CodingExamples | /python/Data Structures/Linked Lists/reorderList.py | 923 | 4.25 | 4 | def reorderList(self, head: Optional[ListNode]) -> None:
"""
Do not return anything, modify head in-place instead.
"""
slow = fast = head
# Find the middle of a linked list
# o(n)
while fast.next and fast.next.next:
slow = slow.n... | true |
6e4fd37c170a4fbc4e65d2c0f742e5b7c05b2f12 | clairefan816/PythonExcercises | /hw04/password.py | 2,255 | 4.3125 | 4 | # Author: Yu Fan (fan.yu@husky.neu.edu)
# For homework 4
# Generate username and passwords
import random
import math
# collect informations from the user, and the origianal case is kept.
print('Welcome to the username and password generator!')
first_name = input('Please enter your first name: ')
last_name = input('Pl... | true |
d9aebcf78c5cc0b94cc98e25cf1c8fb7b86c6bf3 | rkillough/riskPlanningBDI | /BDIPlanning/decisionRule/Rinduction.py | 1,374 | 4.4375 | 4 | #resources - set of amounts of remaining resources
#weights - corresponding value of the resources
#requirments - corresponding amounts of resources needed to complete the goal from this point
'''
The procedure is to calculate a "scarcity measure" from the amoutn we have vs the amount we need, this is then modulated ... | true |
626416c09b0a0584ddb49530bbcbf283fa7ea218 | tayvionne/CTI110 | /M5T1_KilometerConverter_TayVionneCarey.py | 719 | 4.375 | 4 | #Kilometer Converter
#June 29, 2017
#CTI-110 M5T1_KilometerConverter
#TayVionne Carey
#
#The main fucntion gets a distance in kilometers and calls
#the show_miles function to convert it.
conversion_factor = 0.6214
def main ():
#Get the distance in kilometers.
kilometers = float(input('Enter a dis... | true |
9094a8eea38ee2571bb015924a3762c4f9907a82 | scouvreur/hackerrank | /python/python_functionals/map_and_lambda_function.py | 379 | 4.15625 | 4 | def fibonacci(n):
"""
Returns a list of fibonacci numbers of length n
Parameters
----------
n : int
Number in fibonacci suite desired
Returns
-------
fib_list : list[ints]
List of integers
"""
memo = [0, 1]
for i in range(2, n):
memo += [memo[i - 2]... | true |
99786df582fab3a67d802c32b6d636503bc5f77a | bunmiaj/CodeAcademy | /Python/Tutorials/File-IO/4.py | 589 | 4.46875 | 4 | # Reading
# Excellent! You're a pro.
# Finally, we want to know how to read from our output.txt file. As you might expect, we do this with the read() function, like so:
# print my_file.read()
# Instructions
# Declare a variable, my_file, and set it equal to the file object returned by calling open() with both "output... | true |
43a7a0f57ecb78f05eb45bad6ddd514b132b39fb | bunmiaj/CodeAcademy | /Python/Tutorials/Loops/enumerate.py | 796 | 4.625 | 5 | # Counting as you go
# A weakness of using this for-each style of iteration is that you don't know the index of the thing you're looking at.
# Generally this isn't an issue, but at times it is useful to know how far into the list you are.
# Thankfully the built-in enumerate function helps with this.
# enumerate work... | true |
9ffad92645406b273a85cd54d5d286af4969ee7a | DrakeData/automate-the-boring-stuff | /Chapter3/collatzSequence.py | 424 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 15 21:14:51 2018
@author: Nicholas
"""
#collatz
#creating the function
def collatz(number):
#even number
if number % 2 == 0:
print(number // 2)
return number // 2
#odd number
elif number % 2 == 1:
result = 3 * number + 1
... | true |
ffe946410024fdc959b86df27b446e68bb3e639c | KobiBeef/pythonlearn | /pay.py | 626 | 4.15625 | 4 |
def compute_pay():
while True:
hours = input("Enter hours: ")
rate = input("Enter rate: ")
try:
if len(hours) == 0 or len(rate) == 0:
print ('enter a value')
else:
num_hours = float(hours)
num_rate = float(rate)
if num_hours > 40:
overtime_hours = num_hours - 40
overtime_pay = ov... | true |
cf76909b9eb508006b9f36296bf720af4de75f81 | nikrasiya/PreCourse_2 | /Exercise_3.py | 1,861 | 4.3125 | 4 | # Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self) -> None:
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next ... | true |
c41d730eb29ba8d255f72243ab483082c572afcd | rmartind/ctci | /ctci/chapter1/unique.py | 533 | 4.21875 | 4 | """Solution to 1.1 Is Unique."""
def is_unique(string):
"""Determines if a string is unique.
Args:
string: any string of characters.
Returns:
a Boolean value dependant on the uniqueness
Raises:
ValueError: Empty string value given as an argument
"""
temp = list()... | true |
3844564d342532a4a14e4a55c697ff3203488e97 | olehyarmoliuk/Yarmoliuk-Oleh.-Pythone-Core.-Homework | /homework_3/task2.py | 599 | 4.21875 | 4 | from math import pi
q = input('Choose a rectangle, a triangle, or a circle: ')
if q == 'rectangle':
length_1 = float(input('What is the length? '))
width_1 = float(input('What is the width? '))
print("Square of the rectangle is", length_1 * width_1)
elif q == 'triangle':
h = float(input('What is... | true |
c81ffc24ca56ae252a5d3b0dc93e02f216068e57 | Margarita89/AlgorithmsAndDataStructures | /Cracking the Coding Interview/3_StackQueues/3_6.py | 2,640 | 4.125 | 4 | # Animal Shelter: An animal shelter, which holds only dogs and cats, operates on a strictly "first in, first out" basis.
# People must adopt either the "oldest" (based on arrival time) of all animals at the shelter,
# or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of tha... | true |
8e7daff7193b0cf13c6d067d24393665653b7088 | Margarita89/AlgorithmsAndDataStructures | /Cracking the Coding Interview/8_Recursion and Dynamic Programming/8_10.py | 1,757 | 4.1875 | 4 | # Paint Fill: Implement the "paint fill" function that one might see on many image editing programs.
# That is, given a screen (represented by a two-dimensional array of colors), a point, and a new color,
# fill in the surrounding area until the color changes from the original color.
def paint_fill(screen, init_color... | true |
1e3ef3f1875f571f32d260d3ada230640144b13b | Margarita89/AlgorithmsAndDataStructures | /Cracking the Coding Interview/1_Arrays/1_6.py | 950 | 4.46875 | 4 | # String Compression: Implement a method to perform basic string compression using the counts of repeated characters.
# For example, the string aabcccccaaa would become a2blc5a3.
# If the "compressed" string would not become smaller than the original string, your method should return
# the original string. You can assu... | true |
7bff6f91d506d341f0631dfa0e9b628b88fc2868 | Margarita89/AlgorithmsAndDataStructures | /Cracking the Coding Interview/5_Bit_Manipulation/5_2.py | 818 | 4.25 | 4 | # Binary to String: Given a real number between 0 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 binaryToString(num):
if num > 1 or num < 0:
return "ERROR"
an... | true |
36c0fea933b27d423ca99566d2008aaf5ed270e1 | Margarita89/AlgorithmsAndDataStructures | /Cracking the Coding Interview/1_Arrays/1_9.py | 445 | 4.40625 | 4 | # String Rotation: Assume you have a method isSubstring which checks if one word is a substring of another.
# Given two strings, sl and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring
# (e.g.,"waterbottle" is a rotation of"erbottlewat").
def StringRotation(a, b):
s = a + a
... | true |
379974e7dbd465ff7ca3b4cd015184c0a153d86c | SP18-Introduction-Computer-Science/map-and-lists-Katherinemwortmano | /Homework 2.py | 514 | 4.34375 | 4 | #Maps and Lists Homework
#List Questions
MyList=["Assignment", "Number Two", "Intro to computer science", "Katherine", "WortmanOtto"]
for Words in MyList :
print(Words)
#Map Questions
myMap = {0:"Assignment", 1: "Number Two", 2: "Intro to computer science", 3: "Katherine" , 4: "WortmanOtto"}
... | true |
74562f7ffda3842ff0263097f7a2db34f13a556e | hehlinge42/machine_learning_bootcamp | /day00/ex03/std.py | 1,407 | 4.25 | 4 | import numpy as np
from math import sqrt as sqrt
def mean(x):
"""Computes the mean of a non-empty numpy.ndarray, using a for-loop.
Args:
x: has to be an numpy.ndarray, a vector.
Returns:
The mean as a float.
None if x is an empty numpy.ndarray.
Raises:
This function should not raise any Exception.
"""
if x.... | true |
c17bd0bd263a32b11c893fa1910a43bf94d4bf61 | vkvikaskmr/ud036_StarterCode | /media.py | 921 | 4.21875 | 4 |
class Movie():
"""This class is used to store and display Movie related informations"""
VALID_RATINGS = {
"General": "G",
"Parental_Guidance": "PG",
"Parents_Strongly_Cautioned": "PG-13",
"Restricted": "R"
}
def __init__(
self,
movie_title,
... | true |
9db2e4818a541fac4646889b2cfe36af3dea7119 | yw652/Euler-Problem | /EulerProblem/isFibo.py | 686 | 4.125 | 4 | '''
You are given an integer, N. Write a program to determine if N is an element of the Fibonacci Sequence.
'''
import sys
def isFibo():
list = []
num = int(raw_input())
for i in range(0,num):
i = int(raw_input())
list.append(i)
for next in list:
if next in fibonacci():
... | true |
43d9339652882c3227d449ba2ef4a7e89a4de29a | br80/lambda_cs | /timing.py | 2,225 | 4.1875 | 4 | # Find the number of seconds it takes to run any operation
# Output it in a format that can be graphed in google sheets
from time import time
import random
# STRETCH: implement the Bubble Sort function below
def bubble_sort( arr ):
# Repeat this until you make it through an entire pass without any swaps.
is... | true |
37542db4542de3492ad901821f73a6e2b0e8a28f | yosef-kefale/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 1,848 | 4.53125 | 5 | #!/usr/bin/python3
class Square:
"""initializes square, determines size, calculates area, prints"""
def __init__(self, size=0, position=(0, 0)):
"""initializes instance of square
Args:
size: size of square
position: position to indent square
"""
self.siz... | true |
c16abb148afecc330405f48f4d3927cf4d080983 | Carter-Co/she_codes_python | /databases/books.py | 846 | 4.125 | 4 |
#Relational Database - tables and rows
#SQL language to interat with databases
#Every row gets its own ID
import sqlite3
connection = sqlite3.connect("books.db")
cursor = connection.cursor()
#below would be fields / headers
cursor.execute("""
CREATE TABLE IF NOT EXISTS book (
id INTEGER PRIMARY KEY,
... | true |
c5177b0fd0e8fc2a46297fa359b9b91fe355f83f | Carter-Co/she_codes_python | /conditionals/conditionals_playground.py | 1,111 | 4.1875 | 4 | #boolean
is_raining = False
is_cold = True
# print(type(is_raining))
# print(type(is_cold))
# print(is_raining)
# print(not is_raining)
# print(is_raining and is_cold)
# print(is_raining)
# print(not is_raining)
# print(is_raining and is_cold)
# print(is_raining and not is_cold)
# print(is_raining or not is_cold)
# ... | true |
386707d21dffe754c288d9572b54d038fb0ee597 | WuQianyong/Spider_demo | /algorithm_demo/mountanin_h.py | 638 | 4.25 | 4 | #!/usr/bin/env Python3
# -*- coding: utf-8 -*-
# @Name : mountanin_h
# @Author : qianyong
# @Time : 2017-02-06 9:25
import sys
import math
# The while loop represents the game.
# Each iteration represents a turn of the game
# where you are given inputs (the heights of the mountains)
# and where you have to pr... | true |
461edcd59169810bec0e42a163fd9fc6984ee4a5 | jbailey430/The_Tech_Academy_Basic_Python_Projects | /test_database.py | 1,152 | 4.125 | 4 |
import sqlite3
connection = sqlite3.connect("test_database.db")
c = connection.cursor()
c.execute("INSERT INTO People VALUES('Ron', 'Obvious', 42)")
connection.commit()
connection.close()
with sqlite3.connect("test_database.db") as connection:
c = connection.cursor()
c.executescript("""DROP TABLE IF EXISTS... | true |
56658a479cc3eac8d4848915243b03eec72cda72 | cmdellinger/ProjectEuler | /Problem 23 - Non-abundant sums/problem 23-python3.py | 2,035 | 4.1875 | 4 | # -*- coding: UTF-8 -*-
"""
ProjectEuler Problem 23: Non-abundant sums
Written by cmdellinger
A perfect number is a number for which the sum of its proper divisors is exactly
equal to the number. For example, the sum of the proper divisors of 28 would be
1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect numbe... | true |
68a9a16db25f83f2085a54bf7a3190b50849d362 | mishrabhi/Python-Learning | /calc.py | 277 | 4.4375 | 4 | #We can use python as a calculator using print function:
#you can use these some of the operators:
# addition=> +
#substraction => -
#multiply => *
#float division => /
#Integer division => //
#Module(it gives remainder) => %
#exponent => **
print(2+3)
print(2+3*5)
print(2**3) | true |
740791e24aeb483c8de25832c5737dbc88ef777f | mishrabhi/Python-Learning | /string_method.py | 1,396 | 4.625 | 5 | #String Methods:
name = "AbhISHeK MIsHra"
# 1.len() function => It counts the character in string.It includes spaces too.
print(len("Abhishek")) #//8
print(len(name)) #//15 (with space)
print(len("AbhishekMishra")) #//14 (Without space)
# 2.lower() method => It converts all characters into lower cases.
print(nam... | true |
3d74070dedd234df53c0af78c0ac4eee585ffa64 | siddhantmahajani/Basic-python-concepts | /10. Data-Structures-Set.py | 347 | 4.1875 | 4 | # Set
# Set contains unique non-duplicate elements
_set = {1, 2, 2, 3, 4, 5, 6, 7, 8, 9}
print(_set)
# _set.add(10) : used to add an element in the set
# _set.remove(2) : used to remove an element in the set
# _set.pop() : will remove the first element from the set
# print(_set.pop()) : will print the first element tha... | true |
d0d12e833764e83ea94ae640578d5635afe75d31 | dcurry09/machine_learning_intro | /linear_regression/lin_regession.py | 1,239 | 4.28125 | 4 | # David Curry
# Gradient Descent using SciKit - Machine Learning
import pylab as pl
import numpy as np
from sklearn import datasets, linear_model
print '---> Importing the Dataset'
data = np.loadtxt('mlclass-ex1-005/mlclass-ex1/ex1data1.txt', delimiter=',')
x = data[:, 0]
y = data[:, 1]
# Create linear regression o... | true |
4a95f4e68ed70d175839aff6818246479e676b7f | FokhrulAlam/Programming-with-Python | /Tutorial/Exercises/Miscellaneous/array_2.py | 334 | 4.125 | 4 | from array import *
arr=array('i',[])
n=int(input("Enter the length of the array:"))
for i in range(n):
x=int(input("Enter the value:"))
arr.append(x)
print(arr)
value=int(input("Enter a value to know its index: "))
for i in arr:
if value==arr[i]:
index=[i]
print("Index of value is ",index)... | true |
f21ce2fb5a2b071358a911d9e7183597e260f50d | FokhrulAlam/Programming-with-Python | /Starting Out with Python By Tony Gaddis/6.8. Random Number File Reader.py | 1,381 | 4.46875 | 4 | #This exercise assumes you have completed Programming Exercise 7, Random Number File Writer. Write another program
# that reads the random numbers from the file, display the numbers, and then display the following data:•
# The total of the numbers•
# The number of random numbers read from the file
def... | true |
b7071f0ee77ada99eaeaad306da96d0f2e8dd8c6 | degutos/unuteis | /method.py | 283 | 4.28125 | 4 | # Methods
# Creating a list
mylist = [1,2,3]
print(mylist)
# appending new value to a list
mylist.append(4)
print(mylist)
mylist.append(5)
print(mylist)
# pop the last item in the list (delete)
mylist.pop()
print(mylist)
help(mylist.insert)
mylist.insert(1,5)
print(mylist)
| true |
c771b076b6f2d2e1af82170b9b110b81dc63819b | degutos/unuteis | /rock-paper-scisor.py | 1,703 | 4.5 | 4 | # This code is to learn Python by Andre Gonzaga
# This code is the simulator for Rock, Paper, Scissor
import random
def print_options():
print('Lets play this... ')
print('')
print(' Rock ')
print(' Paper ')
print(' Scissor ')
print('')
def ask_option():
user_option=input('Your option now ... | true |
634455d793227c382c8d6f92e223713e7de276f8 | kaushiks90/PythonPrograms | /PythonPrograms/BasicPrograms/Anagrams.py | 644 | 4.1875 | 4 | #Given 2 strings find whether the string is Anagram
#Example NAB and BAN
def ReverseString(originalString,n):
reversedString=""
for x in range(n,0,-1):
reversedString=reversedString+originalString[x-1]
return reversedString
def FindIsAnagram(string1,string2):
isAnagram=False
if(len(strin... | true |
08bd3014908d206cc2240699524006616ec99b3c | benhassenwael/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 750 | 4.28125 | 4 | #!/usr/bin/python3
""" Module implementing a single function append_after """
def append_after(filename="", search_string="", new_string=""):
""" Inserts a line of text to a file,
after each line containing a specific string
Args:
filename: a string representing the file name
search_s... | true |
02ea6e9060b713878723f8903bb65d13b445d0b4 | kitiarasr/LC-101 | /Chapter_1-5/Chapter2Hw.py | 549 | 4.40625 | 4 |
# !/usr/bin/env python
#Write a program that calculates the temperature based on how much the dial
#has been turned. You should prompt the user for a number of clicks-to-the-right
#(from the starting point of 40 degrees). Then you should print the current
#temperature.
# By how many clicks has the dial been turned?
... | true |
2d4a0ffc57e3bb6698e90efea0baa8b6c0383107 | pirate765/bridgelabzbootcamp | /day3/cos.py | 233 | 4.15625 | 4 | import math
x = float(input("Enter the angle in radians"))
x = x % (2 * math.pi)
a = -1
cosx = 1
for i in range(1,15):
cosx += ((a)*(pow(x,2*i))/math.factorial(2*i))
a *= -1
print("The value of cos is {}".format(round(cosx, 3))) | true |
f3186cd2b5b45f1095a93ac0d67a03c8c64f0257 | dblitz21/coding | /cubes.py | 245 | 4.15625 | 4 |
#Get the cube of the first 10 numbers
cubes = []
for value in range(1, 11):
cubes.append(value**3)
print(cubes)
#Get the cube of the first 10 numbers shorthand (list comprehension)
cubes2 = [value**3 for value in range(1, 11)]
print(cubes2)
| true |
65b044b7d31b1225b56d346adbfa189094698a13 | dblitz21/coding | /cars.py | 382 | 4.21875 | 4 | cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars)) #Temporarily sort
#reverse the list
print("\nHere is the reversed list:")
cars.reverse()
print(cars)
numberofcars = len(cars)
print("\nThere are " + str(numberofcars) + "... | true |
090c223991c48e21272017687dae604afb7a7de7 | sanketkothiya/Learn-Python | /Ex-1.py | 201 | 4.21875 | 4 | #create dictionary and take user input
dict1 = {"true":"false" , "right":"left" , "upper":"lower" , "up":"down"}
print(dict1)
print("Select your word in Dictionary")
word = input()
print(dict1[word]) | true |
14be6120c2da64ca210f584de5986aff9d081c34 | mohan78/ProjectEuler | /problem4.py | 761 | 4.28125 | 4 | # Largest 3 digit Palindrome number
"""
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.
"""
first_num = 999
second_num = 999
palindrome = []
def isPalindrome... | true |
d6219f91cba1e92c615d1550f31b1fa3f4cb6a8d | Mingda-Rui/python-learning | /head_first_python/ch02/panic.py | 647 | 4.15625 | 4 | phrase = "Don't panic!"
# we turn the String into a list
plist = list(phrase)
print(phrase)
print(plist)
for i in range(4):
plist.pop()
plist.pop(0)
plist.remove("'")
# Swap the two objects at the end of the list by
# first popping each object from the list, then using
# the popped objects to extend the list. Thi... | true |
8ecf4bcf2ee268a9410b809718702bf732197a3b | VishnuSai/Python-games-coursera | /Guess the number.py | 2,227 | 4.1875 | 4 | # "Guess the number" mini-project
# modules required
import random
import simplegui
# initialize global variables
secret_number = 0
guesses = 0
# helper function to start and restart the game
# decrements the total guesses left
# prints the guesses
def guess_left():
global guesses
guesses = guesses - 1
... | true |
3ad967c8b9676e0168e17561a18112bc07945120 | MuhammadTayyab1/learning-Python | /Basic concepts/3-conversions.py | 425 | 4.25 | 4 | # In order to convert string into int, float or convert int, float we use this
# Convert string into int
num= int(input('enter number'))
print('number in int = ',num)
# Convert string into float
num1= float(input('enter number'))
print('number in float = ',num1)
# Convert int into string
a = str(92)
prin... | true |
f7bf0a1c0880bad489e87beb767688c0e3995556 | RushikeshSP/Yay-Python-Basics | /Assignment1/A1_problem2.py | 375 | 4.34375 | 4 | # Wrire a python program to convert a tuple of string values to a tuple of integer values.
tup = ("1","22","333","4444","55555") #Taking a constant string input.
Result = []
print("Input String Tuple : ",tup)
# for i in tup:
# Result.append(int(i))
Result = [int(i) for i in tup]
... | true |
9c8c85401715f863e64320396c365e9902bd0e7d | pitordoan/devops | /reverse-string.py | 335 | 4.4375 | 4 | #!/usr/bin/python
#Different ways to print a string in reverse order of its characters
s = 'abc'
print s[::-1]
print ''.join(reversed(s))
print s[slice(None, None, -1)]
def reverse(string):
n = len(string)
new_string = ''
for i in range(n-1, -1, -1):
new_string += string[i]
print new_str... | true |
f97c31786938fce30c11c760e4dc16cf5eb9f860 | AnkurPokhrel8/BankManagementSystem | /automate1.py | 1,680 | 4.21875 | 4 | import shelve
class Bank:
def __init__(self):
print("Welcome to the BANK")
self.account_holder = []
db = shelve.open('database')
for i in list(db.keys()):
self.account_holder.append(i)
db.close()
def createAccount(self, name, address, balance):
if name not in self.account_holder:
s... | true |
d2bb378511bc70359cca142fbc38cb727350ede1 | jonathancox1/Python102 | /day_of_the_week.py | 580 | 4.5 | 4 | #prompt user for a number 0-6 to be converted to a day of the week
day = int(input('Enter a day as a number (0-6) and Ill tell you the day of the week '))
#create a default prompt
prompt = 'Your chosen day is:'
#determin the numerical value of the day from the user input
if day == 0:
print(f'{prompt} Sunday')
eli... | true |
da82bde56fd37bfa43f5272463df6757ecff3014 | dgallegos01/Python-Course | /Functions/Reusable_Function.py | 743 | 4.28125 | 4 | # we are gonna convert our Emoji program into a function
# Here is the original code:
"""
message = input(">")
words = message.split(' ')
print(words)
message = input(">")
words = message.split(' ')
emojis = {
":)": "🙂",
":(": "🙁"
}
output = ""
for word in words:
output += emojis.get(word, word) + " "... | true |
83b06381984e6c202d38bf89077a713f4ebdf91e | dgallegos01/Python-Course | /Classes/class.py | 1,203 | 4.46875 | 4 | # we will learn how to use classes in python
# classes are used to define new types. they are very important not just to python but to programming in general
# simple types are the methods we have used so far
"""
example:
Numbers
Strings
Booleans
Lists
Dictionaries
"""
# classes are used to make complex types like defi... | true |
2fe3fc390fae95939e69d1d267fce295028c0392 | dgallegos01/Python-Course | /Modules/module.py | 793 | 4.5 | 4 | # a module is basically a file with python code
# we use them to organize our code into multiple files
# we will take this piece of code and turn it into a module
# we will make a separate file called 'converters.py' and put some code into it. every file is a module
# then we will do this:
import converters # we are ca... | true |
059a9560e85ffca2d871c4b543cc1563f50ee175 | dgallegos01/Python-Course | /Lists/List Methods/exercise.py | 267 | 4.15625 | 4 | # Write a program to remove the duplicates in a list
numbers = [2,2,4,6,3,4,6,1]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number) # this will add one of every number from the original list to the new list
print(uniques) | true |
8cdc58e052f95ceb5278da01927608baadfac4e9 | dgallegos01/Python-Course | /Nested Loops/NestedLoops.py | 383 | 4.5 | 4 | # Nested loops are loops inside a loop
# example with coordinates
for x in range(4): # x starts with 0
for y in range(3): # y will print each value in range first before it goes back the the first loop
print(f'({x}, {y})') # for every x value, ther is a set of y values
""" output:
(0, 0)
(0, 1)
(0, 2)
(1,... | true |
f3eafbd386e367d66a40aba4f44330fda6cc0453 | shravankumar0811/Coding_Ninjas | /Introduction to Python/9 Searching & Sorting/Code Bubble Sort.py | 759 | 4.5 | 4 | ##Code Bubble Sort
##Send Feedback
##Given a random integer array. Sort this array using bubble sort.
##Change in the input array itself. You don't need to return or print elements.
##
##
##Input format :
##Line 1 : Integer N, Array Size
##Line 2 : Elements of the array separated by single space
##Output format :
##Ele... | true |
e99c54d11f4dffc02d03fd28ed96b1d1773b6ed1 | shravankumar0811/Coding_Ninjas | /Introduction to Python/9 Searching & Sorting/Code Merge Sort.py | 709 | 4.34375 | 4 | ##Code Merge Two Sorted Arrays
##Send Feedback
##Given two sorted arrays of Size M and N respectively, merge them into a third array such that the third array is also sorted.
##Input Format :
## Line 1 : Size of first array i.e. M
## Line 2 : M elements of first array separated by space
## Line 3 : Size of second array... | true |
b9bb38ad71a34571620cf6df170f3d4b48c9ed8d | shravankumar0811/Coding_Ninjas | /Introduction to Python/9 Searching & Sorting/Rotate Array.py | 594 | 4.40625 | 4 | ##Rotate array
##Send Feedback
##Given a random integer array of size n, write a function that rotates the given array by d elements (towards left)
##Change in the input array itself. You don't need to return or print elements.
##Input format :
##Line 1 : Integer n (Array Size)
##Line 2 : Array elements (separated by s... | true |
fcda74e98ffa560dfcd3739f7316c45ce82025bc | manikandanmass-007/manikandanmass | /Python Programs/program to print odd numbers from 1 to 100.py | 215 | 4.3125 | 4 | #program to print odd numbers from 1 to 100
start=int(input("enter the starting value:"))
end=int(input("enter the ending value:"))
for i in range(start, end+1):
if i%2!=0:
print(i, end = " ")
| true |
47ec62b7cdb60bcd08fc15c07595911fe8ddaaab | BTunney92/pands-problem-sheet | /Week5/Weekday.py | 460 | 4.3125 | 4 | #Program that outputs whether or not today is a weekday
#Author: Brendan Tunney
# This imports python's datetime module
import datetime
# Weekday function returns days as an integer (0 for Monday up to 6 for Sunday)
dayOfWeek = datetime.datetime.today().weekday()
if dayOfWeek < 5:
print ("Unfortunately, it is ... | true |
5dd09561de925974b05b8b207a048aa4d1db2ab2 | Ankit949/LinearRegression | /LinearRegression_multipleFeature.py | 1,483 | 4.125 | 4 | import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error
#loading pre-existing data set set from sklearn
diabetes=datasets.load_diabetes()
#print(diadetes)
#printing key values of dataset i.e features of data
print(diabetes.ke... | true |
72f8fca98b3edd529513e3de1f2b7d96082e2934 | bibek720/Hacktoberfest | /Python/Trie_implementation.py | 1,439 | 4.21875 | 4 | class TrieNode:
# Trie node class
def __init__(self):
self.children = [None]*26
self.isWordEnd = False
class Trie:
# Trie data structure class
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def insert(self,key):
# If not present, inserts key into t... | true |
758e03c248d6ea6c2ea119fc73ecdc7d2c55b66f | nshekhawat/PythonClass | /Questions-Unit4/Question13-Unit4.py | 303 | 4.25 | 4 | #!/usr/bin/env python
# Author: Narendra
__doc__ = '''
With a given tuple (1,2,3,4,5,6,7,8,9,10),
write a program to print the first half values in one line and the last half values in one line.
'''
tuple1 = (1,2,3,4,5,6,7,8,9,10)
middle = len(tuple1) / 2
print tuple1[:middle]
print tuple1[middle:] | true |
c84871b747bacf4aefd0c3bffb9f6676dd149926 | nshekhawat/PythonClass | /Questions-Unit4/Question2-Unit4.py | 857 | 4.46875 | 4 | #!/usr/bin/env python
# Author: Narendra
__doc__ = '''
Assign a list to a reference a , containing a regular sequence of 5 - 8 elements,
such that if you knew the first 3 elements you would be able to predict the rest. E.G: [3,6,9,12,15,21,24] .
- Using a slice operation assign 2 elements from the middle of your seque... | true |
51661069c279df5e185f9bd8b8dd04392f014362 | nshekhawat/PythonClass | /Questions-Unit4/Question10-Unit4.py | 336 | 4.375 | 4 | #!/usr/bin/env python
# Author: Narendra
__doc__ = '''
Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included)
and the values are square of keys.
'''
def square(x):
d = {}
for i in range(1, x):
d[i] = i**2
return d
if __name__ == "__main__":
p... | true |
d4e342ce06fd6dc9b2034124c4d09b46c9cf23b3 | ddg20/CS0008-f2016 | /Ch3-Ex6 Magic Dates.py | 468 | 4.125 | 4 | #name: Dhruv Gohel
#email: ddg20@pitt.edu
#date: 09/08/2016
#class: CS0008-f2016
#instructor: Max Novelli
#
#description: Introduction to programming with Python, Chapter 3, Exercise 6
#
#Notes:
month = int(input("Enter a month: "))
date = int(input("Enter a date: "))
year = int(... | true |
bd5d5cfe604da46ad7c908ead2d9d91ee8890b98 | mistyjack/pirple | /python-is-easy/homework4/main.py | 889 | 4.34375 | 4 | """
This file contains code that adds a new item to an
existing list
"""
# Create the global list called myUniqueList
myUniqueList = []
myLeftovers = []
# Create a function that makes it possible to add list items
def addNewItem(item, mainList, otherList):
# Does item exists? no, add to global list and re... | true |
b73847c154cb32553516b216a0b48caf0843701c | zeealik/My_Python_Coding | /Chapter 4/VSCode_coding_tricks.py | 412 | 4.125 | 4 | def multipy(*numbers):
total = 1
for number in numbers:
total *= number
return total
print("Start")
print(multipy(1, 2, 3))
print(multipy(1, 2, 3))
# alt + uparrow/downarrow move line up or down
# shift + alt + up to copy
# home key to go at first line
# end key to move at the end of page
# ctrl... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.