blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
14b215cd4bbf1eba8ad00724c8612941cf234650 | efecntrk/python_programming | /unit-1/variables.py | 786 | 4.1875 | 4 | '''
#place a name and give a value
#integer
age = 27
#float
gpa = 3.0
#boolean
has_kids = True
#check the type of a variable
print(type(age)) #This function tell what type of data it is
print(type(gpa))
print(type(has_kids))
'''
#check if a number is even
'''
number = 10
if number % 2 == 0:
print('It is even!... | true |
b3f654665c353ca0192af767791d9ed7375bae64 | CharlesBird/Resources | /coding/Algorithm_exercise/Leetcode/0435-Non-overlapping-Intervals.py | 1,208 | 4.34375 | 4 | """
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [[1,2],[1,2],[1,2]... | true |
ae6b40a94660f9b36a4e1954bd176acc098b8ca3 | Airman-Discord/Python-calculator | /main.py | 530 | 4.25 | 4 | print("Python Calculator")
loop = True
while loop == True:
first_num = float(input("Enter your first number: "))
operation = input("Enter your operation: ")
second_num = float(input("Enter your second number: "))
if operation == "+":
print(first_num + second_num)
elif operation == "-"... | true |
96fb4e1c83c2c41d3e23f26da20a5c36af2383ea | alexmcmillan86/python-projects | /sum_target.py | 729 | 4.125 | 4 | # finding a pair of numbers in a list that sum to a target
# test data
target = 10
numbers = [ 3, 4, 1, 2, 9 ]
# test solution -> 1, 9 can be summed to make 10
# additional test data
numbers1 = [ -11, -20, 2, 4, 30 ]
numbers2 = [ 1, 2, 9, 8 ]
numbers3 = [ 1, 1, 1, 2, 3, 4, 5 ]
# function with O(n)
def... | true |
27b8e98acdd4c3e3a3eff0b4f131751a9a9c29db | jfbm74/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 440 | 4.28125 | 4 | #!/usr/bin/python3
"""
Module that returns the number of lines of a text file:
"""
def number_of_lines(filename=""):
"""
function that returns the number of lines of a text file
:param filename: File to read
:type filename: filename
:return: integer
:rtype: int
"""
counter = 0
wit... | true |
d5490fc4962001fdb36c4885e757827a11de0225 | jfbm74/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 679 | 4.4375 | 4 | #!/usr/bin/python3
"""
Module print_square
This module prints a square with the character #
Return: Nothing
"""
def print_square(size):
"""
Function print_square
This function prints a square with the character #
Args:
size: is the size length of the square
Returns: Nothing
"""
... | true |
0022986af95ce6ad144c40436e54888205a2cdda | rraj29/Dictionaries | /game_challenge.py | 1,826 | 4.21875 | 4 | locations = {0: "You are sitting in front of a computer, learning python.",
1: "You are standing at the end of a road before a small brick building.",
2: "You are at the top of a hill.",
3: "You are inside a building, a well house for a small stream.",
4: "You are in ... | true |
0d2e5ff146429d2209e75b4531d833848ee66784 | sandrahelicka88/codingchallenges | /EveryDayChallenge/fizzbuzz.py | 855 | 4.3125 | 4 | import unittest
'''Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output Fizz instead of the number and for the multiples of five output Buzz. For numbers which are multiples of both three and five output FizzBuzz.'''
def fizzBuzz(n):
result = []
... | true |
eb5f823180f5c69fafb99a9c0502f55045bf517b | RutujaMalpure/Python | /Assignment1/Demo10.py | 335 | 4.28125 | 4 | """
. Write a program which accept name from user and display length of its name.
Input : Marvellous Output : 10
"""
def DisplayLength(name):
ans=len(name)
return ans
def main():
name=input("Enter the name")
ret=DisplayLength(name)
print("the length of {} is {}".format(name,ret))
if __name__=="__ma... | true |
cdbaac13c9d4a49dd7c6fb425b6372929aab870d | RutujaMalpure/Python | /Assignment3/Assignment3_3.2.py | 842 | 4.15625 | 4 | """
.Write a program which accept N numbers from user and store it into List. Return Maximum
number from that List.
Input : Number of elements : 7
Input Elements : 13 5 45 7 4 56 34
Output : 56
"""
def maxnum(arr):
#THIS IS ONE METHOD
#num=arr[0]
#for i in range(len(arr)):
#if(arr[i]... | true |
8d320f16d9ab715efda548016fa5bc02e96e0588 | zkevinbai/LPTHW | /ex34.quiz.py | 2,904 | 4.46875 | 4 | # my first app
# this is a quiz program which tests a novice programmer's ability to understand
# how indexing works with ordinal (0, 1, 2) and cardinal (1, 2, 3) numbers
# list of animals/answers, and indexes/questions
animal = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
List = [0, 1, 2, 3, 4, 5, ... | true |
c925b58fd1c717cd76feb44899fe65d3ac87722c | zkevinbai/LPTHW | /ex20.py | 965 | 4.3125 | 4 | # imports argument variables from terminal
from sys import argv
# unpacks argv
script, input_file = argv
# defines print_all() as a function that reads a file
def print_all(f):
print f.read()
# defines rewind() as a function that finds
def rewind(f):
f.seek(0)
# defines print_a_line as a function that print... | true |
1a78c13413ea3afdfc85f9d38600c34572b2dad8 | ivanchen52/leraning | /ST101/mode.py | 433 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 1 11:36:09 2017
@author: ivanchen
"""
#Complete the mode function to make it return the mode of a list of numbers
data1=[1,2,5,10,-20,5,5]
def mode(data):
modecnt = 0
for i in range(len(data)):
icount = data.count(data[i])
... | true |
a502a5919e592bfaf5580f83ff294cb866ca1742 | EliMendozaEscudero/ThinkPython2ndEdition-Solutions | /Chapter 10/Exercise10-3.py | 293 | 4.125 | 4 | def middle(t):
"""It takes a list and return a new list with all but
the first and last elements."""
t1 = t[:]
del t1[0]
del t1[len(t1)-1]
return t1
if __name__=='__main__':
t = [True,'Hello world',431,None,12]
print('Original: ' + str(t))
print('Modified : ' + str(middle(t)))
| true |
7760610b35f45b8ae1b9493a8e210aaa5a19f867 | EliMendozaEscudero/ThinkPython2ndEdition-Solutions | /Chapter 6/palindrome.py | 1,160 | 4.1875 | 4 | #Exercise 6-3 from "Think python 2e"
def first(word):
"""It returns the first character of a string"""
return word[0]
def last(word):
"""It returns the last character of a string"""
return word[-1]
def midle(word):
"""It returns the string between the last and the first character of a stirng"""
... | true |
7b22dbbe8673675d1ecfca185877c903899b4745 | EliMendozaEscudero/ThinkPython2ndEdition-Solutions | /Chapter 10/Exercise10-5.py | 363 | 4.125 | 4 | def is_sorted(t):
"""It take a list and returns True if it's sorted in
ascending order and False otherwise."""
t1 = t[:]
t1.sort()
if t == t1:
return True
else:
return False
if __name__=='__main__':
t = [42,1,32,0,-2341,2]
t1 = [1,3,5,10,100]
print(str(t)+'\nSorted: '+str(is_sorted(t)))
prin... | true |
1475f834d657d0a4bd22927def4b5ec47f8f9b24 | Chris-LewisI/OOP-Python | /week-7/set_assignment.py | 1,043 | 4.375 | 4 | # Author: Chris Ibraheem
# The following code below will use the random module to create a list of values from 1 to 10.
# Using the code below to create a random list of values, do the following:
# Count the number of times each number (1-10) appears in the list that was created. Print out a formatted string that lists... | true |
8ce325259a74dff8fb76ded6fbbaca275aa86624 | Chris-LewisI/OOP-Python | /week-1-&-2/exercise-1.py | 267 | 4.1875 | 4 | # author: Chris Ibraheem
# takes first name as input after prompt
first_name = input("First Name: ")
# takes last name as input after prompt
last_name = input("Last Name: ")
# prints a greeting using the string input from the user
print(f"Hello {first_name} {last_name}!")
| true |
c2ca0fda6cce4e0a8461479fba4b2488dc930471 | NickjClark1/PythonClass | /Chapter 5/rebuiltfromscratch.py | 682 | 4.125 | 4 | # Output program's purpose
print("Decimal to Base 2-16 converter\n")
def main():
print("Decimal to Base 2-16 converter\n")
number = int(input("Enter a number to convert: "))
for base in range(1, 17):
print (convertDecimalTo(number, base))
#end main function
def convertDecim... | true |
ed03cef20773b13070143965de70c7ae5bbff50e | aayush26j/DevOps | /practical.py | 275 | 4.28125 | 4 | num=int(input(print("Enter a number\n")))
factorial = 1
if num < 0:
print("Number is negative,hence no factorial.")
elif num ==0:
print("The factorial is 1")
else:
for i in range(1,num+1):
factorial=factorial*i
print("The factorial is ",factorial) | true |
ecb0fcd7b5843debc01afe56646dd0ad834db33b | jocassid/Miscellaneous | /sqlInjectionExample/sqlInjection.py | 2,942 | 4.15625 | 4 | #!/usr/bin/env python3
from sqlite3 import connect, Cursor
from random import randint
class UnsafeCursor:
"""Wrapper around sqlite cursor to make it more susceptible to a basic
SQL injection attack"""
def __init__(self, cursor):
self.cursor = cursor
def execute(self, sql, params=... | true |
3d9afb50aa377e790a19cdabd9db440969fae7a8 | jkaria/coding-practice | /python3/Chap_9_BinaryTrees/9.2-symmetric_binary_tree.py | 1,627 | 4.25 | 4 | #!/usr/local/bin/python3
from node import BinaryTreeNode
def is_symmetric(tree):
def check_symmetric(subtree_0, subtree_1):
if not subtree_0 and not subtree_1:
return True
elif subtree_0 and subtree_1:
return (subtree_0.data == subtree_1.data
and check_s... | true |
9a3c939c18e9c648a02710031af7e5da96cc3374 | krunal16-c/pythonprojects | /Days_to_years.py | 440 | 4.3125 | 4 | # Converting days into years using python 3
WEEK_DAYS = 7
# deining a function to find year, week, days
def find(no_of_days):
# assuming that year is of 365 days
year = int(no_of_days/365)
week = int((no_of_days%365)/WEEK_DAYS)
days = (no_of_days%365)%WEEK_DAYS
print("years",year,
"\nWe... | true |
130aee595a5c7aa78c89d5ee034129315afdbe10 | mrkarppinen/the-biggest-square | /main.py | 1,804 | 4.1875 | 4 |
import sys
def find_biggest_square(towers):
# sort towers based on height
towers.sort(key=lambda pair: pair[1], reverse = True)
# indexes list will hold tower indexes
indexes = [None] * len(towers)
biggestSquare = 0
# loop thorough ordered towers list
for tower in towers:
height ... | true |
4239700e5be91ec7126fecc11dbc4ab405f22a3e | RHIT-CSSE/catapult | /Code/Raindrops/StevesObjectExamples/EmployeeClass.py | 1,055 | 4.375 | 4 | # First we define the class:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
# End of c... | true |
69e2a5128e5c34f2968e5bde4ea733630ef74134 | RHIT-CSSE/catapult | /Code/DogBark/Session3FirstProgram.py | 2,700 | 4.75 | 5 | # This is an example of a whole program, for you to modify.
# It shows "for loops", "while loops" and "if statements".
# And it gives you an idea of how function calls would be used
# to make an entire program do something you want.
# Python reads the program from top to bottom:
# First there are two functions. These... | true |
69beb8bab0fe28d2e94cc6f12b60ecf73dba3852 | dmaydan/AlgorithmsTextbook-Exercises | /Chapter4/exercise2.py | 210 | 4.28125 | 4 | # WRITE A RECURSIVE FUNCTION TO REVERSE A LIST
def reverse(listToReverse):
if len(listToReverse) == 1:
return listToReverse
else:
return reverse(listToReverse[1:]) + listToReverse[0:1]
print(reverse([1])) | true |
0cc02c8d3f8a59c29a8ef55ab9fee88a2f768399 | Suiname/LearnPython | /dictionary.py | 861 | 4.125 | 4 | phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print phonebook
phonebook2 = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
print phonebook2
print phonebook == phonebook2
for name, number in phonebook.iteritems():
print "Phone... | true |
2fb640ca926f9769d4ee6f9c0de68e1de8b5729c | organisciak/field-exam | /stoplisting/__init__.py | 1,421 | 4.1875 | 4 | '''
Python code
Example of word frequencies with and without stopwords.
Uses Natural Language Toolkit (NLTK) - Bird et al. 2009
bush.txt is from http://www.bartleby.com/124/pres66.html
obama.txt is from http://www.whitehouse.gov/blog/inaugural-address
'''
from nltk import word_tokenize
from nltk.probability import ... | true |
6d315993b7fe772ac2d2fe290db19438efad581e | sumittal/coding-practice | /python/print_anagram_together.py | 1,368 | 4.375 | 4 | # A Python program to print all anagarms together
#structure for each word of duplicate array
class Word():
def __init__(self, string, index):
self.string = string
self.index = index
# create a duplicate array object that contains an array of Words
def create_dup_array(string, size):
... | true |
39ac1ff3e0e7a78438a9015f83708fc95fdcf1b4 | sumittal/coding-practice | /python/trees/diameter.py | 930 | 4.1875 | 4 | """
Diameter of a Binary Tree
The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes.
"""
class Node:
def __init__(self,val):
self.data = val
self.left = None
self.right = None
def height(root):
if ... | true |
0b6eaf6f099c3b7197101b2d8892e3529f2f0c75 | FabioOJacob/instruct_test | /main.py | 2,136 | 4.1875 | 4 | import math
class Point():
"""
A two-dimensional Point with an x and an y value
>>> Point(0.0, 0.0)
Point(0.0, 0.0)
>>> Point(1.0, 0.0).x
1.0
>>> Point(0.0, 2.0).y
2.0
>>> Point(y = 3.0, x = 1.0).y
3.0
>>> Point(1, 2)
Traceback (most recent call last):
...
V... | true |
a2df6569fb7553f72667c03ae67ace637b9b9dbb | akaliutau/cs-problems-python | /problems/sort/Solution406.py | 1,615 | 4.125 | 4 | """ You are given an array of people, people, which are the attributes of some
people in a queue (not necessarily in order). Each people[i] = [hi, ki]
represents the ith person of height hi with exactly ki other people in front
who have a height greater than or equal to hi. Reconstruct and return the
queu... | true |
657280e2cf8fbbc26b59ed7830b342713cac502b | akaliutau/cs-problems-python | /problems/hashtable/Solution957.py | 1,240 | 4.15625 | 4 | """ There are 8 prison cells in a row, and each cell is either occupied or
vacant.
Each day, whether the cell is occupied or vacant changes according to the
following rules:
If a cell has two adjacent neighbors that are both occupied or both vacant,
then the cell becomes occupied. Otherwise, it... | true |
1ac4822dd02e34f946f4183122d8a6b5ec804d02 | akaliutau/cs-problems-python | /problems/greedy/Solution678.py | 1,937 | 4.25 | 4 | """ Given a string containing only three types of characters: '(', ')' and '*',
write a function to check whether trightBoundarys string is valid. We define
the validity of a string by these rules:
Any left parenthesis '(' must have a corresponding right parenthesis ')'. Any
right parenthesis ')' must... | true |
f4248de8ff831fbb0103ccce3c0effde23ea28ad | akaliutau/cs-problems-python | /problems/backtracking/Solution291.py | 830 | 4.4375 | 4 | """ Given a pattern and a string s, return true if s matches the pattern. A
string s matches a pattern if there is some bijective mapping of single
characters to strings such that if each character in pattern is replaced by
the string it maps to, then the resulting string is s. A bijective mapping
means t... | true |
9369936045f15e39fe607e57906f4811c519fde6 | akaliutau/cs-problems-python | /problems/bfs/Solution1293.py | 1,001 | 4.28125 | 4 | """ Given a m * n grid, where each cell is either 0 (empty) or 1 (obstacle). In
one step, you can move up, down, left or right from and to an empty cell.
Return the minimum number of steps to walk from the upper left corner (0, 0)
to the lower right corner (m-1, n-1) given that you can eliminate at most k
... | true |
41acdd2f91669a03c8ab44e35ea7a7b786be3454 | anettkeszler/ds-algorithms-python | /codewars/6kyu_break_camel_case.py | 508 | 4.4375 | 4 | # Complete the solution so that the function will break up camel casing, using a space between words.
# Example
# solution("camelCasing") == "camel Casing"
import re
def solution(s):
result = ""
for char in s:
if char.isupper():
break
result += char
result += " "
split... | true |
b5b4ebc84d31f10c982dfc65275c44cf9d6a6703 | saraatsai/py_practice | /number_guessing.py | 928 | 4.1875 | 4 | import random
# Generate random number
comp = random.randint(1,10)
# print (comp)
count = 0
while True:
guess = input('Guess a number between 1 and 10: ')
try:
guess_int = int(guess)
if guess_int > 10 or guess_int < 1:
print('Number is not between 1 and 10. Please enter a valid n... | true |
bb20892c11b9fedb0fe35696b45af31451bbe7e8 | Devbata/icpu | /Chapter3/Fexercise3-3-1.py | 594 | 4.25 | 4 | # -*- coding: utf-8 -*-
#Bisecting to find appproximate square root.
x = float(input('Please pick a number you want to find the square root of: '))
epsilon = 1*10**(-3)
NumGuesses = 0
low = 0.0
high = max(1.0, abs(x))
ans = (high + low)/2.0
while abs(ans**2 - abs(x)) >= epsilon:
print('low =', low, 'high... | true |
6858af583e1ad4657650d185b87f289aec26a1a4 | Anvin3/python | /Basic/divisor.py | 261 | 4.15625 | 4 | '''
Create a program that asks the user for a number and then prints out a list of all the divisors of that number.
'''
num=int(input("Please enter a number of your choice:"))
subList=[i for i in range(2,num) if num%i==0 ]
print("All the divisors are",subList) | true |
382dbb2572586d26f9f335e004f6886f74abdc07 | anjana-analyst/Programming-Tutorials | /Competitive Programming/DAY-29/metm.py | 323 | 4.15625 | 4 | def time(hh,mm,ss):
return hh+(mm/60)+(ss/60)/60
def distance():
m=int(input("Enter the meters"))
hh=int(input("Enter the hours"))
mm=int(input("Enter the minutes"))
ss=int(input("Enter the seconds"))
miles=(m*0.000621372)/time(hh,mm,ss);
print("Miles per hour is ",miles)
distance... | true |
63d10fa7f02ba38539f03a49c09dccb6d36dbc70 | MiguelBim/Python_40_c | /Challenge_31.py | 1,250 | 4.1875 | 4 | # CHALLENGE NUMBER 31
# TOPIC: Funct
# Dice App
# https://www.udemy.com/course/the-art-of-doing/learn/lecture/17060876#overview
import random
def dice_app(num_of_dice, roll_times):
total_count = 0
print("\n-----Results are as followed-----")
for rolling in range(roll_times):
val_from_rolling = ra... | true |
18a56761663e1202e10e77d40b4a6cfb5cd47763 | JordiDeSanta/PythonPractices | /passwordcreator.py | 1,600 | 4.34375 | 4 | print("Create a password: ")
# Parameters
minimunlength = 8
numbers = 2
alphanumericchars = 1
uppercasechars = 1
lowercasechars = 1
aprobated = False
def successFunction():
print("Your password is successfully created!")
aprobated = True
def printPasswordRequisites():
print("The password requires:")
... | true |
736fbfee5775cb351f4ee8acabeb5321c0a38c84 | SinglePIXL/CSM10P | /Homework/distanceTraveled.py | 451 | 4.3125 | 4 | """
Alec
distance.py
8-21-19
Ver 1.4
Get the speed of the car from the user then we calculate distances traveled for
5, 8, and 12 hours.
"""
mph = int(input('Enter the speed of the car:'))
time = 5
distance = mph * time
print('The distance traveled in 5 miles is:', distance)
time = 8
distance = mph * time
print('The di... | true |
e7acd1abad675af9ccd1b1b8bddc11884020ea8b | SinglePIXL/CSM10P | /Testing/10-7-19 Lecture/errorTypes.py | 982 | 4.125 | 4 | # IOError: if the file cannot be opened.
# ImportError: if python cannot find the module.
# ValueError: Raised when a built in operation or function recieves an argument
# that has the right type but an inapropriate value
# KeyboardInterrupt: Raised when the user hits the interrupt key
# EOFError: Raised one of the... | true |
288f685744aa6609b795bf433a18ea2ffbb24008 | SinglePIXL/CSM10P | /Testing/9-13-19 Lecture/throwaway.py | 489 | 4.1875 | 4 | def determine_total_Grade(average):
if average <= 100 and average >= 90:
print('Your average of ', average, 'is an A!')
elif average <= 89 and average >= 80:
print('Your average of ', average, 'is a B.')
elif average <= 79 and average >= 70:
print('Your average of ', average, '... | true |
6e1fb9392f9533ac4803cc93cb122d4ddd85ab52 | SinglePIXL/CSM10P | /Lab/fallingDistance.py | 874 | 4.21875 | 4 | # Alec
# fallingDistance.py
# 9-21-19
# Ver 1.3
# Accept an object's falling time in seconds as an argument.
# The function should return the distance in meters that the object has fallen
# during that time interval. Write a program that calls the function in a loop
# that passes the values 1 through 10 as arguments a... | true |
d1f1e3c5760e32f745a2d798bba26f1c1abb3ca2 | MyloTuT/IntroToPython | /Homework/HW1/hw1.py | 1,213 | 4.25 | 4 | #!/usr/bin/env python3
#Ex1.1
x = 2 #assign first to variable
y = 4 #assign second to variable
z = 6.0 #assign float to variable
vsum = x + y + z
print(vsum)
#Ex1.2
a = 10
b = 20
mSum = 10 * 20
print(mSum)
#Ex1.3
var = '5'
var2 = '10'
convert_one = int(var) #convert var into an int and assign to a variab... | true |
ce5015940881770acdbb6fd87af458b35d99c86b | GingerBeardx/Python | /Python_Fundamentals/type_list.py | 908 | 4.40625 | 4 | def tester(case):
string = "String: "
adds = 0
strings = 0
numbers = 0
for element in case:
print element
# first determine the data type
if isinstance(element, float) or isinstance(element, int) == True:
adds += element
numbers += 1
elif isin... | true |
a2c485ba03991204912d6dd23b32d8d17daa3c25 | GingerBeardx/Python | /Python_Fundamentals/loops.py | 340 | 4.34375 | 4 | for count in range(0, 5):
print "looping - ", count
# create a new list
# remember lists can hold many data-types, even lists!
my_list = [4, 'dog', 99, ['list', 'inside', 'another'], 'hello world!']
for element in my_list:
print element
count = 0
while count < 5: # notice the colon!
print 'looping - ', c... | true |
780c24fd5b63cab288383303d3ac8680691afd18 | MicheSi/code_challenges | /isValid.py | 1,421 | 4.34375 | 4 | '''
Sherlock considers a string to be valid if all characters of the string appear the same number of times. It is also valid if he can remove just character at index in the string, and the remaining characters will occur the same number of times. Given a string , determine if it is valid. If so, return YES, otherwis... | true |
aa2e42c78db54ca867c25ce2113b7914bcc666ee | Keshav1506/competitive_programming | /Bit_Magic/004_geeksforgeeks_Toggle_Bits_Given_Range/Solution.py | 2,703 | 4.15625 | 4 | #
# Time :
# Space :
#
# @tag : Bit Magic
# @by : Shaikat Majumdar
# @date: Aug 27, 2020
# **************************************************************************
# GeeksForGeeks: Toggle bits given range
#
# Description:
#
# Given a non-negative number N and two values L and R.
# The problem is to toggle the bits ... | true |
31f5a45e28ccb77adff1f5f3761e9297a121f0cd | Keshav1506/competitive_programming | /Tree_and_BST/021_leetcode_P_366_FindLeavesOfBinaryTree/Solution.py | 2,439 | 4.25 | 4 | #
# Time : O(N) [ We traverse all elements of the tree once so total time complexity is O(n) ] ; Space: O(1)
# @tag : Tree and BST ; Recursion
# @by : Shaikat Majumdar
# @date: Aug 27, 2020
# **************************************************************************
#
# LeetCode - Problem - 366: Find Leaves of Binary ... | true |
0fff29228279abcae6d9fa67f111602e0423db66 | hakepg/operations | /python_sample-master/python_sample-master/basics/deepcloning.py | 757 | 4.15625 | 4 | import copy
listOfElements = ["A", "B", 10, 20, [100, 200, 300]]
# newList= listOfElements.copy() -- list method- performs shallow copy
newList = copy.deepcopy(listOfElements) # Deep copy -- method provided by copy module
newList1 = copy.copy(listOfElements) # Shallow copy -- method provided by copy module
pr... | true |
10841b4db43d984e677eec6a8dcd00415bc8c098 | hakepg/operations | /python_sample-master/python_sample-master/basics/listExample.py | 525 | 4.15625 | 4 | # Sort in the list
# Two ways: list method -- sort and built in function -- sorted
listOfElements = [10,20,30,45,1,5,23,223,44552,34,53,2]
# Difference between sort and sorted
print(sorted(listOfElements)) # Creates new sorted list
print(listOfElements) # original list remains same
print(listOfElements.... | true |
5e49178aa33566d2e953913f919101f8a2bc1e93 | akjadon/HH | /Python/Python_Exercise/Python_Exercise1/ex38.py | 569 | 4.28125 | 4 | """Write a program that will calculate the average word length of a text
stored in a file (i.e the sum of all the lengths of the word tokens in the
text, divided by the number of word tokens)."""
from string import punctuation
def average_word_length(file_name):
with open(file_name, 'r') as f:
for line in f:
... | true |
f50269a35eb4da827425795badc0ba7eab421a92 | akjadon/HH | /Python/Python_Exercise/Python_Exercise1/ex46.py | 2,938 | 4.4375 | 4 | """An alternade is a word in which its letters, taken alternatively in a
strict sequence, and used in the same order as the original word, make up at
least two other words. All letters must be used, but the smaller words are not
necessarily of the same length. For example, a word with seven letters where
every seco... | true |
2a5f3f611ca53f2e173c3ec12fba914a98480d6f | gmastorg/CSC121 | /M2HW1_NumberAnalysis_GabrielaCanjura(longer).py | 1,275 | 4.1875 | 4 | # gathers numbers puts them in a list
# determines correct number for each category
# 02/12/2018
# CSC-121 M2HW1 - NumberAnalysis
# Gabriela Canjura
def main():
total = float(0)
numOfNumbers = int(20) # decides loop count and used for average
total,numbers = get_values(numOfNumbers)
... | true |
1f9f2c05bffaf755d40164b3704909532d50243a | motaz-hejaze/lavaloon-problem-solving-test | /problem2.py | 1,451 | 4.1875 | 4 | print("***************** Welcome ********************")
print("heaviest word function")
print("python version 3.6+")
print("run this script to test the function by yourself")
print("or run test_problem2 for unittest script ")
# all alphabets
alphabet_dict = {
"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7,... | true |
0c62ff7ab5bf7afeb43db3d74580deb06abe89a2 | rohit2219/python | /decorators.py | 1,068 | 4.1875 | 4 | '''
decorator are basically functions which alter the behaviour/wrap the origonal functions and use the original functions
output to add other behavious to it
'''
def add20ToaddFn(inp):
def addval(a,b):
return inp(a,b) + 20
addval.unwrap=inp # this is how you unwrap
return addval
@add20ToaddFn
def... | true |
069de02a13505fa4c356308b8ed189446807612c | BondiAnalytics/Python-Course-Labs | /13_list_comprehensions/13_04_fish.py | 333 | 4.25 | 4 | '''
Using a listcomp, create a list from the following tuple that includes
only words ending with *fish.
Tip: Use an if statement in the listcomp
'''
fish_tuple = ('blowfish', 'clownfish', 'catfish', 'octopus')
fish_list = list(fish_tuple)
print([i for i in fish_list if i[-4:] == "fish"])
# fishy = []
# for i in ... | true |
cd318be0b06227fc766e910ea786fb792c02fced | BondiAnalytics/Python-Course-Labs | /14_generators/14_01_generators.py | 245 | 4.375 | 4 | '''
Demonstrate how to create a generator object. Print the object to the console to see what you get.
Then iterate over the generator object and print out each item.
'''
gen = (x**2 for x in range(1,6))
for i in gen:
print(i)
print(gen) | true |
6de2ac2bbde9274df1540b29f9c983a39253bd57 | the-matrixio/ml_competition_didi | /preprocess_data/get_weekday.py | 630 | 4.1875 | 4 | '''
Given absolute time, return weekday as an integer between 0 and 6
Arguments:
Absolute time (integer)
Returns:
Integer between 0 and 6 inclusive. Monday is 0, Sunday is 6.
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import calendar
def get_wee... | true |
77db9841cf16c96919bf770b7f01e9a2e9abd864 | tegamax/ProjectCode | /Common_Questions/TextBookQuestions/PythonCrashCourse/Chapter_8/8_11.py | 1,260 | 4.21875 | 4 | '''
8-11. Archived Messages: Start with your work from Exercise 8-10.
Call the function send_messages() with a copy of the list of messages.
After calling the function, print both of your lists to show that the original list has retained its messages.
'''
'''
def send_messages(short_list):
sent_messages = []
... | true |
4a6aa2ffcf88c2e4a38ce56fab7d316f6d4e0114 | tegamax/ProjectCode | /Common_Questions/TextBookQuestions/PythonCrashCourse/Chapter_9/Ex_9_4.py | 1,639 | 4.28125 | 4 | '''
9-4. Number Served: Start with your program from Exercise 9-1 (page 162). Add an attribute called number_served with a default value of 0.
Create an instance called restaurant from this class. Print the number of customers the restaurant has served,
and then change this value and print it again.
Add a method call... | true |
b2def23578d639e50d6eea882e5b9a8246edb01b | Pajke123/ORS-PA-18-Homework07 | /task2.py | 469 | 4.1875 | 4 |
"""
=================== TASK 2 ====================
* Name: Recursive Sum
*
* Write a recursive function that will sum given
* list of integer numbers.
*
* Note: Please describe in details possible cases
* in which your solution might not work.
*
* Use main() function to test your solution.
========================... | true |
077e070ecddeedee387a0a9b9b658262af4eccaf | AMfalme/OOP-python-Furniture-sales | /OOP_file.py | 1,182 | 4.1875 | 4 | from abc import ABCMeta, abstractmethod
class Electronics(object):
"""docstring for Electronics
This is an abstract Base class for a vendor selling Electronics of various types.
"""
__metaclass__ = ABCMeta
def __init__(self, make, year_of_manufacture, sale_date, purchase_price, selling_price, purchase_date):
... | true |
61123681d1a35d9a00b4cfba76103fc78ca105e5 | dionysus/coding_challenge | /leetcode/088_MergeSortedArray.py | 1,297 | 4.1875 | 4 | '''
88. Merge Sorted Array
URL: https://leetcode.com/problems/merge-sorted-array/
Given two sorted integer arrays nums1 and nums2,
merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is... | true |
05d0485e40117cf2b4e8063942e6cb4154569ac6 | MankaranSingh/Algorithms-for-Automated-Driving | /code/exercises/control/get_target_point.py | 981 | 4.125 | 4 |
import numpy as np
def get_target_point(lookahead, polyline):
""" Determines the target point for the pure pursuit controller
Parameters
----------
lookahead : float
The target point is on a circle of radius `lookahead`
The circle's center is (0,0)
poyline: array_li... | true |
5a129e2a8a4dd86d3d295899ff3cf8e015afd5fb | calvinstudebaker/ssc-scheduling | /src/core/constants.py | 2,840 | 4.28125 | 4 | """Hold values for all of the constants for the project."""
class Constants():
"""This is a class for managing constants in the project."""
STRINGS = {}
@classmethod
def get_string(cls, val, dictionary=None):
"""Get the string representation of the given constant val.
Looks in the subclass's dictionary cal... | true |
a6da2062585d75edf9643bdac2f9df4619211327 | vijaypatha/python_sandbox | /numpie_mani.py | 2,173 | 4.375 | 4 | '''
pretty simple:
1) Create a array
2) Manipylate the arary: Accessing, deleting, inserting, slicing etc
'''
#!/usr/bin/env python
# coding: utf-8
# In[10]:
import numpy as np
#Step 1: Create a array
x = np.arange(5,55,5).reshape(2,5)
print("Array X is:")
print(x)
print("Attrubute of Array X is:")
print("# of ... | true |
86f2268590847d4f99e6899e8049b7a2abe72ac4 | anjalak/Code-Archive | /Python_Code/python code/bitOperator.py | 892 | 4.21875 | 4 | # Create a function in Python called bitOperator that takes two bit strings of length 5 from the user.
# The function should return a tuple of the bitwise OR string, and the bitwise AND string
# (they need not be formatted to a certain length, see examples).
def bitOperator(int1, int2):
num1 = int(int1,2);
nu... | true |
8782817b87ac1f819b078b3c773778f2c72a93ee | davide-coccomini/Algorithmic-problems | /Python/steps.py | 988 | 4.15625 | 4 | # Given the number of the steps of a stair you have to write a function which returns the number of ways you can go from the bottom to the top
# You can only take a number of steps based on a set given to the function.
# EXAMPLE:
# With N=2 and X={1,2} you can go to the top using 2 steps or you can use a single step... | true |
b3080fe028e3a62ade5b64a57da7ce9276c650ae | niksm7/March-LeetCoding-Challenge2021 | /Palindromic Substrings.py | 622 | 4.15625 | 4 | '''
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
'''
... | true |
77de892bfce5df9d0d5c9bad7cde7b401e1ba38e | TheDarkKnight1939/FirstYearPython | /3.py | 539 | 4.28125 | 4 | #!/usr/bin/python
import random #Imports the class random
r=random.randint(10,66) #Uses the randint function to choose a number from 10 to 66
print(r) #Prints the random number choosen
if r<35: #If loop which checks if the number is lesser than 35
print(r)
print(": is less than 35 \n")
exit
elif r==30:#If loop whi... | true |
aad35df15da4265e65defc8f609290a342e727f3 | gaurav-singh-au16/Online-Judges | /Binary_Search_Problems/nth_fibonacci_no.py | 916 | 4.1875 | 4 | """
Nth Fibonacci Number
The Fibonacci sequence goes like this: 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
The next number can be found by adding up the two numbers before it, and the first two numbers are always 1.
Write a function that takes an integer n and returns the nth Fibonacci number in the sequence.
Constraints
n ... | true |
86a7c2270c42fdd3e898d027dac3f0c63d07fbc8 | gaurav-singh-au16/Online-Judges | /Leet_Code_problems/69. Sqrt(x).py | 543 | 4.15625 | 4 | """
69. Sqrt(x)
Easy
1657
2143
Add to List
Share
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.
Example 1:
Input: x = 4
Output: 2
Example 2:
Input: x = 8
Outpu... | true |
d5fee0cdc323a6feca2f3b7cf95cc59f909bbfab | tsakaloss/pycalculator | /calculator.py | 2,930 | 4.375 | 4 | import sys
from lib import operations
# Manage the operations
def mathing_func(a, b, sign):
if sign == '+':
return operations.Calculations.plus(a, b)
elif sign == '-':
return operations.Calculations.minus(a, b)
elif sign == '*':
return operations.Calculations.multiply(a, b)
eli... | true |
0c3925c9dfd8736a0f5836d2139fdf6d6a259a70 | lightdarkx/python-snippets | /LinearSearch.py | 513 | 4.28125 | 4 | # Program to implement linear search in a given array/list
def linearSearch(arr,search_item):
print(f"search_item: {search_item}")
for i in arr:
if (i == search_item):
return -2,i
#print(f"i: {i}")
return -1,-1
arr = [1,2,3,4,5]
search_item... | true |
e9a6d1c8de9290cf452f81f35df46f9ab2f9e48a | Meeds122/Grokking-Algorthms | /4-quicksort/quicksort.py | 1,280 | 4.21875 | 4 | #!/usr/bin/python3
def quickSort(arr):
working_array = arr.copy()
working_array_length = len(working_array)
if working_array_length <= 1:
# Empty element or single element case
return working_array
elif working_array_length == 2:
# only 2 elements case
if working_array[0... | true |
def9cd930313f4fe0e6f5219f51e25e31ff04788 | andrewswellie/Python_Rock_Paper_Scissors | /RockPaperScissors.py | 1,537 | 4.15625 | 4 | # Incorporate the random library
import random
restart = 1
while restart != "x":
print("Let's Play Rock Paper Scissors!!!")
options = ["r", "p", "s"]
computer_choice = random.choice(options)
user_choice = input("You are playing against the computer. His choice is completely random. Make your Choi... | true |
368ec147cd5f547160e88580a4c11783f2f79f98 | pani-vishal/String-Manipulation-in-Python | /Problem 7.txt | 221 | 4.21875 | 4 | #Program to count no. of letters in a sentence/word
sent=input("Enter a sentence: ")
sent=sent.lower()
count=0
for x in sent:
if (x>='a' and x<='z'):
count+=1
print("Number of letters: "+str(count))
| true |
f91a700285537cbbd9f51fb70d8d7ae0559d1709 | jeremymatt/DS2FP | /drop_illogical.py | 713 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 25 22:59:05 2019
@author: jmatt
"""
def drop_illogical(df,var1,var2):
"""
Drops records from the dataframe df is var1 is greater than var2
For example, if var1 is spending on clothing and var2 is total income
it is not logical that var1 is grea... | true |
051d08ec216fff8651d3a096578c7fa38ba875ed | CLAHRCWessex/math6005-python | /Labs/wk1/if_statement_preview.py | 1,884 | 4.6875 | 5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Week 1 Extra Material: If-then statements
A short look ahead at conditionals and if statements.
We will cover these in detail in week 2. But feel free to have edit the code
below to see how it works.
In most Python programmes that you write you will be using if... | true |
c7d99b39a0557d62a59e5607c9620f2bcfcab248 | eshanmherath/neural-networks | /perceptron/simple_perceptron_OR_gate.py | 2,098 | 4.15625 | 4 | import numpy as np
class Perceptron:
def __init__(self, number_of_inputs, learning_rate):
self.weights = np.random.rand(1, number_of_inputs + 1)[0]
self.learning_rate = learning_rate
"""A step function where non-negative values are returned by a 1 and negative values are returned by a -1"""
... | true |
e347dab6cada8dfd16b370d9f40f3b590b949a2e | tvocoder/learning_python | /python_functional_programming.py | 1,191 | 4.59375 | 5 | # Functional Programming
print("---= Functional Programming =---")
print("--= Map =--")
# Description: Applies function to every item of an iterable and returns a list of the results.
# Syntax: map(function,iterable[,...])
# -- function: Required. A function that is used to create a new list.
# -- iterable: Required. ... | true |
304598e5e382fad84021f4a95d5a395b957a4456 | tvocoder/learning_python | /python_callable_func.py | 2,317 | 4.5 | 4 | print("---= Callables Operators =---")
print("-- *(tuple packing) --")
# Description: Packs the consecutive function positional arguments into a tuple.
# Syntax: def function(*tuple):
# -- tuple: A tuple object used for storing the passed in arguments.
# All the arguments can be accessed within the function body the s... | true |
2690b3fb0d1b3339f9b29f8c5c81638c0eefb682 | Python-aryan/Hacktoberfest2020 | /Python/sum of list-elements.py | 287 | 4.25 | 4 | #Calculates the sum of a list of numbers
number = int(input("Enter number of elements: "))
elements = []
for i in range(number):
x = int(input("Enter {} number: ".format(i+1)))
elements.append(x)
sum=0
for i in elements:
sum=sum+i
print("Sum of the list elements is: ",sum)
| true |
bb62b6e47c6d5606a253690c003d9b72b6aea79e | docljn/python-self-study | /wesleyan_intro/module_3/name_phone.py | 925 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 28 15:48:51 2018
@author: DocLJN
"""
import sys
import csv
# open the csv file here
filename = sys.argv[1]
file = open(filename, 'w')
while True:
nextname = input("Enter a friend's name, press return to end: ")
if nextname == "":
... | true |
4585d9c998c7312a8a2541259970987d700b45ab | Scorch116/PythonProject---Simple-calculator | /Calculator.py | 1,261 | 4.25 | 4 | '''Simple calculator used to perform basic calculator functions such as addition,
subtraction,division and multplication'''
def Addition(value1, value2): # this function will add the two numbers
return value1 + value2
def subtract (value1, value2):
return value1 - value2
def Divide(value1, value2):
retur... | true |
d6374434fb6c9d67a684c3db37d6bc34e7701fd9 | abhinavmittal93/Week1_Circle_Radius | /Week1_coding.py | 320 | 4.1875 | 4 | import math
import datetime
def calc_radius():
radius = float(input('Enter the radius of the circle: '))
area = math.pi * radius**2
print(f'Area of the circle is: {area:.2f}')
def print_date_time():
time = datetime.datetime.now()
print(f'Today\'s date: {time}')
print_date_time()
calc_radius()
| true |
9b31816c42dc2107fdbe3af38c21992213168768 | danel2005/triple-of-da-centry | /Aviel/8.3.3.py | 675 | 4.3125 | 4 | def count_chars(my_str):
"""
returns a dict that the keys are the letters and the valus are how many of them were in the string
:param my_str: the string we want to count every letter
:type my_str: str
:return: a dict that the keys are the letters and the valus are how many of them were in the strin... | true |
1c6125e33f932902b101c449ffd44c5236788bc0 | danel2005/triple-of-da-centry | /Aviel/6.4.2.py | 876 | 4.15625 | 4 | def try_update_letter_guessed(letter_guessed, old_letters_guessed):
"""
Adds the letter guessed to the array of letters that has already been guessed
:param letter_guessed: the guess that the user inputing
:param old_letters_guessed: all the letters the user already guessed
:type letter_guessed: str... | true |
2c772ed45516775c12da8c4ae9ba0d6330ab5105 | danel2005/triple-of-da-centry | /Aviel/6.4.1.py | 651 | 4.1875 | 4 | def check_valid_input(letter_guessed, old_letters_guessed):
"""
Checks if the guess is valid or not
:param letter_guessed: the guess that the user inputing
:param old_letters_guessed: all the letters the user already guessed
:type letter_guessed: string
:type old_letters_guessed: array
:retu... | true |
c889e0e9d7f44f7c13658bfeaebdb60e6ffaea8c | danel2005/triple-of-da-centry | /Aviel/7.2.2.py | 677 | 4.28125 | 4 | def numbers_letters_count(my_str):
"""
returns a list that the first number is the numbers count and the second number is the letters count
:param my_str: the string we want to check
:type my_str: str
:return: list that the first number is the numbers count and the second number is the letters count... | true |
76cde6d34c1a99e235e6c828c1aa0495810947ec | mossi1mj/SentenceValidator | /SentenceValidator.py | 882 | 4.21875 | 4 | import string
# take in sentence as variable
sentence = input("Enter a sentence: ")
# take words in sentence and place in array[] with split() function
word = sentence.split()[0] # first word in array will be 0
capitalWord = word.capitalize() # capitalize() function puts first character of a string to uppercase
# ... | true |
e9cf929eb3f418b403cbebf5b171db97ef597d76 | alejogonza/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 316 | 4.125 | 4 | #!/usr/bin/python3
"""
1-my_list
"""
class MyList(list):
"""
prints to stdout list in order
"""
def print_sorted(self):
"""
prints the list
"""
sorted_list = MyList()
for item in self:
sorted_list.append(item)
print(sorted(sorted_list))
| true |
9ef602b0e1df3f4111037ecd84e1d78d5994fffb | wesenu/COP3035-CGS5935-Introduction-to-Programming-Using-Python | /myPrograms/Chapter_4_exerciseSolution/ex4_14.py | 903 | 4.21875 | 4 | ######################################################
# 4.14 #
######################################################
rows = 7
for r in range (rows):
for c in range (rows-r):
print ('*', end = ' ')
print()
#####################################################
# end = ' ' m... | true |
15f146f69ea979780ba6d2a9610f064e0c327cc8 | wesenu/COP3035-CGS5935-Introduction-to-Programming-Using-Python | /loopExerciseStarter.py | 382 | 4.1875 | 4 | inputPIN = 0
validPIN = False
userPIN = 9999 # for example use only !
inputPIN = int(input("Please enter your PIN -> "))
validPIN = (inputPIN == userPIN)
while not validPIN:
inputPIN = int(input("Please try again. Enter your PIN -> "))
validPIN = (inputPIN == userPIN)
# know complement is true... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.