blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3b4ac26a260e4a0118d90637899ee3755c975a97 | aburmd/leetcode | /Regular_Practice/easy/17_371_Sum_of_Two_Integers.py | 1,883 | 4.125 | 4 | """
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = -2, b = 3
Output: 1
"""
class Solution:
def getPositivesum(self,a,b):
while b!=0:
bitcommon=a&b #Example: 4(100),5(101) bit commo... | true |
9eba98a92942adeb3cffc9bab950d03c384e56c0 | MarthaSamuel/simplecodes | /OOPexpt.py | 1,142 | 4.46875 | 4 | #experimenting with Object Orienting Programming
#defining our first class called apple
class Apple:
pass
#we define 2 attributes of the class and initialize as strings
class Apple:
color = ''
flavor = ''
# we define an instance of the apple class(object)
jonagold = Apple()
# attributes of the object
jonago... | true |
4ac5b4a4d773a73aa6768d57afd9e44a3482cb86 | AllenWang314/python-test-scaffolding | /interview.py | 275 | 4.3125 | 4 |
""" returns square of a number x
raises exception if x is not of type int or float """
def square(x):
if type(x) != int and type(x) != float:
raise Exception("Invalid input type: type must be int or float")
print(f"the square is {x**2}")
return x**2
| true |
84ed875a37f483f8acfa592c24bd6c9dd5b4cbf7 | RuchirChawdhry/Python | /all_capital.py | 1,163 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# script by Ruchir Chawdhry
# released under MIT License
# github.com/RuchirChawdhry/Python
# ruchirchawdhry.com
# linkedin.com/in/RuchirChawdhry
"""
Write a program that accept a sequence of lines* and prints the lines
as input and prints the lines after making all the ... | true |
656ae9779498767407dfbec47689c6aaf15907d3 | RuchirChawdhry/Python | /circle_class.py | 984 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# script by Ruchir Chawdhry
# released under MIT License
# github.com/RuchirChawdhry/Python
# ruchirchawdhry.com
# linkedin.com/in/RuchirChawdhry
"""
Define a class 'Circle' which can be constructed by either radius or diameter.
The 'Circle' class has a method which can ... | true |
f3c2abbab1697397006113c42c1fc03568d17719 | Sanchi02/Dojo | /LeetCode/Strings/ValidPalindrome.py | 742 | 4.125 | 4 | # Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
# Note: For the purpose of this problem, we define empty string as valid palindrome.
# Example 1:
# Input: "A man, a plan, a canal: Panama"
# Output: true
# Example 2:
# Input: "race a car"
# Output: fals... | true |
768e42c29a97bcf3c2d6ec5992d33b9458fb56e8 | ujjwalshiva/pythonprograms | /Check whether Alphabet is a Vowel.py | 256 | 4.40625 | 4 | # Check if the alphabet is vowel/consonant
letter=input("Enter any letter from a-z (small-caps): ")
if letter == 'a' or letter =='e' or letter =='i' or letter =='o' or letter =='u':
print(letter, "is a Vowel")
else:
print(letter, "is a Consonant")
| true |
16e13a2f6042e3deae198df89a2956f6648edfb4 | davidwang0829/Python | /小甲鱼课后习题/34/习题2.py | 1,464 | 4.15625 | 4 | # 使用try…except语句改写第25课习题3
print('''--- Welcome to the address book program ---
--- 1:Query contact information ---
--- 2:Insert a new contact ---
--- 3:Delete existing contacts ---
--- 4:Exit the address book program ---''')
dic = dict()
while 1:
IC = input('\nPlease enter the relevant instruction code:')
if I... | true |
be23213891eb1945990bd61cec32c986a29fba49 | matvelius/Selection-Sort | /selection_sort.py | 1,825 | 4.3125 | 4 | # The algorithm divides the input list into two parts:
# the sublist of items already sorted, which is built up from left
# to right at the front (left) of the list, and the sublist of items
# remaining to be sorted that occupy the rest of the list.
# Initially, the sorted sublist is empty and the unsorted sublist ... | true |
52ae48b48dd9f7c9a60970dab786b3a02a7f76b0 | abhi15sep/Python-Course | /introduction/loops/Loop_Example/exercise.py | 637 | 4.125 | 4 | # Use a for loop to add up every odd number from 10 to 20 (inclusive) and store the result in the variable x.
# Add up all odd numbers between 10 and 20
# Store the result in x:
x = 0
# YOUR CODE GOES HERE:
#Solution Using a Conditional
for n in range(10, 21): #remember range is exclusive, so we have to go up to 21... | true |
684a6a2571adb3bb17ea97230600d5ae76ed6570 | abhi15sep/Python-Course | /collection/Dictionaries/examples/Dictionary.py | 1,581 | 4.5625 | 5 |
"""
A dictionary is very similar to a set, except instead of storing single values like numbers or strings, it associates those values to something else. This is normally a key-value pair.
For example, we could create a dictionary that associates each of our friends' names with a number describing how long ago we la... | true |
52432f6633d264b1f53d9c6e8a9bb834e4532d7b | abhi15sep/Python-Course | /introduction/example/lucky.py | 502 | 4.15625 | 4 | #At the top of the file is some starter code that randomly picks a number between 1 and 10, and saves it to a variable called choice. Don't touch those lines! (please).
#Your job is to write a simple conditional to check if choice is 7, print out "lucky". Otherwise, print out "unlucky".
# NO TOUCHING PLEASE-------... | true |
2eab7e313a1104ca9384d3c73f8e3d3b10ff4491 | abhi15sep/Python-Course | /Functions/examples/exercise4.py | 600 | 4.4375 | 4 | #Implement a function yell which accepts a single string argument. It should return(not print) an uppercased version of the string with an exclamation point aded at the end. For example:
# yell("go away") # "GO AWAY!"
#yell("leave me alone") # "LEAVE ME ALONE!"
#You do not need to call the function to pass the ... | true |
b8c247b00db447a205409067aad84ea853ad2040 | abhi15sep/Python-Course | /introduction/example/positive_negative_check.py | 970 | 4.46875 | 4 | # In this exercise x and y are two random variables. The code at the top of the file randomly assigns them.
#1) If both are positive numbers, print "both positive".
#2) If both are negative, print "both negative".
#3) Otherwise, tell us which one is positive and which one is negative, e.g. "x is positive and y is ne... | true |
9d18ab098eb2d59fbba6595cbc157dd3b629d87a | yogabull/LPTHW | /ex14.py | 789 | 4.15625 | 4 | # Exercise 14: Prompting and Passing
from sys import argv
script, user_name, last_name, Day = argv
#prompt is a string. Changing the variable here, changes every instance when it is called.
prompt = 'ENTER: '
#the 'f' inside the parenthesis is a function or method to place the argv arguements into the sentence.
prin... | true |
ef8d22e8ab44d0a3cad96db2c94779ab98c2d11c | Catrinici/Python_OOP | /bike_assignement.py | 1,177 | 4.28125 | 4 | class Bike:
def __init__(self, price, max_speed, miles):
self.price = price
self.max_speed = max_speed
self.miles = abs(0)
def ride(self):
print("Riding!")
self.miles += 10
print(f"Total miles : {self.miles}")
return self
def reverse(self):
pr... | true |
459bbf3c436621c0b769c07740b44261bb84ff3d | Abeilles14/Java_exercises | /6.32_IfThenElseChallenge/IfThenElseChallenge.py | 274 | 4.15625 | 4 | #isabelle andre
#14-07/18
#if challenge
name = input("Enter your name: ")
age = int(input("Enter your age: "))
#if age >= 18 and age <= 30:
if 18 >= age <= 30:
print("Welcome to the 18-30 holiday, {}".format(name))
else:
print ("You are not eligible to enter the holiday") | true |
8d69bd1f68bd1dfe19adb1909d0ed541fdef7b7c | mmsamiei/Learning | /python/dictionary_examples/create_grade_dictionary.py | 532 | 4.1875 | 4 | grades = {}
while(True):
print("Enter a name: (blank to quit):")
name = raw_input()
if name == '':
break
if name in grades:
print(' {grade} is the grade of {name} ').format(grade=grades[name],name=name)
else:
print("we have not the grade of {name}").format(name=name)
... | true |
6a07533146042655f2780ff329ecaff3089cedd6 | ziyuanrao11/Leetcode | /Sum of 1d array.py | 2,483 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 14:41:32 2021
@author: rao
"""
'''Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
Example 1:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is o... | true |
eb5b36fd683ead2eb4205f18ab6897eb76327aa0 | pandiarajan-src/PyWorks | /educative_examples/benchmarking_ex3.py | 1,192 | 4.15625 | 4 | # Benchmarking
# Create a Timing Context Manager
"""
Some programmers like to use context managers to time small pieces of code. So let’s create our own timer context manager class!
"""
import random
import time
class MyTimer():
def __init__(self):
self.start = time.time()
def __enter__(self):
... | true |
e86df3f56dc9ca95f6a2018b41e19aa3fc7f8e5b | pandiarajan-src/PyWorks | /Learn/converters_sample.py | 1,108 | 4.28125 | 4 | '''This example script shows how to convert different units - excercise for variables'''
MILES_TO_KILO_CONST = 1.609344
RESOLUTION_CONST = 2
def miles_to_kilometers(miles):
"""Convert given input miles to kilometers"""
return round((miles * MILES_TO_KILO_CONST), RESOLUTION_CONST)
def kilometers_to_miles(kilo... | true |
58ef0063ab66182a98cfeb82a2173be41952ac75 | chigginss/guessing-game | /game.py | 1,870 | 4.21875 | 4 | """A number-guessing game."""
from random import randint
def guessing_game():
# pick random number
repeat = "Y"
scores = []
#Greet player and get the player name rawinput
print("Hello!")
name = raw_input("What is your name? ")
while repeat == "Y":
start = int(raw_input("Choose a star... | true |
fd6d45ba6fecb3605e025a74ed5f56abc63e6625 | slayer6409/foobar | /unsolved/solar_doomsday.py | 1,692 | 4.4375 | 4 | """
Solar Doomsday
==============
Who would've guessed? Doomsday devices take a LOT of power. Commander Lambda wants to supplement the LAMBCHOP's quantum antimatter reactor core with solar arrays, and she's tasked you with setting up the solar panels.
Due to the nature of the space station's outer paneling, all of it... | true |
e77a9e0ab70fbb5916f12e1b864f5f5b7211ba48 | gauravkunwar/PyPractice | /PyExamples/factorials.py | 248 | 4.3125 | 4 | num=int(input("Enter the value :"))
if(num<0):
print("Cannot be factorized:")
elif (num==0):
print("the factorial of 0 is 1:")
else :
for i in range(0 to num+1):
factorial=factorial*i
print"the factorial of a given number is:",factorial
| true |
48d1eeffbf97cdf144e0f8f1fb6305da1141b5be | gauravkunwar/PyPractice | /PyExamples/largestnum.py | 352 | 4.3125 | 4 |
num1=float(input("Enter the first num:"))
num2=float(input("Enter the second num:"))
num3=float(input("Enter the third num:"))
if:
(num1>num2) and(num1>num3)
print("largest=num1")
elif:
(num2>num3) and(num2>num1)
print("largest=num2")
else
print("largest=num3")
#print("The largest number among,"num... | true |
f1ac7ce434862b7b26f5225810e65f539ec38838 | Nike0601/Python-programs | /km_cm_m.py | 322 | 4.3125 | 4 | print "Enter distance/length in km: "
l_km=float(input())
print "Do you want to convert to cm/m: "
unit=raw_input()
if unit=="cm":
l_cm=(10**5)*l_km
print "Length in cm is: "+str(l_cm)
elif unit=="m":
l_m=(10**3)*l_km
print "Length in m is: "+str(l_m)
else:
print "Invalid input. Enter only cm or m"... | true |
f31a2f8ae56690da86253aed017a2dfa91a83343 | okdonga/algorithms | /find_matches_both_prefix_and_suffix.py | 2,873 | 4.15625 | 4 | ################
# Given a string of characters, find a series of letters starting from the left of the string that is repeated at the end of the string.
# For example, given a string 'jablebjab', 'jab' is found at the start of the string, and the same set of characters is also found at the end of the string.
# This i... | true |
6d0745071e38ee8949a6392e51d8f036faef9dcc | arnillacej/calculator | /calculator.py | 397 | 4.34375 | 4 | num1 = float(input("Please enter the first number: "))
operation = input("Please choose an arithmetical operation '+,-,*,/': ")
num2 = float(input("Please enter the second number: "))
if operation == "+":
print(num1+num2)
elif operation == "-":
print(num1-num2)
elif operation == "*":
print(num1*num2)
elif o... | true |
74fd1b9071853159dbed349504f704be01534532 | EricE-Freelancer/Learning-Python | /the power of two.py | 426 | 4.40625 | 4 | print("Hi! what is your name? ")
name = input()
anything = float(input("Hi " + name + ", Enter a number: "))
something = anything ** 2.0
print("nice to meet you " + name +"!")
print(anything, "to the power of 2 is", something)
#the float() function takes one argument (e.g., a string: float(string))and tries... | true |
be5e00cd27adb53a3e3c6f873ffdfc91acf1463f | Nayan356/Python_DataStructures-Functions | /Functions/pgm9.py | 676 | 4.3125 | 4 | # Write a function called showNumbers that takes a parameter called limit.
# It should print all the numbers between 0 and limit with a label to
# identify the even and odd numbers.
def showNumbers(limit):
count_odd = 0
count_even = 0
for x in range(1,limit):
if not x % 2... | true |
b88b8781aff585532384232fae3028ec7ce2d82d | Nayan356/Python_DataStructures-Functions | /DataStructures_2/pgm7.py | 472 | 4.4375 | 4 | # # Write a program in Python to reverse a string and
# # print only the vowel alphabet if exist in the string with their index.
def reverse_string(str1):
return ''.join(reversed(str1))
print()
print(reverse_string("random"))
print(reverse_string("consultadd"))
print()
# def vowel(text):
# vowels = "aeiuoAEI... | true |
c5a78bcae376bba759a179839b6eba037ecd6988 | Nayan356/Python_DataStructures-Functions | /DataStructures/pgm7.py | 232 | 4.375 | 4 | # Write a program to replace the last element in a list with another list.
# Sample data: [[1,3,5,7,9,10],[2,4,6,8]]
# Expected output: [1,3,5,7,9,2,4,6,8]
num1 = [1, 3, 5, 7, 9, 10]
num2 = [2, 4, 6, 8]
num1[-1:] = num2
print(num1)
| true |
84e673227276da95fa1bc8e4cf0801c5c77080a4 | Nayan356/Python_DataStructures-Functions | /Functions/pgm7.py | 519 | 4.4375 | 4 | # Define a function that can accept two strings as input and print the string
# with maximum length in console. If two strings have the same length,
# then the function should print all strings line by line.
def length_of_string(str1, str2):
if (len(str1) == len(str2)):
print(str1)
#print("\n")
print(str2)
... | true |
4f708d85e2be8dba03ad84c944f1192f7fb9c961 | perryl/daftpython | /calc.py | 846 | 4.15625 | 4 | while True:
try:
x = int(raw_input('Enter a value: '))
break
except:
print "Integer values only, please!"
continue
while True:
try:
y = int(raw_input('Enter a second value: '))
break
except:
print "Integer values only, please!"
continue
add = x+y
dif = abs(x-y)
mul = x*y
quo = x/y
rem = x%y
print 'T... | true |
c8c98a63020ff5971183ce90bd3d4a43d95f0b95 | karayount/study-hall | /string_compression.py | 1,012 | 4.53125 | 5 | """ Implement a method to perform basic string compression using the counts of
repeated characters. For example, the string aabcccccaaa would become a2b1c5a3.
If the "compressed" string would not become smaller than the original string,
your method should return the original string. You can assume the string has
only u... | true |
6190823da69071ca54625f541a5e90463c9876b7 | karayount/study-hall | /highest_product.py | 1,388 | 4.34375 | 4 | """Given a list_of_ints, find the highest_product you can get from
three of the integers.
The input list_of_ints will always have at least three integers.
>>> find_highest_product([1, 2, 3, 4, 5])
60
>>> find_highest_product([1, 2, 3, 2, 3, 2, 3, 4])
36
>>> find_highest_product([0, 1, 2])
0
>>> find_highest_produc... | true |
52cffd996c81e097f71bec337c2dce3d69faecac | Potatology/algo_design_manual | /algorist/data_structure/linked_list.py | 1,947 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Linked list-based container implementation.
Translate from list-demo.c, list.h, item.h. Add iterator implementation.
"""
__author__ = "csong2022"
class Node:
"""List node."""
def __init__(self, item, _next=None):
self.item = item # data item
... | true |
af76bb19fcfa690fa49ea0390ef6ea6e9716f133 | Potatology/algo_design_manual | /algorist/data_structure/linked_queue.py | 1,773 | 4.375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Implementation of a FIFO queue abstract data type.
Translate from queue.h, queue.c. Implement with singly linked list. Add iterator implementation.
"""
__author__ = "csong2022"
class Node:
"""Queue node."""
def __init__(self, item, _next=None):
self... | true |
fd96bd483b82593170856bc0d62ccab97ad33036 | abriggs914/CS2043 | /Lab2/palindrome.py | 466 | 4.125 | 4 | def palcheck(line, revline):
half = (len(line) / 2)
x = 0
while(half > x):
if(line[x] == revline[x]):
x += 1
else:
return False
return True
class palindrome :
line = raw_input("Please enter a string:")
print(line)
print(line[::-1])
revline = (line... | true |
85d156b95da272ad1d9cdb86cde272cd842e0fa0 | imclab/introduction-to-algorithms | /2-1-insertion-sort/insertion_sort.py | 728 | 4.34375 | 4 | #!/usr/bin/env python
#
# insertion sort implementation in python
#
import unittest
def insertion_sort(input):
"""
function which performs insertion sort
Input:
input -> array of integer keys
Returns: the sorted array
"""
for j in xrange(len(input)):
key = inp... | true |
5e53080b0af272b0d9f0aa69e542bbaaa9af09f5 | Azeem-Q/Py4e | /ex84.py | 711 | 4.28125 | 4 | """
8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort a... | true |
4877cfe0219914090f0eb38fec32a4cdafb780ec | mehnazchyadila/Python_Practice | /program45.py | 512 | 4.15625 | 4 | """
Exception Handling
"""
try:
num1 = int(input("Enter Any Integer number : "))
num2 = int(input("Enter any integer number : "))
result = num1 / num2
print(result)
except (ValueError,ZeroDivisionError,IndexError):
print("You have to insert any integer number ")
finally:
print("Thanks")
def voter... | true |
87c7fa65332cd453521fbc957b430fd2878e2eb8 | antoniougit/aByteOfPython | /str_format.py | 916 | 4.34375 | 4 | age = 20
name = 'Swaroop'
# numbers (indexes) for variables inside {} are optional
print '{} was {} years old when he wrote this book'.format(name, age)
print 'Why is {} playing with that python?'.format(name)
# decimal (.) precision of 3 for float '0.333'
print '{0:.3f}'.format(1.0/3)
# fill with underscores (_) with... | true |
8f590bec22c64d0c9d89bfcc765f042883955a02 | tprhat/codewarspy | /valid_parentheses.py | 807 | 4.34375 | 4 | # Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The
# function should return true if the string is valid, and false if it's invalid.
# Constraints
# 0 <= input.length <= 100
#
# Along with opening (() and closing ()) parenthesis, input may contain any vali... | true |
657dd462815393c877709d5dcdef2485ec6d8763 | lidorelias3/Lidor_Elias_Answers | /python - Advenced/Pirates of the Biss/PiratesOfTheBiss.py | 678 | 4.3125 | 4 | import re
def dejumble(scramble_word, list_of_correct_words):
"""
Function take scramble word and a list of a words and
check what word in the list the scramble word can be
:param scramble_word: word in pirate language
:param list_of_correct_words: a list of words in our language
:return: the ... | true |
8678b04cd9e28847b30d4b8ec7fe3f9aaddc1708 | rohan8594/DS-Algos | /leetcode/medium/Arrays and Strings/ReverseWordsInAString.py | 1,076 | 4.3125 | 4 | # Given an input string, reverse the string word by word.
# Example 1:
# Input: "the sky is blue"
# Output: "blue is sky the"
# Example 2:
# Input: " hello world! "
# Output: "world! hello"
# Example 3:
# Input: "a good example"
# Output: "example good a"
# Note:
# A word is defined as a sequence of non-space... | true |
634119cf7cb1a5d461e0a320ac79151f217e00fd | rohan8594/DS-Algos | /leetcode/easy/Arrays and Strings/UniqueCharachters.py | 476 | 4.25 | 4 | # Given a string,determine if it is comprised of all unique characters. For example,
# the string 'abcde' has all unique characters and should return True. The string 'aabcde'
# contains duplicate characters and should return false.
def uniqueChars(s):
seen = set()
for i in range(len(s)):
if s[i] not... | true |
a2510d4c072bbae473cee9ea22e27c081bd97a4c | MVGasior/Udemy_training | /We_Wy/reading_input.py | 1,536 | 4.3125 | 4 | # This program is a 1# lesson of In_Ou Udemy
# Author: Mateusz Gąsior
# filename = input("Enter filename: ")
# print("The file name is: %s" % filename)
file_size = int(input("Enter the max file size (MB): "))
print("The max size is %d" % file_size)
print("Size in KB is %d" % (file_size * 1024))
pri... | true |
d1af7d34089b172801b7bef550955595791f2422 | yujie-hao/python_basics | /datatypes/type_conversion_and_casting.py | 1,689 | 4.75 | 5 | # ==================================================
"""
https://www.programiz.com/python-programming/type-conversion-and-casting
Key Points to Remember
1. Type Conversion is the conversion of object from one data type to another data type.
2. Implicit Type Conversion is automatically performed by the Python interpret... | true |
1eb815e71e54a98630a1c89715a1a59edabaf461 | yujie-hao/python_basics | /objects/class_and_object.py | 2,060 | 4.53125 | 5 | # A class is a blueprint for the object
class Parrot:
# docstring: a brief description about the class.
"""This is a Parrot class"""
# class attribute
species = "bird"
# constructor
def __init__(self, name, age):
# instance attribute
self.name = name
self.age = age
... | true |
6a9980954beb1a423130f6eb65c83a2a4ec8a1b7 | lekakeny/Python-for-Dummies | /file_operations.py | 1,762 | 4.46875 | 4 | """
File operation involves
1. opening the file
2. read or write the file
3. close file
Here we are learning how to read and write files. I learnt how to read and write long time ago! How could I be
learning now? Anyway, kwani ni kesho?
"""
f = open('text.txt', 'w',
encoding='utf8') # open the file called... | true |
ed5cb135e00272635753e85b0a7d8d859dea1e0d | lekakeny/Python-for-Dummies | /generator_and_decorators.py | 2,132 | 4.59375 | 5 | """
Generators are functions that return a lazy iterator
lazy iterators do not store their contents in memory, unlike lists
generators generate elements/values when you iterate over it
It is lazy because it will not calculate the element until when we want to use the element
"""
"Use isinstance function to check if an ... | true |
8488ee8f09498521c1cc3054147370b793a35fe1 | xs2tariqrasheed/python_exercises | /integer_float.py | 722 | 4.1875 | 4 | _ = print
# NOTE: don't compare floating number with ==
# A better way to compare floating point numbers is to assume that two
# numbers are equal if the difference between them is less than ε , where ε is a
# small number.
# In practice, the numbers can be compared as follows ( ε = 10 − 9 )
# if abs(a - b) < 1e-9: # ... | true |
6af88b90a7d58c79ee0e192212d0893c168bf45e | BinYuOnCa/DS-Algo | /CH2/stevenli/HW1/pycode/NumpyDemo.py | 1,454 | 4.25 | 4 | import numpy as np
# Generate some random data
data = np.random.randn(2, 3)
print("first random data: ", data)
# data * 10
data = data * 10
print("Data times 10: ", data)
# try np shape
print("Data shape: ", data.shape)
# Print data value's type
print("Data types:", data.dtype)
# Create a new ndarray
data_forarray... | true |
416500cec0887721d8eb35ace2b89bc8d208a247 | qasimriaz002/LeranOOPFall2020 | /qasim.py | 555 | 4.34375 | 4 | from typing import List
def count_evens(values: List[List[int]]) -> List[int]:
"""Return a list of counts of even numbers in each of the inner lists
of values.
# >>> count_evens([[10, 20, 30]])
[3]
# >>> count_evens([[1, 2], [3], [4, 5, 6]])
[1, 0, 2]
"""
evenList = []
for sublist... | true |
ad3a6c22485fece625f45f894962d548960b00b0 | qasimriaz002/LeranOOPFall2020 | /Labs/Lab_1/Lab_1_part_3.py | 1,323 | 4.53125 | 5 | # Here we will use the dictionaries with the list
# We will create the record of 5 students in the different 5 dictionaries
# Then we will add all of the these three dictionaries in the list containing the record of all student
# Creating the dictionaries
stdDict_1 = {"name": "Bilal", "age": 21, "rollno": "BSDS-001-20... | true |
c2bf6604b053c51f040365c80ccdb95d3dae9fba | domsqas-git/Python | /vscode/myGame.py | 1,044 | 4.21875 | 4 | print("Bim Bum Bam!!")
name = input("What's your name? ").upper()
age = int(input("What's your age? "))
print("Hello", name, "you are", age, "years hold.")
points = 10
if age >= 18:
print("Hooray!! You can play!!")
wants_to_play = input("Do you want to play? ").lower()
if wants_to_play == "yes":
... | true |
04c9bfd9367c43b47f01ba345ba94a7a9ac61129 | Nilutpal-Gogoi/LeetCode-Python-Solutions | /Array/Easy/674_LongestContinuousIncreasingSubsequence.py | 856 | 4.21875 | 4 | # Given an unsorted array of integers, find the length of longest continuous
# increasing subsequence(Subarray).
# Example 1:
# Input: [1,3,5,4,7]
# Output: 3
# Explanation: The longest continuous increasing subsequence is [1,3,5], its length
# is 3. Even though [1,3,5,7] is also an increasing subseque... | true |
05365bc5a7afac8cb90b1078393aec87ec1867b4 | Nilutpal-Gogoi/LeetCode-Python-Solutions | /Array/Easy/349_IntersectionOfTwoArrays.py | 986 | 4.21875 | 4 | # Given two arrays, write a function to compute their intersection.
# Example 1:
# Input: nums1 = [1,2,2,1], nums2 = [2,2]
# Output: [2]
# Example 2:
# Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
# Output: [9,4]
# Note:
# Each element in the result must be unique.
# The result can be in any order.
# -----... | true |
8b9c0aac40b97452fc35f19f49f191bc161e90b9 | Nilutpal-Gogoi/LeetCode-Python-Solutions | /LinkedList/Easy/21_MergeTwoSortedLists.py | 1,184 | 4.21875 | 4 | # Merge two sorted linked lists and return it as a new sorted list. The new list should
# be made by splicing together the nodes of the first two lists.
# Example:
# Input: 1->2->4, 1->3->4
# Output: 1->1->2->3->4->4
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None)... | true |
2ff343c91342b32581d3726eb92c6570eb4c049e | forgoroe/python-misc | /5 listOverLap.py | 1,102 | 4.3125 | 4 | """
ake two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of diffe... | true |
1e138a3770218338f66b78f14945e0508c1041a4 | forgoroe/python-misc | /3 listLessThan.py | 912 | 4.375 | 4 | """
Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.
Extras:
Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out t... | true |
7c57689eac501ab4bc6da1e8c17a5c7abe1dd58b | forgoroe/python-misc | /14 removeListDuplicates.py | 771 | 4.21875 | 4 | """
Write a program (function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates.
Extras:
Write two different functions to do this - one using a loop and constructing a list, and another using sets.
Go back and do Exercise 5 using sets, and write the s... | true |
c45559cbf2cd3491aa031ec9116ba6d2478dace9 | notontilt09/Intro-Python-I | /src/prime.py | 294 | 4.125 | 4 | import math
x = input("Enter a number, I'll let you know if it's prime:")
def isPrime(num):
if num < 2:
return False
for i in range(2, math.ceil(math.sqrt(num))):
if num % i == 0:
return False
return True
if isPrime(int(x)):
print('Prime')
else:
print('Not prime')
| true |
4d343fedf8584b93d3835f74851898c2bbff0e8c | Tanner-Jones/Crypto_Examples | /Encryption.py | 696 | 4.15625 | 4 | from cryptography.fernet import Fernet
# Let's begin by showing an example of what encryption looks like
# This is an example random key. If you run the file again
# you will notice the key is different each time
key = Fernet.generate_key()
print(key)
# Fernet is just a symmetric encryption implementation
... | true |
4b772bd2b3e80c5efb292bfedf7e74908aae1d7a | jonaskas/Programa-o | /7_colecoes-master/C_mutability2.py | 489 | 4.15625 | 4 | """
Mutability
- Python is strongly object-oriented in the sense that everything
is an object including numbers, strings and functions
- Immutable objects: int, float, decimal, complex, bool, string,
tuple, range, frozenset, bytes
- Mutable objects: list, dict, set, bytearray,user-defined classes
"""
def print... | true |
3939d09d42684a7b934c5d81820cb8153b8c4b29 | jonaskas/Programa-o | /7_colecoes-master/C_mutability4.py | 684 | 4.3125 | 4 | """
Mutability
- Python is strongly object-oriented in the sense that everything
is an object including numbers, strings and functions
- Immutable objects: int, float, decimal, complex, bool, string,
tuple, range, frozenset, bytes
- Mutable objects: list, dict, set, bytearray,user-defined classes
"""
def print... | true |
62fb02699f26a16e7c18ba5d70b234068c05b0ee | jonaskas/Programa-o | /7_colecoes-master/C_mutability3.py | 474 | 4.125 | 4 | """
Mutability
- Python is strongly object-oriented in the sense that everything
is an object including numbers, strings and functions
- Immutable objects: int, float, decimal, complex, bool, string,
tuple, range, frozenset, bytes
- Mutable objects: list, dict, set, bytearray,user-defined classes
"""
def print... | true |
74494d848957c254dea03530e1cabe13b1b399b1 | Jithin2002/pythonprojects | /List/element found.py | 384 | 4.125 | 4 | lst=[2,3,4,5,6,7,8]
num=int(input("enter a number"))
flag=0
for i in lst:
if(i==num):
flag=1
break
else:
flag=0
if(flag>0):
print("element found")
else:
print("not found")
#this program is caled linear search
# we have to search everytime wheather element is thereor not
# drawbac... | true |
321f1e726d75e4f7013074163ce7cfeab25dbeb8 | sunglassman/U3_L11 | /Lesson11/problem3/problem3.py | 253 | 4.1875 | 4 | print('-' * 60)
print('I am EvenOrOdd Bot')
print()
number = input('Type a number: ')
number = int(number)
if number == even:
print('Your number is even. ')
else:
print('Your number is odd. ')
print('Thank you for using the app! ')
print('-' * 60) | true |
639de603bbf4502f07acfdfe29d6e048c4a89076 | rjtshrm/altan-task | /task2.py | 926 | 4.125 | 4 | # Algorithm (Merge Intervals)
# - Sort the interval by first element
# - Append the first interval to stack
# - For next interval check if it overlaps with the top interval in stack, if yes merge them
def merge_intervals(intervals):
# Sort interval by first element
sort_intervals_first_elem = sorted(intervals... | true |
132b54c3b4587e500e050d6be5cfadc4488f5da5 | briantsnyder/Lutron-Coding-Competiton-2018 | /move_maker.py | 1,946 | 4.4375 | 4 | """This class is the main class that should be modified to make moves in order to play the game.
"""
class MoveMaker:
def __init__(self):
"""This class is initialized when the program first runs.
All variables stored in this class will persist across moves.
Do any initialization of data y... | true |
c7363294a807a273dce1204c1c6b0a2b167590ee | nathancmoore/code-katas | /growing_plant/plant.py | 528 | 4.34375 | 4 | """Return the number of days for a plant to grow to a certain height.
#1 Best Practices Solution by Giacomo Sorbi
from math import ceil; growing_plant=lambda u,d,h: max([ceil((h-u)/(u-d)),0])+1
"""
def growing_plant(up_speed, down_speed, desired_height):
"""Return the number of days for a plant to grow to a ce... | true |
d0f59bf4520f993c32505a7b3406d786a76befa9 | PaviLee/yapa-python | /in-class-code/CW22.py | 482 | 4.25 | 4 | # Key = Name
# Value = Age
# First way to make a dictionary object
database = {}
database["Frank"] = 21
database["Mary"] = 7
database["John"] = 10
print(database)
# Second way to make a dictionary object
database2 = {
"Frank": 21,
"Mary": 7,
"Jill": 10
}
print(database2)
for name, age in database2.item... | true |
832439c69ddbcbeb4b2ad961e7427b760306fb92 | Th0rt/LeetCode | /how-many-numbers-are-smaller-than-the-current-number.py | 999 | 4.125 | 4 | # https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/
import unittest
from typing import List
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
length = len(nums)
temp = sorted(nums)
mapping = {}
for i in range(lengt... | true |
9f0d9d5ee1f94937f54a70330e70f5c3b5dc0358 | JoeD1991/Quantum | /Joe_Problem_1.py | 361 | 4.3125 | 4 | """
If we list all the natural numbers below 10 that are multiples of
3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
myList = set()
N5 = 1000//5
N3 = 1000//3+1
for i in range(1,N3):
myList.add(3*i)
if i<N5:
myList.a... | true |
53684088e0af3d314c602a4c58439b76faf161cb | NGPHAN310707/C4TB13 | /season6/validpasswordstourheart.py | 212 | 4.125 | 4 | while True:
txt = input("Enter your password?")
print(txt)
if txt.isalpha() or len(txt)<=8 or txt.isdigit:
print(txt,"is a name")
break
else:
print("please don't")
| true |
144a61b43eab0992d60e4b0e8146734ed53347d0 | JitinKansal/My-DS-code | /tree_imlementation.py | 1,048 | 4.1875 | 4 | # Creating a new node for the binary tree.
class BinaryTree():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Inorder traversal of the tree (using recurssion.)
def inorder(root):
if root:
inorder(root.left)
print(root.data,... | true |
86a9f9654568017337b9f306ebd4a8eea326b535 | YaohuiZeng/Leetcode | /152_maximum_product_subarray.py | 1,446 | 4.28125 | 4 | """
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
"""
"""
Q:
(1) could have 0, and negative
(2) input contains at least one number
(3) all in... | true |
d5ac5a0d89985b6525988e21ed9fe17a44fb4caa | YaohuiZeng/Leetcode | /280_wiggly_sort.py | 1,227 | 4.21875 | 4 | """
Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].
"""
"""
1. use python in-place sort()
2. one pass: compare current and next, if not the right order, swap.
This wo... | true |
6aea488ab45998317d8a8d5e180d539e5721873e | ariModlin/IdTech-Summer | /MAC.py | 518 | 4.125 | 4 | # finds the MAC of a message using two different keys and a prime number
message = "blah blahs"
key1 = 15
key2 = 20
prime_num = 19
def find_mac():
message_num = 0
for i in range(len(message)):
# takes each letter of the message and finds its ASCII counterpart
num = ord(message[i])
# adds each ASCII nu... | true |
6fe51f731f777d02022852d1428ce069f0594cf4 | ariModlin/IdTech-Summer | /one time pad.py | 1,867 | 4.21875 | 4 | alphabet = "abcdefghijklmnopqrstuvwxyz"
message = input("input message you want to encrypt: ")
key = input("input key you want to encrypt the message with: ")
message_array = []
key_array = []
encrypted_numbers = []
decrypted_message = ""
def convert_message():
for i in range(len(message)):
# takes... | true |
ada99ffe37296e78bbaa7d804092a495be47c1ba | dineshj20/pythonBasicCode | /palindrome.py | 890 | 4.25 | 4 | #this program is about Palindrome
#Palindrom is something who have the same result if reversed for e.g. " MOM "
#how do we know whether the given string or number is palindrome
number = 0
reverse = 0
temp = 0
number = int(input("Please Enter the number to Check whether it is a palidrome : "))
print(number)
temp = numbe... | true |
6c5ee3e9cb85a24940a9238981b7f6fbf9ec1696 | MichealPro/sudoku | /create_sudoku.py | 2,158 | 4.375 | 4 | import random
import itertools
from copy import deepcopy
# This function is used to make a board
def make_board(m=3):
numbers = list(range(1, m ** 2 + 1))
board = None
while board is None:
board = attempt_board(m, numbers)
return board
# This function is used to generate a full board
def at... | true |
f605c356950e7e609d3e57c92169775cf4ed497a | sssvip/LeetCode | /python/num003.py | 1,303 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-09-28 22:25:36
# @Author : David:admin@dxscx.com)
# @Link : http://blog.dxscx.com
# @Version : 1.0
"""
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the ... | true |
89db6d170e6eb265a1db962fead41646aaed6f9f | sssvip/LeetCode | /python/num581.py | 1,606 | 4.21875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@version: v1.0
@author: David
@contact: tangwei@newrank.cn
@file: num581.py
@time: 2017/11/7 20:29
@description:
Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be s... | true |
09eb0f8acf255d4471a41a56a50bccf24ed4c91c | MissBolin/CSE-Period3 | /tax calc.py | 230 | 4.15625 | 4 | # Tax Calculator
cost = float(input("What is the cost of this item? "))
state = input("What state? ")
tax = 0
if state == "CA":
tax = cost * .08
print("Your item costs ${:.2f}, with ${:.2f} in tax.".format(cost+tax, tax))
| true |
b9884eae05e9518e3ec889dd5280a8cea7c3c1d7 | gandastik/365Challenge | /365Challenge/insertElementes.py | 382 | 4.125 | 4 | #Jan 24, 2021 - insert a elements according to the list of indices
from typing import List
def createTargetArray(nums: List[int], index: List[int]) -> List[int]:
ret = []
for i in range(len(nums)):
ret.insert(index[i], nums[i])
return ret
lst = [int(x) for x in input().split()]
index = [int(x) ... | true |
20644bc6631d5eb8e555b1e2e61d1e0e6273bd00 | gandastik/365Challenge | /365Challenge/matrixDiagonalSum.py | 762 | 4.21875 | 4 | #37. Feb 6, 2021 - Given a square matrix mat, return the sum of the matrix diagonals.
# Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
from typing import List
def diagonalSum(mat: List[List[int]]) -> int:
... | true |
9fdedda65ec74a7ac9d9ab1510dcc1b63adf502d | ovidubya/Coursework | /Python/Programs/assign5part1.py | 560 | 4.46875 | 4 | def find_longest_word(wordList):
print("The list of words entered is:")
print(wordList)
result = ""
i = 0
while(i < len(wordList)): # iterates over the list to find the first biggest word
if(len(result) < len(wordList[i])):
result = wordList[i]
i = i + 1
print("")
... | true |
a5201821c6cd15088a4b1a4d604531bbcca68c69 | mlrice/DSC510_Intro_to_Programming_Python | /fiber_optic_discount.py | 1,297 | 4.34375 | 4 | # DSC510
# 4.1 Programming Assignment
# Author Michelle Rice
# 09/27/20
# The purpose of this program is to estimate the cost of fiber optic
# installation including a bulk discount
from decimal import Decimal
print('Hello. Thank you for visiting our site, we look forward to serving you.'
'\nPlease provide some... | true |
65293fcbfb356d2f045eff563083e2b751e61326 | martinkalanda/code-avengers-stuff | /wage calculaor.py | 297 | 4.40625 | 4 | #Create variables
hourly_rate = int(input("what is your hourly rate"))
hours_worked = int(input("how many hours have you worked per week"))
#Calculate wages based on hourly_rate and hours_worked
wages = hourly_rate * hours_worked
print("your wages are ${} per week" .format(wages))
| true |
d1c8e6df0c2a44e543b879dcfcee89a2f77557ba | NishadKumar/interview-prep | /dailybyte/strings/longest_substring_between_characters.py | 1,874 | 4.21875 | 4 | # Given a string, s, return the length of the longest substring between two characters that are equal.
# Note: s will only contain lowercase alphabetical characters.
# Ex: Given the following string s
# s = "bbccb", return 3 ("bcc" is length 3).
# Ex: Given the following string s
# s = "abb", return 0.
# Approach:
#... | true |
649fb09854bb5c385e3eaff27302436741f09e4f | NishadKumar/interview-prep | /leetcode/1197_minimum_knight_moves/minimum_knight_moves.py | 2,147 | 4.125 | 4 | # In an infinite chess board with coordinates from -infinity to +infinity, you have a knight at square [0, 0].
# A knight has 8 possible moves it can make. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
# Return the minimum number of steps needed to move the knight to the ... | true |
8488da7cb5989c2785a81faf81d9ac7a849c5b0d | Marcus-Mosley/ICS3U-Unit4-02-Python | /product.py | 1,153 | 4.65625 | 5 | #!/usr/bin/env python3
# Created by Marcus A. Mosley
# Created on October 2020
# This program finds the product of all natural numbers preceding the
# number inputted by the user (a.k.a. Factorial)
def main():
# This function finds the product of all natural numbers preceding the
# number inputted by... | true |
e7958f906c313378efd5815b81b70b4f5c45c65e | robbyhecht/Python-Data-Structures-edX | /CH9/exercise1.py | 776 | 4.15625 | 4 | # Write a program that reads the words inwords.txtand stores them askeys in a dictionary. It doesn’t matter what the values are. Then youcan use theinoperator as a fast way to check whether a string is in thedictionary.
from collections import defaultdict
f = input("Enter file name: ")
try:
content = open(f)
exce... | true |
566a23e9b7633a9ce17062fad16cb1088e33e155 | TareqJudehGithub/Ardit_Sulce_Udemy | /Python_Mega/sec14_Numpy/numpy_practice.py | 886 | 4.1875 | 4 | """ Numpy
- Numpy is a fundamental package for scientific computing with Python.
- Official page: https://numpy.org/
- Numpy comes installed with Pandas library.
"""
import numpy
# .arange(int) created a new array with the specified int number.
n = numpy.arange(27)
print(n)
print(type(n))
print(len(n))
print(... | true |
fdb85dd88220653054dc4127e2273885515a9c53 | TareqJudehGithub/Ardit_Sulce_Udemy | /Python_Mega/sec6_Basics_Proc_User_Input/string_formatting.py | 653 | 4.125 | 4 | """
String formatting in Python
- More on:
https://pyformat.info/
"""
def greet_user():
name = input('What is your name? ')
# this is the a string formatting method introduced in Python 2
return "Hello, %s!" %name.title()
# using format()
return "Hello, {}!".format(name.title)
... | true |
ebdfab2cb3cc75734d4d514005ffbb2bef50fa67 | TareqJudehGithub/Ardit_Sulce_Udemy | /Python_Mega/sec8_build_prog/input_problem.py | 1,092 | 4.25 | 4 | import re
# Write a program, that asks the user for input(s), until
# the user types \end
# user inputs should not include any symbols.
# return all user outputs
def inputs_problem():
inputs = list()
inputs_str = str()
interrogatives = ('how', 'what', 'why', 'where')
input_validator = re.co... | true |
f13e841d3a8ef2d2e46bd958811aa53409350686 | niyatigulati/Calculator.py | /calc.py | 524 | 4.125 | 4 | def calc(choice, x, y):
if (choice == 1):
add(x, y)
elif (choice == 2):
sub(x, y)
elif (choice == 3):
mul(x,y)
elif (choice == 2):
div(x,y)
# the below functions must display the output for the given arithmetic
# TODO
def add(a, b):
pass
def sub(a, b):
pass
... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.