blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
cc7ef88686c8d373fd39688118340cda0064312d | brlala/Educative-Grokking-Coding-Exercise | /03. Pattern Two Pointer/7 Dutch National Flag Problem (medium).py | 932 | 4.3125 | 4 | # Problem Statement
# Given an array containing 0s, 1s and 2s, sort the array in-place. You should treat numbers of the array as objects,
# hence, we can’t count 0s, 1s, and 2s to recreate the array.
#
# The flag of the Netherlands consists of three colors: red, white and blue; and since our input array also consists
#... | true |
8a9475e083e978b40b6e164e6ff65af999ce569e | brlala/Educative-Grokking-Coding-Exercise | /11. Pattern Subsets/3. Permutations (medium).py | 862 | 4.1875 | 4 | # Problem Statement
# Given a set of distinct numbers, find all of its permutations.
def find_permutations(nums):
"""
Time:
Space:
"""
result = []
find_permutations_recursive(nums, 0, [], result)
return result
def find_permutations_recursive(nums, index, current_permutation, result):
... | true |
a6dbf81217f5306e17a270d2863d00168d42f31e | brlala/Educative-Grokking-Coding-Exercise | /04. Fast Slow pointers/2 Start of LinkedList Cycle (medium).py | 1,784 | 4.15625 | 4 | # Problem Statement
# Given the head of a Singly LinkedList, write a function to determine if the LinkedList has a cycle in it or not.
from __future__ import annotations
class Node:
def __init__(self, value, next: Node=None):
self.value = value
self.next = next
def has_cycle(head: Node):
"""... | true |
5acd5ec2f2049e1b60e92fdfbdbad9afb18a86bc | brlala/Educative-Grokking-Coding-Exercise | /04. Fast Slow pointers/5 Palindrome LinkedList (medium).py | 2,691 | 4.34375 | 4 | # Problem Statement
# Given the head of a Singly LinkedList, write a method to check if the LinkedList is a palindrome or not.
#
# Your algorithm should use constant space and the input LinkedList should be in the original form once the algorithm
# is finished. The algorithm should have O(N)O(N) time complexity where ‘... | true |
f61446620ae9390b2a49a31edd991f59a44fd4b0 | brlala/Educative-Grokking-Coding-Exercise | /11. Pattern Subsets/2. Subsets With Duplicates (easy).py | 856 | 4.125 | 4 | # Problem Statement
# Given a set with distinct elements, find all of its distinct subsets.
def find_subsets(nums):
"""
Time:
Space:
"""
list.sort(nums)
subsets = [[]]
start = end = 0
for i in range(len(nums)):
start = 0
# if current element and previous element is same,... | true |
506c4f0512af2dc99bfb707c5007be07fb74c28f | Avani22/Sorting-Algorithms | /mergesort.py | 2,974 | 4.15625 | 4 | '''
Name: Avani Chandorkar
'''
from datetime import datetime #package for calculating execution time of mergesort
import random #package for generating random numbers
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr) // 2 # Finding the mid of th... | true |
6a47a7197217100ca17e9e7639f453f8c1cb9cbd | Sahoju/old-course-material-and-assignments | /python/a14.py | 838 | 4.28125 | 4 | # Write a function called symbols that takes a string
# containing +, = and letters. The function should
# return True if all of the letters in the string
# are surrounded by a + symbol.
def IsSurroundedBy(stuff):
plusopen = False
for i in stuff:
if i == '+' and plusopen == False:
plus... | true |
c599d72d60ecb050e89cc651dd25d3834174b44b | Sahoju/old-course-material-and-assignments | /python/a10.py | 443 | 4.34375 | 4 | # Write a function, called largest, that is given a list of numbers
# and the function returns the largest number in the list.
def Largest(nums):
count = 0
largest = 0
for i in nums:
if largest < nums[count]: # i = the number in the table, not the index
largest = i
count += 1
... | true |
9ca5347804ef5bf66e9f0c62fea61b435929ac5f | lyndewright/codeguildlabs | /grading.py | 982 | 4.21875 | 4 | # version 2
score = input("What is your score?: ")
grade = int(score)
if grade >= 97:
print("You got an A+!")
elif grade >= 93:
print("You got an A!")
elif grade >= 90:
print("You got an A-!")
elif grade >= 87:
print("You got a B+!")
elif grade >= 83:
print("You got a B!")
elif grade >= 80:
pr... | true |
c4d3d1aee6d92aeb738e5b9ff8c93a33cfc63066 | mmacedom/various_exercises | /String Exercises.py | 2,964 | 4.1875 | 4 | def check_password(passwd):
""" (str) -> bool
A strong password has a length greater than or equal to 6, contains at
least one lowercase letter, at least one uppercase letter, and at least
one digit. Return True iff passwd is considered strong.
>>> check_password('I<3csc108')
True
"""
... | true |
c1b2b09570e093f8293046bc5fa8366cdf84fcb1 | cMinzel-Z/Python3-review | /Py3_basic_exercises/dict_prac_b.py | 374 | 4.1875 | 4 | d = {"Tom" : 500, "Stuart" : 1000, "Bob" : 55, "Dave" : 21274}
'''
When using a dictionary it is possible to add and delete items from it.
Provide code to delete the entry for "Bob" and add an entry for "Phil".
'''
print('修改前: ', d)
# delete the entry for "Bob"
del d['Bob']
print('删除后: ', d)
# add an entry for "Phil"... | true |
eec695623763eef57194f2e77a861817dcb69263 | oketafred/python-sandbox | /backup.py | 2,185 | 4.34375 | 4 | # Author: Oketa Fred
# Laboremus Uganda Home Assignment
# Object Definition
class Account:
# Declaring a constructor Method
def __init__(self, balance = 0):
# self.owner = owner
self.balance = balance
self.pin = 1234
# A Method for Depositing Money in their account
def deposit(self, de... | true |
b5c8e669df6a0070a27898b9cdb353782c7b7ce1 | Max143/python-strings | /use of replace().py | 283 | 4.53125 | 5 | '''
Python Program to Replace all Occurrences of ‘a’ with $ in a String
'''
# string_name.replace(2 parameter)
# 1st - replacing element
#2nd - replacing with element
string = input("Enter a sentence(Including character a): ")
final = string.replace('a', '$')
print(final)
| true |
f24cdc28b2e7712258e855be357471e17dbe6d0f | Max143/python-strings | /largest word string comparison.py | 1,132 | 4.3125 | 4 | '''
Python Program to Take in Two Strings and Display the Larger String without Using Built-in Functions
''''
# using built in functions
str1 = input("Enter a word: ")
str2 = input("Enter another word: ")
char1 = 0
char2 = 0
for char in str1:
char1 += 1
for char in str2:
char2 += 1
print("First word characte... | true |
da4ead78d29cce9ec0529a70c503b78f9317d6dc | mugambi-victor/functions | /dict/dict.py | 381 | 4.25 | 4 | #syntax for py dictionaries
thisdict={"brand":"ford","model":"mustang","year":2010 }
print(thisdict)
#accessing a dictionary element
x=thisdict["model"]
#prints the value of the model key(i.e mustang)
print(x)
#merging two dictionaries
dict2={"name":"victor", "age":20, "gender":"male"}
def merge(thisdict,dict2):
retu... | true |
5210b35e0d5346475e083ad1d77f1c3f4fe8df48 | keerthidl/python-assignment- | /concatenate.py | 266 | 4.375 | 4 | string1=input(" enter the first to concatenate: ");
string2=input("enter the second to concatenate: ");
string3= string1+string2;
print("string after concatenate is: ", string3);
print("string1=", string1);
print("string2=", string2);
print("string3=", string3);
| true |
94be280021b0af439cc6da9c46626b6075f439ad | ColeRichardson/CSC148 | /lectures/lecture 8/nary trees.py | 1,304 | 4.125 | 4 | def __len__(self) -> int:
"""
returns the number of items contained in this tree
>>> t1 = Tree(None, [])
>>> len(t1)
0
>>> t2 = Tree(3, )
"""
if self.Is_empty():
return 0
size = 1
for child in self.children:
size += len(child)
return size
def count(self, item... | true |
e2c031b04449d83bf9c0ab5eb8d4050df614d4f9 | sampadadalvi22/Design-Analysis-Of-Algorithms | /measure_time.py | 447 | 4.21875 | 4 | import time
def recursive(n):
if n==1:
return n
else:
return n*recursive(n-1)
def iterative(n):
fact=1
for i in range(1,n+1):
fact=fact*i
return fact
print "fact programs check time using time clock function..."
n=input()
st=time.clock()
d1=iterative(n)
print d1
print "Iterative mea... | true |
2dace7a580833de8437c52d46618eb1b6bfaf359 | SeeMurphy/INFM340 | /netflixstock.py | 793 | 4.1875 | 4 | # This is a python script to display the first 10 rows of a csv file on Netflix stock value.
# Importing CSV Library
import csv
# file name
filename = "netflix.csv"
# Fields and Rows list
fields = []
rows = []
# reading csv
with open(filename, 'r') as csvfile:
# csv reader object
csvreader = csv.reader(csvfile)... | true |
434ec4c04c3602b8520502b9a80a840d65aa7d18 | pombredanne/snuba | /snuba/utils/clock.py | 945 | 4.15625 | 4 | import time
from abc import ABC, abstractmethod
class Clock(ABC):
"""
An abstract clock interface.
"""
@abstractmethod
def time(self) -> float:
raise NotImplementedError
@abstractmethod
def sleep(self, duration: float) -> None:
raise NotImplementedError
class SystemCloc... | true |
036901234da128c965221d41a041a39ee75b6f06 | sankeerthankam/Big-Data | /1. Python Essentials/4. For Loop.py | 2,124 | 4.6875 | 5 | ## This file contains functions that implments the following tasks using a for loop.
# 1. Write a program to print 10 even numbers and 10 odd numbers.
# 2. Write a program to find factorial of a number.
# 3. Write a program to generate tables of 10.
# 4. Write a program to add the digits of a number.
# 5. Write a pro... | true |
2678e925bc5c084d9f07339234b5051440ce8e96 | nikkiredfern/learning_python | /LPTHW/ex7.py | 1,406 | 4.15625 | 4 | #A print statement for the first line of 'mary had a little Lamb'.
print("Mary had a little lamb.")
#A print statement for the second line of 'mary had a little Lamb'. This line uses the format() function.
print("It's fleece was whit as {}.".format('snow'))
#A print statement for the third line of 'mary had a little La... | true |
09a0a30f121e6db1d223664044e80ff910618cb5 | axat1/Online-Course | /Python/Programming For EveryBody/Week7/assignment5-2.py | 841 | 4.15625 | 4 | # 5.2 Write a program that repeatedly prompts a user
# for integer numbers until the user enters
# 'done'. Once 'done' is entered, print out
# the largest and smallest of the numbers.
# If the user enters anything other than a valid number
# catch it with a try/except and put out an appropriate
# message and igno... | true |
82696c0d17a2f6d472532155e1c7c882f89b1423 | CommitHooks/LeetCode | /moveZeros.py | 548 | 4.25 | 4 | #! python
# Given an array nums, write a function to move all 0's to the end of it
# while maintaining the relative order of the non-zero elements.
"""
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums
should be [1, 3, 12, 0, 0].
"""
def shuffleZeros(aList):
for item in aList:
... | true |
3772c81192628309ad1849fb19c43d7cffce125e | wufans/EverydayAlgorithms | /2018/binary/278. First Bad Version.py | 1,681 | 4.15625 | 4 | # -*- coding: utf-8 -*-
#@author: WuFan
# You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
#
# Sup... | true |
e096f073d9c0b65e3f5482499a37e31660115584 | wufans/EverydayAlgorithms | /2018/binary/*342. Power of Four.py | 1,920 | 4.125 | 4 | # -*- coding: utf-8 -*-
#@author: WuFan
"""
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example 1:
Input: 16
Output: true
Example 2:
Input: 5
Output: false
Follow up: Could you solve it without loops/recursion?
"""
class Solution:
def isPowerOfFour(self, num):
... | true |
8c7aefb70da7f8fea7ead752722b183949f69e8c | Grazziella/Python-for-Dummies | /exercise8_1.py | 660 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Exercise 8.1 Write a function called chop that takes a list and modifies it, removing
# the first and last elements, and returns None.
# Then write a function called middle that takes a list and returns a new list that
# contains all but the first and last elements.
def... | true |
abdeb4ea68da78ea46bb279101b586c2c3fe61ff | Grazziella/Python-for-Dummies | /exercise6_1.py | 429 | 4.625 | 5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Exercise 6.1 Write a while loop that starts at the last character in the string and
# works its way backwards to the first character in the string, printing each letter on
# a separate line, except backwards.
def backwards(string):
index = 0
while index < len(string)... | true |
4bd8769e19547eedba06518f117d0ac875966ae7 | Grazziella/Python-for-Dummies | /exercise10_2.py | 897 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Exercise 10.2 This program counts the distribution of the hour of the day for
# each of the messages. You can pull the hour from the “From” line by finding the
# time string and then splitting that string into parts using the colon character. Once
# you have accumulated ... | true |
818fef536b7f0c12df16c97815bc8ec3c866fff1 | mkcor/GDI-for-PyCon | /drinking_age.py | 756 | 4.25 | 4 | # Script returning whether you are allowed to drink alcohol or not, based on
# age and place, to illustrate conditional statements
age = raw_input('What is your age? ')
age = int(age)
place = raw_input('What is your place? (Capitalize) ')
legal18 = ['AB', 'MB', 'QC']
legal19 = ['BC', 'ON', 'SK']
legal21 = ['MA', 'NY'... | true |
afb515883cd152b0f3d45e0acbcc6ca2551894a8 | Umotrus/python-lab2 | /Ex1.py | 833 | 4.125 | 4 |
# Exercise 1
task_list = []
while True:
print("\n\nTo do manager:\n\n 1.\tinsert a new task\n 2.\tremove a task\n")
print(" 3.\tshow all existing tasks\n 4.\tclose the program\n\n")
cmd = input("Command: ")
if cmd == "1":
# Insert a new task
task = input("New task: ")
tas... | true |
7a92ffdb91f0be82f79f07367b2e79f0fbca621a | Vasudevatirupathinaidu/Python_Harshit-vashisth | /179_c15e1.py | 327 | 4.21875 | 4 | # define generator function
# take one number as argument
# generate a sequence of even numbers from 1 to that number
# ex: 9 --> 2,4,6,8
def even_numbers(n):
for num in range(1,n+1):
if (num%2==0):
yield num
for even_num in even_numbers(9):
print(even_num)
for even_num in even_numbers(9):
print(ev... | true |
98e2523e4b56507b53d3c3f64cd427b390f601c6 | Vasudevatirupathinaidu/Python_Harshit-vashisth | /143_c11e1.py | 381 | 4.125 | 4 | # example
# nums = [1,2,3]
# to_power(3, *nums)
# output
# list --> [1, 8, 27]
# if user didn't pass any args then given a user a message 'hey you didn't pass args'
# else return list
def to_power(num, *args):
if args:
return [i**num for i in args]
else:
return "You didn't pass any args"
n... | true |
761d366c09b3f35a46917d42c16d13087f6193bd | Vasudevatirupathinaidu/Python_Harshit-vashisth | /82_intro_list.py | 500 | 4.46875 | 4 | # data structures
# list ---> this chapter
# ordered collection of items
# you can store anything in lists int, float, string and other data types
numbers = [1, 2, 3, 4, 5]
print(numbers)
print(numbers[1])
print()
words = ['word1', 'word2', 'word3']
print(words)
print(words[1:])
print()
mixed = [1, 2, 3, 4, "five",... | true |
18fcf05ba238186d9ae399ffe119a86b8bb7a825 | Vasudevatirupathinaidu/Python_Harshit-vashisth | /110_more_about_tuples.py | 896 | 4.46875 | 4 | # looping in tuples
# tuple with one element
# tuple without parenthesis
# tuple unpacking
# list inside tuple
# some functions that you can use with tuples
mixed = (1, 2, 3, 4, 0)
# looping in tuples
for i in mixed:
print(i)
print()
# tuple with one element
nums = (2,)
words = ('word1',)
print(type(nums))
prin... | true |
68eaca1696c5a1ac8869ffddc78d56b68f799967 | Vasudevatirupathinaidu/Python_Harshit-vashisth | /114_dict_intro.py | 1,073 | 4.5 | 4 | # dictionaries intro
# Q - Why we use dictionaries?
# A - Because of limitations of lists, lists are not enough to represent real data
# Example
user = ["vasudev", 26, ['tenet', 'inception'], ['awakening', 'fairy tale']]
# this list contains user name, age, fav movies, fav tunes
# you can do this but this is not a goo... | true |
e7a91f0a2212f54a2fe76891a02f45dd057e1573 | sahuvivek083/INFYTQ-LEVEL-2-SOLUTIONS | /problem21_L2.py | 957 | 4.40625 | 4 | """
Tom is working in a shop where he labels items. Each item is labelled with a number between
num1 and num2 (both inclusive).
Since Tom is also a natural mathematician, he likes to observe patterns in numbers.
Tom could observe that some of these label numbers are divisible by other label numbers.
Write a Python... | true |
f3e50dd8085f37eb1125d2b1d013d1c0e308a5fd | SimonXu0811/Python_crash | /classes.py | 931 | 4.21875 | 4 | # A class is like a blueprint for creating objects. An object has properties and methods(functions) associated with it. Almost everything in Python is an object
class User:
# Constructor
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
def gr... | true |
9e1d61a7d89e200a4cab89240ac3f2058887268f | AnonymousAmalgrams/Berkeley-Pacman-Projects | /Berkeley-Pacman-Project-0/priorityQueue.py | 1,573 | 4.125 | 4 | #Priority Queue
import heapq
class PriorityQueue:
def __init__(pq):
pq.heap = []
pq.count = 0
def pop(pq):
# Check if the heap is empty before popping an element
if pq.isEmpty():
print("The heap is empty.")
return False
pq.count -... | true |
ead6c12611f781265a525c09f45f90fd9678f091 | adityabads/cracking-coding-interview | /chapter2/8_loop_detection.py | 1,427 | 4.15625 | 4 | # Loop Detection
# Given a circular linked list, implement an algorithm that returns the node at the
# beginning of the loop.
#
# DEFINITION
# Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so
# as to make a loop in the linked list.
#
# EXAMPLE
# Input: A -> B ->... | true |
b74c20932a29c3e28caa3ce18cb499a3967b4612 | adityabads/cracking-coding-interview | /chapter5/8_draw_line.py | 1,556 | 4.375 | 4 | # Draw Line
# A monochrome screen is stored as a single array of bytes, allowing eight
# consecutive pixels to be stored in one byte. The screen has width w,
# where w is divisible by 8 (that is, no byte will be split across rows).
# The height of the screen, of course, can be derived from the length of the
# array and... | true |
e58b65f0e51d929b75cca9d87e990bfa21622ef5 | 4ratkm88/COM404 | /1-Basics/5-Function/8-function-calls/bot.py | 1,133 | 4.40625 | 4 | #1) Display in a Box – display the word in an ascii art box
def ascii(asciiword):
print("#####################")
print("# #")
print("# #")
print("# " + word + " #")
print("# #")
print("# #")
print("# ... | true |
9258d7fc28ee32985fd73019d1e6952cdd5edd88 | baharaysel/python-pythonCrashCourseBookStudy | /working_with_lists/dimensions.py | 1,206 | 4.375 | 4 |
##Defining a Tuple ()
#tuples value doesnt change
dimensions = (200, 50)
print(dimensions[0])
#200
print(dimensions[1])
#50
# dimensions[0] = 20 ## we cant change dimensions/tuple it gives error
###Looping Through All Values in a Tuple
dimensions = (200,50)
for dimension in dimensions:
print(dimensio... | true |
91fe1b8f64858ec255702a98e8d7955f6bc55917 | wildlingjill/codingdojowork | /Python/Python_OOP/OOP work/bike.py | 825 | 4.34375 | 4 | class Bike(object):
def __init__(self, price, max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
# display price, max speed and total miles
def displayInfo(self):
print self.price, self.max_speed, self.miles
# display "riding" and increase miles by 10
def ride(self):
self.miles +=... | true |
97bf493dc0d69aead48bbb06797d22df294e36af | NSYue/cpy5python | /practical03/q7_display_matrix.py | 424 | 4.40625 | 4 | # Filename: q7_display_matrix.py
# Author: Nie Shuyue
# Created: 20130221
# Modified: 20130221
# Description: Program to display a n by n matrix
# with random element of 0 or 1
# Function
def print_matrix(n):
import random
for i in range(0, n):
for j in range(0, n):
print(random.randint(0,1... | true |
bef4cb4ec0ed43df16080920746692a341ab61fa | NSYue/cpy5python | /practical01/q4_sum_digits.py | 516 | 4.21875 | 4 | # Filename:q4_sum_digits.py
# Author: Nie Shuyue
# Date: 20130122
# Modified: 20130122
# Description: Program to get an integer between 0 and 1000
# and adds all the digits in the integer.
#main
#prompt and get the integer
integer = int(input("Enter the integer between 0 and 1000: "))
#get the sum of the last digit
... | true |
d5613dc4df322b5616137f1ef2ce62b5115ab2a1 | NSYue/cpy5python | /practical02/q08_top2_scores.py | 898 | 4.1875 | 4 | # Filename: q08_top2_scores.py
# Author: Nie Shuyue
# Created: 20130204
# Modified: 20130205
# Description: Program to get the top 2 scores of a group of students
# main
# prompt and get the number of students
num = int(input("Enter the number of students: "))
# define top, second score and the names
top = -10000
se... | true |
09b1b06da84eda85e5c3e6ff404513a7913aafeb | NSYue/cpy5python | /practical02/q02_triangle.py | 504 | 4.40625 | 4 | # Filename:q02_triangle.py
# Author: Nie Shuyue
# Date: 20130129
# Modified: 20130129
# Description: Program to identify a triangle
# and calculate its perimeter.
# main
# Prompt and get the length of each
# side of the triangle
a = int(input("Enter side 1:"))
b = int(input("Enter side 2:"))
c = int(input("Enter side... | true |
8c00568cbebfe8b2af4ac93318214e79e7114a5c | mayababuji/MyCodefights | /reverseParentheses.py | 920 | 4.25 | 4 | #!/usr/bin/env python
#-*- coding : utf-8 -*-
'''
You have a string s that consists of English letters, punctuation marks, whitespace characters, and brackets. It is guaranteed that the parentheses in s form a regular bracket sequence.
Your task is to reverse the strings contained in each pair of matching parentheses,... | true |
b54d6a6018b9ad367195c0e90de0d13010a898ad | macjabeth/Lambda-Sorting | /src/iterative_sorting/iterative_sorting.py | 1,918 | 4.21875 | 4 | # TO-DO: Complete the selection_sort() function below
# def selection_sort(arr):
# count = len(arr)
# # loop through n-1 elements
# for i in range(count-1):
# cur_index = i
# smallest_index = cur_index
# # TO-DO: find next smallest element
# # (hint, can do in 3 loc)
# ... | true |
64a1ce9f6a308e0a4b2bdaa30ea59e53f140ae9c | emanuel-mazilu/python-projects | /calculator/calculator.py | 1,567 | 4.375 | 4 | import tkinter as tk
# the display string
expression = ""
# TODO
# Division by 0
# invalid expressions
def onclick(sign):
global expression
# Evaluate the expression on the display ex: 2+3/2-6*5
if sign == "=":
text_input.set(eval(expression))
expression = ""
# clear the memory and t... | true |
d5a8976e67ff84c03bc5df83b65f5d2003e61692 | MattR-GitHub/Python-1 | /L2 Check_string.py | 1,637 | 4.28125 | 4 | # check_string.py
countmax = 5
count = 0
while count != countmax:
count+=1
uin = input(" Enter an uppercase word followed by a period. Or enter " "end" " to exit. ")
upperltrs = uin.upper()
if uin.endswith("end"):
print("Exiting")
count = 5
#Upper Letters
elif uin.isuppe... | true |
cc7306c01119d237d3e6df1c0d8cbe9afd856c59 | anushamurthy/CodeInPlace | /Assignment2/khansole_academy.py | 1,552 | 4.40625 | 4 | """
File: khansole_academy.py
-------------------------
Add your comments here.
"""
import random
RIGHT_SCORE = 3
RANDOM_MIN = 10
RANDOM_MAX = 99
def main():
test()
"""The function test begins with your score being 0. The users are continued to be tested until
their score matches the right score (which is 3 he... | true |
58271b720700c5f61ef0bd7dd2bdd85865c0ac5f | esadakcam/assignment2 | /hash_passwd.py | 1,298 | 4.78125 | 5 | '''The below is a simple example of how you would use "hashing" to
compare passwords without having to save the password - you would-
save the "hash" of the password instead.
Written for the class BLG101E assignment 2.'''
'''We need to import a function for generating hashes from byte
strings.'''
from hashlib i... | true |
e5a46864dd82d6d76a58fa17c36dbbf29283edd1 | Adroit-Abhik/CipherSchools_Assignment | /majorityElement.py | 1,300 | 4.125 | 4 | '''
Write a function which takes an array and prints the majority element (if it exists), otherwise prints “No Majority Element”.
A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element).
'''
# Naive approach
def find_majority_element(ar... | true |
b3197fd59fdaab5e4bac8663a3920fcd0686628c | anschy/Hacktober-Challenges | /Simple_Caluclator/simpleCalculator.py | 1,480 | 4.375 | 4 | # Python program of a simple calculator
# This function performs addition of two number's
def add(num_one, num_two):
return num_one + num_two
# This function performs subtraction of two number's
def subtract(num_one, num_two):
return num_one - num_two
# This function performs multiplication of two number's
d... | true |
4491e1510e6ad57212fe327be2b5fd2225cb4d31 | ICS3U-Programming-LiamC/Unit6-01-Python | /random_array.py | 1,153 | 4.28125 | 4 | #!/usr/bin/env python3
# Created by: Liam Csiffary
# Created on: June 6, 2021
# This program generates 10 random numbers then
# it calculates the average of them
# import the necessary modules
import random
import const
# greet the user
def greet():
print("Welcome! This program generates 10 random numbers and w... | true |
bcad13d1e474c82bc26f31f7c6b9bd2979ff3044 | clancybawdenjcu/cp1404practicals | /prac_01/shop_calculator.py | 466 | 4.125 | 4 | total_price = 0
number_of_items = int(input("Number of items: "))
while number_of_items < 0:
print("Invalid number of items!")
number_of_items = int(input("Number of items: "))
for i in range(1, number_of_items + 1):
price = float(input(f"Price of item {i}: "))
total_price += price
if total_price > 100... | true |
de7d2d4ce3881419864b5aa119e01261e0f43159 | zweed4u/Python-Concepts | /Design patterns/creational_patterns/factory.py | 843 | 4.625 | 5 | """
Factory Pattern example - creational design pattern
Scenario: Pet shop - orginally sold dogs, now sell cats as well
"""
class Cat():
def __init__(self, name):
self.name = name
def speak(self):
return "Meow"
class Dog():
def __init__(self, name):
self.name = name
def speak(self):
return "Bark"
class ... | true |
a323a530af7ab84312d682db75191f80c75ef3da | zweed4u/Python-Concepts | /Map Filter Reduce functions/map_function.py | 1,067 | 4.5625 | 5 | """
Map function
"""
import math
def area(radius):
"""
Area of circle given radius
"""
return math.pi*(radius**2)
# Compute areas of many circles given all of their radius'
radii = [2, 5, 7.1, .3, 10]
print(radii)
# Direct method
areas = []
for radius in radii:
areas.append(area(radius))
print(areas)
# Map met... | true |
b738330a15670e15e37e80adde72a00e290b573a | haominhe/Undergraduate | /CIS211 Computer Science II/Projects/p4/flipper.py | 1,727 | 4.75 | 5 | """CIS 211 Winter 2015
Haomin He
Project 4: Building GUIs with Tk
3. Write a program that will display three playing card images and a button
labeled "flip". Each time the user clicks the button one of the card images
should be updated.
When the window is first opened the user should see the backs ... | true |
4f49a3f6fb7ecb9ca302f0f6db2ff7dedc870d4e | Severian999/Homework-7 | /DonGass_hw7_task2.py | 1,449 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 20 21:36:26 2017
@author: Don Gass
"""
word = 'onomatopoeia'
def hangman(num_guesses, word):
"""
Controls the logic of the hangman game.
Handles the guesses and determines whether the user wins or loses.
Calls hidden_word(word, guesses) to g... | true |
c4281cd1d3bad824e8199801179681d3228c5037 | shaneleblanc/codefights | /permutationCypher.py | 1,149 | 4.1875 | 4 | # You found your very first laptop in the attic, and decided to give in to nostalgia and turn it on. The laptop turned out to be password protected, but you know how to crack it: you have always used the same password, but encrypt it using permutation ciphers with various keys. The key to the cipher used to protect you... | true |
345b9214b6288bdb379a1bc0f94fb49e4fd4d6b5 | mghamdi86/Python-Lesson | /Lesson1.py | 401 | 4.3125 | 4 | Variables will teach us how to store values for later use:
x = 5
Loops will allow us to do some math on every value in a list:
print(item) for item in ['milk', 'eggs', 'cheese']
Conditionals will let us run code if some test is true:
"Our test is true!" if 1 < 2 else "Our test is false!"
Math Operators allow us to perf... | true |
1ba71e3e3f8ab2cc4584c20924d6456da5854b42 | michberr/code-challenges | /spiral.py | 2,215 | 4.65625 | 5 | """Print points in matrix, going in a spiral.
Give a square matrix, like this 4 x 4 matrix, it's composed
of points that are x, y points (top-left is 0, 0):
0,0 0,1 0,2 0,3
1,0 1,1 1,2 1,3
2,0 2,1 2,2 2,3
3,0 3,1 3,2 3,3
Starting at the top left, print the x and y coordinates of each
poin... | true |
186e9a29e00e43262654e667e1029e457eeb655a | michberr/code-challenges | /sum_recursive.py | 370 | 4.15625 | 4 | def sum_list(nums):
"""Sum the numbers in a list with recursion
>>> sum_list([])
0
>>> sum_list([1])
1
>>> sum_list([1, 2, 3])
6
"""
if not nums:
return 0
return nums[-1] + sum_list(nums[:-1])
if __name__ == "__main__":
import doctest
if doctest.testmod().fa... | true |
fd3d0e66e5d3b98b2ee796ae7e3e8c46d3919a66 | thepros847/python_programiing | /lessons/#Python_program_to_Find_day.py | 392 | 4.25 | 4 | # Python program to find day of the week for a given date
while True:
import datetime
import calendar
def findDay(date):
born = datetime.datetime.strptime(date, '%d %m %Y').weekday()
return (calendar.day_name[born])
# Driver program
date = '04 07 1962'
print(findDay(date))
prin... | true |
64e4437e992ab02b351d6ce1fd0968037e369cbc | richa067/Python-Basics | /Dictionaries.py | 2,579 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 24 22:18:33 2020
@author: Richa Arora
"""
#Dictionaries
# Add code to the above program to figure out who has the most messages in the file. After all the data has beenread and the dictionary has been created, look through the dictionary using a maximum
# lo... | true |
2f50199874eb8936c327b02c6a6ea27ecefbfb89 | kaiserkonok/python-data-structures-for-beginner | /linked_list.py | 1,416 | 4.1875 | 4 | class Node:
def __init__(self, item, next=None):
self.data = item
self.next = next
class LinkedList:
def __init__(self, head):
self.head = head
def prepend(self, item):
new_node = Node(item, self.head)
self.head = new_node
def append(self, item):
new_n... | true |
9209b667e5a198e3b32b860c4eb05bc14c1281b4 | HGWright/QA_Python | /programs/grade_calculator.py | 617 | 4.25 | 4 | print("Welcome to the Grade Calculator")
maths_mark = int(input("Please enter your Maths mark: "))
chemistry_mark = int(input("Please enter your Chemistry mark: "))
physics_mark = int(input("Please enter your Physics mark: "))
total_mark = (maths_mark + chemistry_mark + physics_mark)/3
print(f"Your overall percentag... | true |
4113c239c2cb18566b1b0d7b29114fbc49ac1fcb | Pramod123-mittal/python-prgs | /guessing_problem.py | 546 | 4.125 | 4 | # guessing problem
number = 18
no_of_guessses = 1
print('you have 9 guesses to win the game')
while no_of_guessses<=9:
guess_number = int(input('enter a number'))
if guess_number > 18:
print('greater then required')
elif guess_number < 18:
print('lesser then required')
else:
prin... | true |
15cfd57c7a6a58f6fb90e93b23056c33399228dd | BennettBierman/recruiting-exercises | /inventory-allocator/Warehouse.py | 1,317 | 4.40625 | 4 | class Warehouse:
"""
Warehouse encapsulates a string and a dictionary of strings and integers.
"""
def __init__(self, name, inventory):
"""
Construct a new 'Warehouse' object.
:param name: string representing name of Warehouse
:param inventory: dictionary representing na... | true |
5d85bb6b4e6901944cf11e502d10a1ca450f9a8b | ashish8796/python | /day-5/list_methods.py | 886 | 4.5 | 4 | #Useful Functions for Lists
len() #returns how many elements are in a list.
max() #returns the greatest element of the list.
#The max function is undefined for lists that contain elements from different, incomparable types.
min() #returns the smallest element in a list.
sorted() #returns a copy of a list in order from ... | true |
6e990727edcfb9781d3741a19e798aa443fa7405 | ashish8796/python | /day-11/for_through_dictionaries.py | 878 | 4.65625 | 5 | #Iterating Through Dictionaries with For Loops
'''
When you iterate through a dictionary using a for loop, doing it the normal way (for n in some_dict) will only give you access to the keys in the dictionary
'''
cast = {
"Jerry Seinfeld": "Jerry Seinfeld",
"Julia Louis-Dreyfus": "Elaine Benes",
... | true |
a3fa02ef6abf8fedd48ff9f01c5da79ade01265f | ashish8796/python | /day-17/scripting.py | 426 | 4.375 | 4 | #Scripting With Raw Input
#input, the built-in function, which takes in an optional string argument form user.
name = input("Enter your name: ")
print("Hello there, {}!".format(name.title()))
num = int(input("Enter an integer"))#change string into integer
print("hello" * num)
result = eval(input("Enter an expression... | true |
d4c3c7cfd283136567979e0fdf1c0dc495889778 | ashish8796/python | /day-6/dictionaries_identity_operators.py | 1,587 | 4.59375 | 5 | #Dictionaries
#A dictionary is a mutable data type that stores mappings of unique keys to values.
elements = {"hydrogen": 1, "helium": 2, "carbon": 6}
print(elements["helium"]) # print the value mapped to "helium"
#2
elements["lithium"] = 3 # insert "lithium" with a value of 3 into the dictionary
print(elements)
#{... | true |
8a45f66a39fee8556fa1aa8fc27170e33034cbdb | alexisbird/BC2repo | /number_guess.py | 2,952 | 4.625 | 5 | """Have the program generate a random int between 1 and 100. Keep it a secret. Ask the user to guess. Tell them if the secret number is higher or lower than their guess. Let them guess until they get it right.
Advanced:
Limit the number of guesses to 5."""
# ***NOTE TO SELF*** if you have the time and desire:
# - Ad... | true |
0215cb209db874303eafe410171c442c7d85b0db | popnfreshspk/python_exercises | /connect_four/pt1_piece_and_board.py | 821 | 4.40625 | 4 | # CONNECT 4 Part: 1
#
# This exercise should expand on the TIC-TAC-TOE learning and let you explor
# implementing programs with classes.
#
# The output of your game board should look like the following:
#
# 0 1 2 3 4 5 6
# |_|_|_|_|_|_|_|
# |_|_|_|_|_|_|_|
# |_|_|_|_|_|_|_|
# |_|_|_|_|_|_|_|
# |_|_|_|_|_|_|_|
# |●|_|_... | true |
f2642ca47db5cbe70990d96919108745009ddc90 | kwy518/Udemy | /BMI.py | 221 | 4.28125 | 4 | weight = input('Please enter your weight(kg): ')
height = input('Please enter your height(cm): ')
height = float(height)
weight = float(weight)
height /= 100
BMI = weight / (height * height)
print('Your BMI is: ', BMI) | true |
6bc1c39d0bfd966c86046b9b2b34af90fc49a7b8 | ocanava/number_guessing_game | /app.py | 1,401 | 4.15625 | 4 | """
Python Web Development Techdegree
Project 1 - Number Guessing Game
--------------------------------
import random
number = random.randint(1, 10)
def start_game():
print("Welcome to the Number Guessing Game!!")
input("Press ENTER to continue...")
Tries = 1
while True:
try: ... | true |
23b620af391c84e21d5ed4b5a2617343346ff020 | kumarmj/test | /main.py | 1,002 | 4.1875 | 4 | # Chapter 1: The role of algorithms in Computing
# In this chapter, we will answer these questions
# What are algorithms?
# An algorithm is thus a sequence of computational steps that transform the input into the output
# e.g. let's define sorting problem
# Input: A sequence of n numbers a1, a2,...an.
# Output: Produ... | true |
7346d76a53843db430d118cd4981d0611e0bb3a4 | denisecase/chapstack | /scripts/04-functions.py | 2,616 | 4.125 | 4 | """04-functions.py
This script provides practice working with functions.
It's based on the script 3 - we use functions to make our code more
reusable and easier to maintain.
We add some fun css effects (zoom when we hover).
See index.html - in this example, our html has additional elements
See styles - we add a zo... | true |
1d297e99053f2596a3e59364129cedd8a5c35f4d | cnDelbert/Karan-Projects-Python | /Text/Count_Words_in_a_String.py | 826 | 4.5 | 4 | # coding: utf-8
__author__ = 'Delbert'
"""
Count Words in a String - Counts the number of individual words in a string. For added complexity read these strings in from a text file and generate a summary.
"""
def count_by_input(inp):
return len(inp.strip().split())
def count_by_file(inp):
f = open(inp, "r").... | true |
b0d3208e3e8599e913dbda7124657ec67e8129e5 | philburling/UndergraduateElectiveModules | /Introduction to Programming -with Python/numbersorter.py | 975 | 4.4375 | 4 | # Filename: numbersorter.py
# Title: Number Sorter
# Function: Sorts 10 numbers entered by the user into descending numerical order
# starting the highest first and ending with the lowest. It then prints the new
# order in a list for the user to see.
# Author: Philip Burling
# Date: 28/04/07
# First the program creat... | true |
f19e136c3552317f9445bbeaaff2d407c7ff560f | philburling/UndergraduateElectiveModules | /Introduction to Programming -with Python/OrangutanDave.py | 921 | 4.40625 | 4 | # Filename: OrangutanDave.py
# Title: Dave the Orangutan
# Function: Creates an object (an orangutan called Dave) and gives it the
# co-ordinates (2,2). The program then displays how far (in a straight line)
# 'Dave' is from the point (5,3) where his favourite food is.
# Author: Philip Burling
# Date: 28/04/07
# This ... | true |
ef4893b9a6ebacda80a48219f20fcb2df250941e | malekmahjoub635/holbertonschool-higher_level_programming-2 | /0x07-python-test_driven_development/4-print_square.py | 685 | 4.46875 | 4 | #!/usr/bin/python3
"""
Module to print a square
"""
def print_square(size):
"""
a function that prints a square with the character #.
Args:
size(int): size of the square
Raises:
TypeError: if size is not integer
ValueError: if size less than 0
Returns:
a printed squ... | true |
30102d891dde0e518c406b0d0341bfc061ef3298 | malekmahjoub635/holbertonschool-higher_level_programming-2 | /0x0B-python-input_output/1-write_file.py | 363 | 4.34375 | 4 | #!/usr/bin/python3
""" write file Module """
def write_file(filename="", text=""):
"""
write file function
Args:
filename(string): the given file name
text(string): the text
Returns:
number of characters written.
"""
with open(filename, 'w', encoding="UTF8") as f:
... | true |
c068b8ca7d7bb252bbdd37720db7b9ebeff4f60c | ananya-byte/Code-for-HacktoberFest-2021 | /Intermediate/Python/second_highest.py | 588 | 4.21875 | 4 | def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than ... | true |
b838bb47b7f9a0f56fe6dadc188a0ad8a9446f73 | CivicTesla/Teacher-Stone-s-Data-Structure-Lesson | /Notes/01-Basic/src/Fraction.py | 1,484 | 4.34375 | 4 | # 1. how to define a class
# 2. show function definition in class and out of class
# 3. show main function
# 4. the meaning of self
# When defining an instance method,
# the first parameter of the method should always be self
# (name convension from the python community).
# The self in python represents ... | true |
0f84bb21c8148a79a337527f89d0afb60953a72b | ellojess/coding-interview-practice | /LeetCode/two-sums.py | 1,066 | 4.125 | 4 | '''
Prompt:
Given an array of integers, return indices of the two
numbers such that they add up to a specific target.
You may assume that each input would have
exactly one solution, and you may not use the same
element twice.
Summary:
Find the indices of two numbers that add up to a specific target.
Examples: ... | true |
d2ba77f5316776a5acee116a7931a7d5aae92bbf | codesbyHaizhen/show-circle-and-rectangle-with-self-defined-modul | /ModulGeometry/circle.py | 860 | 4.21875 | 4 | # Create a class Circle
class Circle(object):
# Constructor
def __init__(self, radius=3, color='red'):
self.radius = radius
self.color = color
def add_radius(self, r):
self.radius = self.radius + r
return(self.radius)
def drawCircle(self):
# this m... | true |
98cc1941b3e421126a3a7b1a77ac366133761591 | andreiturcanu/Data-Structures-Algorithms-Udemy-Course | /Selection Sort Algorithm Implementation - Project.py | 631 | 4.25 | 4 | #Write Selection Sort Algorithm; Ascending Order
def selectionsort (array):
for i in range(len(array) - 1):
#identify index to be equal to i
index = i
#1 through length of array -1
for j in range (i+1, len(array),1):
if array [j] < array [index]:
#we find smallest item in that given array
... | true |
72269a40897df9c8e829815aa805dd57c923d04b | andreiturcanu/Data-Structures-Algorithms-Udemy-Course | /Quick Sort Algorithm Implementation - Project.py | 1,108 | 4.15625 | 4 | #Write Quick Sort Algorithm; Ascending Order
def quicksort (array, low, high):
if low >= high:
return
#partition array
#select middle item in array
piv_index = (low+high)//2
#sort
temp1 = array[piv_index]
temp2 = array[high]
array[piv_index]=temp2
array[high]=temp1
i = low
#make sure... | true |
3a9c797ad3aeb48b52c81298eae76973f2211fd9 | drvinceknight/rsd | /assets/code/src/is_prime.py | 363 | 4.25 | 4 | """
Function to check if a number is prime.
"""
def check(N):
"""
Test if N is prime.
Inputs:
- N: an integer
Output:
- A boolean
"""
potential_factor = 1
while potential_factor < N / 2:
potential_factor = potential_factor + 1
if (N % potential_factor == 0)... | true |
662fb93b5d859097b4bf55c34343989c9ea469fa | TudorMaiereanu/Algorithms-DataStructures | /mergesort.py | 744 | 4.3125 | 4 | # Mergesort algorithm in Python
import sys
# function to be called on a list
def mergesort(unsortedList):
mergesortIndex(unsortedList, 0, len(A)-1)
def mergesortIndex(unsortedList, first, last):
if first < last:
middle = (first + last)//2
mergesortIndex(unsortedList, first, middle)
mergesortIndex... | true |
39a2bd9408657fbf40b7a20fa5d0c1b089cdeea9 | jesseulundo/basic_python_coding | /nested_data_structure.py | 1,711 | 4.5 | 4 | """
Create a list nested_list consisting of five empty lists
"""
nested_list = [[], [], [], [], []]
print(nested_list)
print("Nested_list of length 5 whose items are themselves lists consisting of 3 zeros")
print("===============================================================================")
n_nested_list... | true |
0c2cfc4554e2444d2bee517d03be6d0d4e9be96e | axtell5000/working-with-python | /basics-1.py | 873 | 4.125 | 4 | # Fundamental Data types
int
float
bool
str
list
tuple
set
dict
# Classes - custom data type
# Specialized data types - external packages
None
# int and float
print(type(3 + 3))
print(type(2 * 8))
print(type(2 / 8))
print(2 ** 2) # 4
print(4 // 2) # rounds down to integer
print(6 % 4) # modular remainder
# Mat... | true |
ac1f79328c2c79bc5cab0ebc059821acb7817321 | guillempalou/scikit-cv | /skcv/multiview/util/synthetic_point_cloud.py | 1,926 | 4.15625 | 4 | import numpy as np
def random_sphere(N, radius, center=None):
"""
Generates N points randomly distributed on a sphere
Parameters
----------
N: int
Number of points to generate
radius: float
Radius of the sphere
center: numyp array, optional
center of the sphere. (0,0,0) defau... | true |
00882283a9a01dfdbbcc7961ce471ae1046fbc35 | Hol7/100_Days_Challenge | /Day1.py | 664 | 4.25 | 4 | print("Day 1 - Python Print Function ")
print("The function is declared like this:")
print("print('what to print')")
# Debug and fix Exercise
print("Day 1 - String Manipulation")
print("String Concatenation is done with the" "+" "sign.")
print("e.g print('Hello'+'world')")
print("New lines can be created with a back... | true |
9df8f7a84cb750453653d64b6c6b8c48b6cb793a | naveenshandilya30/Common-Modules-in-Python | /Assignment_8.py | 883 | 4.21875 | 4 | #Question 1
"""A time tuple is the usage of a tuple (list of ordered items/functions) for the ordering and notation of time."""
#Question 2
import datetime,time
print (time.strftime("%I:%M:%S"))
#Question 3
import datetime,time
print ("Month:",time.strftime("%B"))
#Question 4
import datetime,time
print ("Day:"... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.