blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
5f3742149ccb7d2f09cf2233de28e7339cd30777 | 16030IT028/Daily_coding_challenge | /InterviewBit/005_powerOfTwoIntegers.py | 662 | 4.15625 | 4 | # https://www.interviewbit.com/problems/power-of-two-integers/
"""Given a positive integer which fits in a 32 bit signed integer, find if it can be expressed as A^P where P > 1 and A > 0. A and P both should be integers.
Example
Input : 4
Output : True
as 2^2 = 4. """
import math
def isPower(n):
if n == 1:
return 1 # True
# Try all numbers from 2 to sqrt(n) as base
for x in range(2, int(math.sqrt(n))+1):
y = 2
p = x **y
# Keep increasing y while power 'p' is smaller than n.
while (p <= n and p > 0):
if p == n:
return 1 # True
y += 1
p = x ** y
return 0 #False
print (isPower(7)) | true |
a3f07f91380d0e530fb44c94b28f84855efba2f0 | 16030IT028/Daily_coding_challenge | /Algoexpert-Solutions in Python/Group by Category/Recursion/001_powerset.py | 1,210 | 4.4375 | 4 | # https://www.algoexpert.io/questions/Powerset
"""
Powerset
Write a function that takes in an array of unique integers and returns its powerset. The powerset P(X) of a set X is the set of all subsets of X. For example, the powerset of [1,2] is [[], [1], [2], [1,2]]. Note that the sets in the powerset do not need to be in any particular order.
Sample input: [1, 2, 3]
Sample output: [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]"""
# Solution 1: Using iterative way
# O(n*2^n) time | O(n*2^n) space
# for n elements, there are 2 ^n subsets.
def powerset(array):
subsets = [[]]
for ele in array:
for i in range(len(subsets)):
currentSubset = subsets[i]
subsets.append(currentSubset + [ele])
return subsets
# Solution 2: Recursive way
# O(n*2^n) time | O(n*2^n) space - Same as iterative
def powerset2(array, idx=None):
if idx is None:
idx = len(array) - 1
if idx < 0:
return [[]]
ele = array[idx]
subsets = powerset2(array, idx - 1)
#Same logic as in solution 1
for i in range(len(subsets)):
currentSubset = subsets[i]
subsets.append(currentSubset + [ele])
return subsets | true |
302f512a87c8f0dbd29c36cd9326e1ba73ab95e4 | JacobJustice/Sneer | /sneer | 2,956 | 4.21875 | 4 | #! /usr/bin/python3
import sys
import getopt
#
# sneer_default
#
# parameters:
# word -word in the input string that the character you are considering to
# upper or lower is from
# index-index of the character you are considering to upper or lower
#
# return:
# boolean (capitalize this character or not)
#
# parameters allow for a wide variety of conditions to make your own sarcastic
# looking text. sneer_default simply flips a coin
#
# intended to be passed in as an argument to the main function
#
def sneer_default(word, index):
import random
return random.choice([True,False])
#
# char_to_words
#
# parameters:
# char_list - list of chars
#
# return:
# word_list - list of strings
#
# concatenates chars into string, seperated by spaces
#
# in: ['a','p','p','l','e',' ','j','u','i','c','e']
# out: ["apple", "juice"]
#
def char_to_words(char_list):
word_list = ''.join(char_list)
word_list = word_list.split(' ')
return word_list
def sneer(sneer_function, words):
sneered = []
for word in words:
l_word = list(''.join(word))
for i, letter in enumerate(word):
if sneer_function(word, i):
l_word[i] = l_word[i].upper()
else:
l_word[i] = l_word[i].lower()
l_word.append(' ')
sneered += l_word
# Delete trailing newline
del sneered[-1]
return sneered
#
# main
#
# parameters:
# sneer_function - function that takes in a word and index, and returns true or false
#
# uses sneer_function to decide whether or not to capitalize a letter
#
def main(sneer_function):
input_from_file = False
output_to_file = False
opts, args = getopt.getopt(sys.argv[1:], "f:o:")
# Parse arguments
for opt, arg in opts:
if opt == "-f":
input_from_file = True
input_path = arg
if opt == "-o":
output_to_file = True
output_path = arg
# If an input file was specified, read the file into input
if input_from_file:
with open(input_path) as f:
content = f.read()
input = list(content)
input = char_to_words(input)
# otherwise get input from stdin
else:
input = args
if len(input) == 0: #if there are no normal arguments
args = list(sys.stdin.read()) #check stdin
input = char_to_words(args) #convert to proper format
if input[-1][-1] == '\n':
input[-1] = input[-1][:-1] #remove \n
if len(input) == 0: #if there are still no normal arguments
sys.exit() #exit
# Run sneer
sneered = sneer(sneer_function, input)
# If an output file was specified, write to it
if output_to_file:
with open(output_path, 'w+') as f:
f.write(''.join(sneered))
# Otherwise print to stdin
else:
print(''.join(sneered))
main(sneer_default)
| true |
d9180832982a0a6edae7e16eacedb63e2a31f643 | s-ankur/cipher-gui | /vigenere.py | 1,111 | 4.21875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
The Vigenère cipher is a method of encrypting alphabetic text by using a
series of interwoven Caesar ciphers, based on the letters of a keyword.
It is a form of polyalphabetic substitution.
"""
import random
from itertools import cycle
from collections import Counter
import caesar
import test
cipher_type = 'text'
def encrypt(plaintext, key):
key = map(lambda x: ord(x) - ord('a'), key.lower())
return ''.join(list(map(lambda p: caesar.encrypt_letter(*p), zip(plaintext, cycle(key)))))
def decrypt(ciphertext, key):
key = map(lambda x: -(ord(x) - ord('a')), key.lower())
return ''.join(list(map(lambda x: caesar.encrypt_letter(*x), zip(ciphertext, cycle(key)))))
def crack(ciphertext):
length = test.kasiski_length(ciphertext)
length = random.choice([int(length), int(length) + 1])
key = []
for i in range(length):
column = ciphertext[i::length]
text, key_letter = caesar.crack(column)
key.append(key_letter)
key = ''.join(key)
plaintext = decrypt(ciphertext, key)
return plaintext, key
| true |
66ce3651849839bafd55e0d1fe26eac975fb6ab5 | s-ankur/cipher-gui | /caesar.py | 2,164 | 4.21875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Caesar shift, is one of the simplest and most widely known encryption techniques.
It is a type of substitution cipher in which each letter in the plaintext is replaced
by a letter some fixed number of positions down the alphabet. For example,
with a left shift of 3, D would be replaced by A, E would become B, and so on.
The method is named after Julius Caesar, who used it in his private correspondence.
"""
from collections import Counter
from functools import lru_cache
import string
FREQ_LETTERS = 'ETAOINSRHDLUCMFYWGPBVKXQJZ'
cipher_type = 'text'
alphabet = string.printable
key_length = 1
def encrypt_letter(letter, key):
if letter.islower():
return chr((ord(letter) + key - ord('a')) % 26 + ord('a'))
if letter.isupper():
return chr((ord(letter) + key - ord('A')) % 26 + ord('A'))
return letter
def encrypt(plaintext, key):
key = ord(key.lower()[0]) - ord('a')
return ''.join(list(map(lambda x: encrypt_letter(x, key), plaintext)))
def decrypt(ciphertext, key):
key = - (ord(key.lower()[0]) - ord('a'))
return ''.join(list(map(lambda x: encrypt_letter(x, key), ciphertext)))
def lcs(X, Y):
m = len(X)
n = len(Y)
L = [[None] * (n + 1) for i in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
L[i][j] = 0
elif X[i - 1] == Y[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
else:
L[i][j] = max(L[i - 1][j], L[i][j - 1])
return L[m][n]
def crack(ciphertext):
ciphertext_orig = ciphertext
ciphertext = ciphertext.upper()
candidates = []
for candidate_key in string.ascii_lowercase:
print('trying', candidate_key)
candidate_plaintext = decrypt(ciphertext, candidate_key)
freq_cipher = ''.join([letter for letter, count in Counter(candidate_plaintext).most_common() if letter.isalpha()])
print(freq_cipher)
candidates.append((lcs(freq_cipher, FREQ_LETTERS), candidate_key))
key = max(candidates)[1]
plaintext = decrypt(ciphertext_orig, key)
return plaintext, key
| true |
a50d97b6cea7967ac59ac5654f7cc23c4c5ff17d | mehedi-hasan-shuvon/python-ML-learing | /6.py | 226 | 4.125 | 4 | #........if else statements.........
number =int (input ("enter your marked: "))
print(number)
if number>=90 and number<=100:
grade='A'
elif number>=80:
grade='B'
else:
grade='fail'
print("the grade is" ,grade) | true |
9c610e215d10acf6066a03c14a1d7afbc09a3903 | beardedsamwise/AutomateTheBoringStuff | /Chapter 7 - Regexes/practiceQuestions.py | 1,227 | 4.34375 | 4 | import re
# Question 21
# Write a regex that matches the full name of someone whose last name is Watanabe.
# You can assume that the first name that comes before it will always be one word that begins with a capital letter.
watanabeRegex = re.compile(r'([A-Z])(\w)+(\s)Watanabe$')
print(watanabeRegex.search('haruto Watanabe')) #must not match
print(watanabeRegex.search('Mr. Watanabe')) #must not match
print(watanabeRegex.search('Watanabe')) #must not match
print(watanabeRegex.search('Haruto watanabe')) #must not match
print(watanabeRegex.search('Haruto Watanabe')) #must match
# Question 22
# Write a regex that matches a sentence where the first word is either Alice, Bob, or Carol;
# the second word is either eats, pets, or throws; the third word is apples, cats, or baseballs;
# and the sentence ends with a period? This regex should be case-insensitive.
regex22 = re.compile(r'(alice|bob|carol)\s(eats|pets|throws)\s(apples|cats|baseballs)(.)', re.IGNORECASE)
print(regex22.search('Alice eats apples.'))
print(regex22.search('Bob pets cats.'))
print(regex22.search('Carol throws baseballs.'))
print(regex22.search('Alice throws Apples.'))
print(regex22.search('BOB EATS CATS.'))
print(regex22.search('RoboCop eats apples.'))
| true |
26436225c9a4d34240e231b93ddf065ec78cdd0c | beardedsamwise/AutomateTheBoringStuff | /Chapter 7 - Regexes/passwordComplexity.py | 1,387 | 4.4375 | 4 | # Write a function that uses regular expressions to make sure the password string it is passed is strong.
# A strong password is defined as one that is at least eight characters long, contains both uppercase and lowercase characters, and has at least one digit.
import re
def passStrength(password):
capsRegex = re.compile(r'([A-Z])') # regex for capital letters
lowRegex = re.compile(r'([a-z])') # regex for lower case letters
numRegex = re.compile(r'\d') # regex for numbers
numMo = numRegex.findall(password) # find all numbers
alphaMo = capsRegex.findall(password) + lowRegex.findall(password) # combine regex results for all letters
lowMo = lowRegex.findall(password) # find all lower case chars
capsMo = capsRegex.findall(password) # find all upper case chars
print("Current password is: " + password) # You'd never do this with a real password
# check there are 8 letters, 1 number, and a mix of upper and lower case
if (len(numMo) > 0 and len(alphaMo) > 7 and len(lowMo) > 0 and len(capsMo) > 0):
print("Your password is valid!")
else:
print("Your password does not meet the minimum requirements.")
print("It must contain 8 letters with a mix of lower and upper case and 1 number.")
print("")
passStrength("AbCdEfGhIjKl21")
passStrength("AbCdEfG1")
passStrength("AbCdEfGasd")
passStrength("abcdefghji12")
| true |
896f9f9eb299255024397cf01780615bfbb5e232 | iamstmvasan/python_programs | /BinaryGap.py | 953 | 4.1875 | 4 | #BinaryGap
#Find longest sequence of zeros in binary representation of an integer.
'''
given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001
and so its longest binary gap is of length 5.
Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.
''''
def binaryGap(N):
N = bin(N).replace("0b", "")
if N.count("0") == 0 or N.count("1") < 2:
return 0
count_list = []
count = 0
for i in range(1,len(N)):
if N[i] == "0":
count += 1
elif N[i] == "1":
count_list.append(count)
count = 0
return max(count_list)
N = int(input("Enter N : "))
print("Longest sequence of zero in binary representation is : ",binaryGap(N))
input()
| true |
8ca9ccbcc5fd6f66be9a640eb69332ced45ee797 | Dfmaaa/transferfile | /Python31/factorial_finder.py | 277 | 4.4375 | 4 | print("This app will find the factorial of the number given by you.")
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))
import factorial_finder
| true |
42c189f912652267b1bcfb2638774364f9ecfb11 | foldsters/learn-git | /example.py | 1,537 | 4.25 | 4 | #
# Decription: This program will analize the upper and lower case content of
# a given string.
#
sampleString = ("We the People of the United States, in Order+ to form a more perfect Union,"
" establish Justice, insure domestic Tranquility, provide for the common defence, promote the general Welfare,"
" and secure the Blessings of Liberty to ourselves and our Posterity, do ordain and establish this Constitution"
" for the United States of America.")
# 1) Start by counting the number of upper, lower, and other characters in the provided string. Print your results.
# 2) Next, invert the case of all of the text in the sample string. Print the resulting string.
# 3) Place all vowels in one list.
# 4) Place all consonant in another list.
# 5) Find the decimal value of each character and place all characters that are multiples of 3 in another list.
lowers = 0
uppers = 0
not_letters = 0
vowel_list = []
consonant_list = []
new_string = ""
for char in sampleString:
if char.islower():
new_string += char.upper()
lowers += 1
elif char.isupper():
new_string += char.lower()
uppers += 1
else:
new_string += char
not_letters += 1
if char.lower() in "aeiouy":
vowel_list.append(char)
elif char.isalpha():
consonant_list.append(char)
print(lowers, uppers, not_letters)
print()
print(new_string)
print()
print(vowel_list)
print()
print(consonant_list)
print()
print([ord(c) for c in sampleString if ord(c)%3==0])
| true |
3ed20ff3deb2c1950cdbbf5e474f2d7b8003db5d | HoussemCharf/FunUtils | /Searching Algorithms/binary_search.py | 775 | 4.125 | 4 | #
# Binary search works for a sorted array.
# Note: The code logic is written for an array sorted in
# increasing order.
# T(n): O(log n)
#
def binary_search(array, query):
lo, hi = 0, len(array) - 1
while lo <= hi:
mid = (hi + lo) // 2
val = array[mid]
if val == query:
return mid
elif val < query:
lo = mid + 1
else:
hi = mid - 1
return None
def binary_search_recur(array, low, high, val):
if low > high: # error case
return -1
mid = (low + high) // 2
if val < array[mid]:
return binary_search_recur(array, low, mid - 1, val)
elif val > array[mid]:
return binary_search_recur(array, mid + 1, high, val)
else:
return mid
| true |
fc78ce3ac616d51d2f5e8d7d862316e7d73c835c | zNIKK/Exercicios-Python | /Python_1/Conversor de bases numéricas.py | 479 | 4.21875 | 4 |
num=int(input('digite um número inteiro: '))
print('escolha as bases de conversão:\n'
'[ 1 ] converter para BINÁRIO\n'
'[ 2 ] converter para OCTAL\n'
'[ 3 ] converter para HEXADECIMAL')
op=int(input('Escolha:'))
if op==1:
print('{} convertido para BINÁRIO: {}'.format(num,bin(num)[2:]))
elif op==2:
print('{} convertido para OCTAL: {}'.format(num,oct(num)[2:]))
elif op==3:
print('{} convertido para HEXADECIMAL: {}'.format(num,hex(num)[2:])) | false |
5cd6988aca1ca186b582e812a4c19bc40021d1d3 | CruzJeff/CS3612017 | /Python/Exercise3.py | 1,448 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 27 13:44:36 2017
@author: User
"""
'''Very often, one wants to "Cast" variables of a certain type into another type.
Suppose we have variable x = '123', but really we would like x to be an integer.
This is easy to do in python, just use desiredtype(x) e.g. int(x) to obtain an integer.
Try the following and explain the output:'''
print(float(123)) #Converts the int 123, into the equivalent value float: 123.0
print(float('123')) #Converts the string '123' into the equivalent numeric value float: 123.0
print(float('123.23')) #Converts the string '123.23' into the equivalent numeric value float: 123.23
print(int(123.23)) #Truncates the decimal to get 123
#int('123.23')
#Will return a value error. There is no direct integer that is equivalent to '123.23',
#the string '123.23' must first be converted to a float, and then to a int.
print(int(float('123.23'))) #First converts the string '123.23' to the float 123.23, then truncates the decimal to get 123
print(str(12)) #Turns the integer 12, into the string '12'
print(str(12.2)) #Turns the float 12.2 into the string '12.2'
print(bool('a')) #All values except for 0 and empty data structures are equivalent to a boolean True.
print(bool(0)) # 0 is equivalent to a boolean False.
print(bool(0.1)) #All values except for 0 and empty data structures are equivalent to a boolean True. | true |
17223ef9ccbbfb48804dcbdcc8e544293f5c8c20 | wsegard/python-bootcamp-udemy | /python-bootcamp/01-Nbers.py | 612 | 4.28125 | 4 | # Addition
print(2+1)
# Subtraction
2-1
# Multiplication
2*2
# Division
3/2
# Floor Division
7//4
# Modulo
7%4
# Powers
2**3
# Can also do roots this way
4**0.5
# Order of Operations followed in Python
2 + 10 * 10 + 3
# Can use parentheses to specify orders
(2+10) * (10+3)
# Let's create an object called "a" and assign it the number 5
a = 5
# Adding the objects
a+a
# Reassignment
a = 10
# Check
a
# Use A to redefine A
a = a + a
# Check
a
# Use object names to keep better track of what's going on in your code!
my_income = 100
tax_rate = 0.1
my_taxes = my_income*tax_rate
# Show my taxes!
print(my_taxes)
| true |
205f7076b1b29a348c317117854b9b87751f6bb8 | zaid-kamil/DP-21-PYTHON-DS-1230 | /functions_in_python/param_fun1.py | 777 | 4.25 | 4 | # parameterized functions take input when you call them
# there are 5 ways to call a parameterized function
# 1. with required parameters ✔
# 2. with keyword/named parameters ✔
# 3. with default parameters ✔
# 4. with variable arguments ✔
# 5. with keyword arguments ✔
#########################################################
'''
def showMessage(msg):
print('*' * 30)
print(msg)
print('*' * 30)
'''
def showMessage(msg, symbol):
print(symbol*30)
print(msg)
print(symbol*30)
if __name__ == '__main__':
# directly parameterized function call
showMessage('The Stormlight Archives',">>")
showMessage("Brandon Sanderson",'*')
# user input based parameterized function call
quote = input('enter your quote: ')
showMessage(quote,'#') | true |
9d7f39be8a14a8010e7cc3652024793e8ba65a9c | zumerani/Python | /Classes and Objects/inheritance.py | 1,815 | 4.125 | 4 | class Student:
def __init__(self , name , school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
@classmethod
def friend(cls , origin , friendName , salary):
#return a new Student called 'friendName' in the same school as self
return cls(friendName , origin.school , salary) #This now calls WorkingStudent's constructor
#This is bascially 'WorkingStudent' extends 'Student', all of Student's methods are now in WorkingStudent
class WorkingStudent(Student):
def __init__(self , name , school , salary):
#rather than copying the contents of the constructor, use 'super()'
super().__init__(name , school) #executes the supper class constructor (Student's constructor)
self.salary = salary #now set your 'WorkingStudent' characteristics
zain = WorkingStudent("Zain" , "UCSD" , 15.00)
print(zain.salary) #prints 15.0
friend = WorkingStudent.friend( zain , "Bob" , 20.00) #NOTE: This calls Student's 'friend' method NOT WorkingStudent, because WorkingStudent
# doesn't have a friend method. But in order to call 'friend' as a WorkingStudent object,
# you need to declare 'friend' in the super class (Student) as a classmethod. This is
# because you are now passing 'cls' which is WorkingStudent and you return:
# cls(friendName) but that calls WorkingStudent's constructor so it will store the salary
# as well.
print(friend.name) #prints Bob
print(friend.school) #prints school
print(friend.salary) #prints salary (20.0)
| true |
47ecc6a3d81dbbf26acf7b3be532a12dda74c9f1 | huayuhui123/prac05 | /emails.py | 464 | 4.1875 | 4 | email=input("Email:")
dict={}
while email!=" ":
nameread=email.split("@")[0].title()
namecheck=' '.join(nameread.split("."))
choice=input("Is your name {}?(Y/n)".format(namecheck))
if choice.upper()=='Y':
dict[email]=namecheck
elif (choice.upper()=='N')or (choice=='no'):
name=input("Name:")
dict[email]=name
email = input("Email:")
for key,value in dict.items():
print("{}({})".format(value,key))
print("finished") | false |
8e467824df7bbab58d2f56478b1311cfe79a5bc7 | HalynaMaslak/Python_for_Linguists_module_Solutions | /Frequency_Brown_corpus.py | 1,121 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Create a program that: Asks for a word; Checks whether it is more frequent
as a Noun or a Verb in the Brown corpus. Display a message if it does not appear
as a noun or a verb in the Brown corpus.
"""
from nltk.corpus import brown
print('The program checks whether the entered word is more frequent as a Noun or a Verb in the Brown corpus.')
word = input('Enter your word: ').lower()
br_words = brown.tagged_words(tagset='universal')
count_N = 0
count_V = 0
for w in br_words:
if w[0].lower() == word and w[1] == 'NOUN':
count_N += 1
elif w[0].lower() == word and w[1] == 'VERB':
count_V += 1
print('As a Noun:', count_N, 'time(s)')
print('As a Verb:', count_V, 'time(s)')
if count_N > count_V:
print('Your word', word, 'is more frequent as a Noun.')
elif count_N == count_V !=0:
print('Your word', word, 'equally appears both as a Noun and a Verb.')
elif count_N < count_V:
print('Your word', word, 'is more frequent as a Verb.')
elif count_N == 0 and count_V == 0:
print('Your word', word, 'does not appear as a Noun or a Verb in the Brown corpus.')
| true |
3e1a7e19c27eda447d07c27f8ee641f5c384f4bf | mnaiwrit52/git-practice | /fibonacci.py | 693 | 4.28125 | 4 | #This code helps in generating fibonacci numbers upto a certain range given as user input
# f1 = 0
# f2 = 1
# n = int(input("Enter the range: "))
# print(f1,f2,end=' ')
# for count in range(2,n):
# f3 = f1 + f2
# print(f3,end=' ')
# f1 = f2
# f2 = f3
def fibo_series(num):
f1 = 0
f2 = 1
count = sum = 0
if num <= 0:
print("wrong")
elif num == 1:
print("Fibonacci series: ",num)
print(f1)
else:
print("Fibonacci series")
while count < num:
print(f1)
sum = f1 + f2
f1 = f2
f2 = sum
count = count + 1
num = int(input("Enter the number: "))
fibo_series(num) | true |
3d8a796eb5dd1b4faae9d891632b68aadcc7f8b9 | longLiveData/Practice | /python/20190404-Astar/Robotplanner.py | 2,310 | 4.1875 | 4 | import sys
# 这里的输入文件每行结尾可能是\n也可能是\r 都要考虑到
# 输出格式python3和python2不一样 注意 格式转换
def getPath(arr, path, spath, cx, cy):
arr[cx][cy] = '1'
# if get to target position, print
if(cx == endx and cy == endy):
print (str(len(path)) + " " + str(len(spath)))
res = ""
for i in spath:
res += i + " "
print(res)
return path, spath
# else
else:
if(ifOverIndex(arr, cx-1, cy)):
path.append([cx-1, cy])
if(ifPass(arr, cx-1, cy)):
spath.append("U")
path, spath = getPath(arr, path, spath, cx-1, cy)
if(ifOverIndex(arr, cx+1, cy)):
path.append([cx+1, cy])
if(ifPass(arr, cx+1, cy)):
spath.append("D")
path, spath = getPath(arr, path, spath, cx+1, cy)
if(ifOverIndex(arr, cx, cy-1)):
path.append([cx, cy-1])
if(ifPass(arr, cx, cy-1)):
spath.append("L")
path, spath = getPath(arr, path, spath, cx, cy-1)
if(ifOverIndex(arr, cx, cy+1)):
path.append([cx, cy+1])
if(ifPass(arr, cx, cy+1)):
spath.append("R")
path, spath = getPath(arr, path, spath, cx, cy+1)
if(len(spath) > 0):
spath.pop()
return path, spath
# judge if over index
def ifOverIndex(arr, cx, cy):
if(0 <= cx and cx < len(arr) and 0 <= cy and cy < len(arr[0])):
return True
# if pass
def ifPass(arr, cx, cy):
if(arr[cx][cy] == '0'):
return True
# sys.argv : input args by command line
args = sys.argv
file = open(args[1])
lines = file.readlines()
arr = []
for i in range (1, len(lines)):
a = lines[i].split("\n")[0].split("\r")[0].split(" ")
arr.append(a)
startx = int(args[3])
starty = int(args[2])
endx = int(args[5])
endy = int(args[4])
if (arr[endx][endy] == '1' or arr[startx][starty] == '1'):
print("0 0")
print('X')
else:
path = []
spath = []
path, spath = getPath(arr, path, spath, startx, starty)
if [endx, endy] not in path:
print(str(len(path))+ " " + str(0))
print('X') | false |
d429b8cdd4993081ced30d6e7d663a737d4adc54 | claeusdev/Python-basics | /chapter 4/ques3.4.py | 562 | 4.15625 | 4 | temp = float(input('enter a temperature in Celsius:'))
if temp < -273.15:
print ('The temperature is invalid because it is below absolute zero')
if temp == -273.15:
print('the temperature is absolute 0')
if -273.15 < temp < 0:
print('the temperature below is freezing')
if temp == 0:
print('the temperature is at the freezing point')
if 0 < temp <100:
print('temperature is in normal range')
if temp ==100:
print('temperature is at the boiling point')
if temp > 100:
print('the temperature is above the boiling point')
| true |
9102c4017af6a031a917b1d164448e8938654ad6 | claeusdev/Python-basics | /chapter 4/ques4.4.py | 267 | 4.1875 | 4 | credit = int(input('how many credits have you taken:'))
if credit <= 23:
print('you are a freshman')
if 24 <= credit <=53:
print('you are a sophomore')
if 54 <= credit <= 83:
print('you are a junior')
if credit >= 84:
print('you are a senior') | false |
39510b515c5c1bc0feb29b00bb5196a26809f907 | MrWillian/BinarySearch | /binarySearch.py | 615 | 4.125 | 4 | # Returns index of x in array if present
def binarySearch(array, l, r, x):
# check base case
if r >= l:
middle = l + (r - l)//2 #Get the middle index
# If element is present at the middle returns itself
if array[middle] == x:
return middle
# If element is smaller than middle, then it can only be present in left subarray
elif array[middle] > x:
return binarySearch(array, l, middle-1, x)
# Else the element can only be present in right subarray
else:
return binarySearch(array, middle+1, r, x)
else:
# Element is not present in the array
return -1
| true |
85e9677dbff83dc06c7e2ad5142548e5ca5cf9a3 | enzostefani507/python-info | /Funciones/Complementarios/Complementario15.py | 725 | 4.15625 | 4 | def verificarContraseña(pwd):
return len(pwd)>=8 and verificarMinimoMayuscula(pwd) and verificarMinimoMinuscula(pwd) and verificarMinimoNumeros(pwd)
def verificarMinimoMayuscula(pwd):
for i in pwd:
if i.isupper():
return True
return False
def verificarMinimoMinuscula(pwd):
for i in pwd:
if i.islower():
return True
return False
def verificarMinimoNumeros(pwd):
for i in pwd:
if i.isnumeric():
return True
return False
def main():
contraseña = input("Ingrese su contraseña")
verif = verificarContraseña(contraseña)
print("La firmacion: Su contraseña es segura es {}".format(verif))
main() | false |
46d784518804906896a865dbc781984d421e96fe | enzostefani507/python-info | /Listas/1/g.py | 319 | 4.1875 | 4 | #Cargar dos listas con la misma cantidad de elementos. Luego mezclarlas, cargándolas ordenadas en otra lista.
lista_1 = list(range(0,5,2))
lista_2 = list(range(2,10,3))
mezcla = lista_1.copy()
mezcla.extend(lista_2)
mezcla.sort()
print(f'Lista 1: {lista_1}')
print(f'Lista 2: {lista_2}')
print(f'Mezcla: {mezcla}')
| false |
e7e77532f52f3bf96455b8ee99396458e880cb9b | enzostefani507/python-info | /Funciones/Complementarios/Complementario4.py | 945 | 4.15625 | 4 | """Ejercicio 4: Mediana de tres valores
Escriba una función que tome tres números como parámetros y devuelva el valor medio de esos parámetros como resultado.
Incluya un programa principal que lea tres valores del usuario y muestre su mediana.
Sugerencia: El valor medio es el medio de los tres valores cuando se ordenan en orden ascendente.
Se puede encontrar usando declaraciones if, o con un poco de creatividad matemática."""
def mediana(*argv):
datos = list(argv)
datos.sort()
if len(datos)%2 != 0:
mediana = datos[len(datos)//2]
else:
mediana = datos[len(datos)//2]+datos[(len(datos)//2)-1]
mediana = mediana / 21
return mediana
valor1 = int(input("Ingrese un valor: "))
valor2 = int(input("Ingrese otro valor: "))
valor3 = int(input("Ingrese otro valor: "))
print("La media de los valores {},{},{} es {}".format(valor1,valor2,valor3,mediana(valor1,valor2,valor3))) | false |
d53787419a05c209820d093634c65bb611dad43b | cristinarivera/python | /88 mayusculas minusculas.py | 576 | 4.28125 | 4 | #Programa que nos dice si una letra es mayuscula o minuscula.
letra= raw_input('Dame un caracter: ')
if letra>='a':
if letra=='a' or (letra=='e' or (letra=='i' or (letra=='o' or letra=='u'))):
print 'Es vocal minuscula'
else:
if letra<='z':
print 'Es minuscula'
if letra>='A':
if letra=='A' or (letra=='E' or (letra=='I' or (letra=='O' or letra=='U'))):
print 'Es vocal mayuscula'
else:
if letra<='Z':
print 'Es mayuscula'
else:
print 'Es otro tipo de caracter'
| false |
60267fcab54ee1e742c9310db31443c53eb56df5 | cristinarivera/python | /184 números binarios bis.py | 325 | 4.125 | 4 | bits=raw_input('Dame un numero binario: ')
for bit in bits:
valor=0
if bit!='1' or bit!='0':
print 'Numero binario mal formado'
bits=raw_input('Dame un numero binario: ')
if bit=='1' or bit=='0':
valor+=valor+int(bit)
print 'Su valor decimal es' , valor
| false |
35e6b2d8cddef27fff93d9ae51fb0b6cf30e4185 | ivansangines/Deep-Learning | /Assignment1_Sangines/PythonExamples/PythonExamples/First.py | 1,262 | 4.1875 | 4 | from math import pi
import sys
def computeAvg(a,b,c) :
return (a + b + c)/3.0;
def doComplexMath() :
num1 = 3 + 4j
num2 = 6 + 3.5j
res = num1 * num2
return res;
def mapTest(mylist) :
ys = map(lambda x: x * 2, mylist)
#ys is a map object, so we need to convert it to a list
result = []
for elem in ys:
result.append(elem)
return result
def main():
#Simple math
print("Result = ",computeAvg(5,8,9))
print("Result = ",doComplexMath())
#working with strings
s1 = "hello"
s2 = s1.upper()
print(s1 + "\n" + s2)
s3 = "hello there how are you"
pos = s3.find('how')
print("index: " + str(pos)) #should print index 12
s4 = 'helllo'
s5 = s1[0:3]
print(s5)
snum = "25"
num1 = int(snum)
print(num1 + 1)
snum2 = "25.5"
num2 = float(snum2)
print(num2 + 1)
#list and tupples examples
fruits = ['apples', 'oranges', 'bananas', 'plums', 'pineapples']
print(fruits)
pfruits = fruits[2:4]
print(pfruits)
for fr in pfruits :
print(fr)
del fruits[2]
fruits.remove('oranges')
fruits.append('kiwi')
print(fruits + pfruits)
s1 = ('john','starkey',12341,3.5) # firstname, lastname, id, gpa
print(s1[1])
#map and lambda functions
ys = mapTest([5,7,2,6])
print(ys)
if __name__ == "__main__":
sys.exit(int(main() or 0))
| false |
cd23ce139de38af256c594434e90b9e65a6ec98d | eloyekunle/python_snippets | /others/last_even_number.py | 587 | 4.25 | 4 | # An algorithm that takes as input a list of n integers and finds the location of the last even integer in the
# list or returns 0 if there are no even integers in the list.
def last_even_number(numbers):
index = None
for i in range(len(numbers)):
if numbers[i] % 2 == 0:
index = (numbers[i], i)
return index
nums = list(
map(int, input("Enter a sequence of numbers, separated by space: ").split())
)
last_even = last_even_number(nums)
if last_even:
print("The last even number is", last_even[0], "at index", last_even[1])
else:
print(0)
| true |
ad17e4a130882a927f4c2fe2f02aa4a29bf03682 | eloyekunle/python_snippets | /search/ternary_search.py | 1,130 | 4.375 | 4 | # The ternary search algorithm locates an element in a list
# of increasing integers by successively splitting the list into
# three sublists of equal (or as close to equal as possible)
# size, and restricting the search to the appropriate piece.
def ternary_search(key, numbers):
i = 0
j = len(numbers) - 1
while i < j - 1:
low = i + (j - i) // 3
upper = i + 2 * (j - i) // 3
if key > numbers[upper]:
i = upper + 1
print(numbers[i : j + 1])
elif key > numbers[low]:
i = low + 1
j = upper
print(numbers[i : j + 1])
else:
j = low
print(numbers[i : j + 1])
if key == numbers[i]:
location = i
elif key == numbers[j]:
location = j
else:
location = 0
return location
search_list = list(
map(int, input("Enter sorted numbers, separated by space: ").split())
)
search_key = int(input("Enter number to search for: "))
index = ternary_search(search_key, search_list)
message = "Index = " + str(index) if index >= 0 else "Item not found"
print(message)
| true |
cf85ebff256f4345d2bd59332acf4cfe21b30a81 | wagnersistemalima/Algoritimos-importantes-Python | /pacote dawload/Projetos de algoritimo em Python/Algoritimo para descobrir o fatorial Função.py | 501 | 4.21875 | 4 | # 3.
# Considere o fatorial de um número n como a multiplicação dos números de 1 a n.
# Assim, para n = 5, o fatorial de 5 é 5 * 4 * 3 * 2 * 1 = 120.
# Implemente uma função chamada fatorial(n) usando For. Ela recebe um valor n retorna o seu fatorial.
def fatorial(n):
calculo = 1
for c in range(n, 0, -1):
calculo = calculo * c
return calculo
numero = int(input('Digite um número para calcular seu fatorial: '))
print(f'O fatorial do número é {fatorial(numero)}')
| false |
5c8922df6c04bdc6d16903a96e8efee04537443a | Mona6046/python | /practicepython/Fibonacci.py | 418 | 4.125 | 4 | #Fibonacci
#length of Fibonacci series
length=input("Enter the length of Fibonacci series")
series=[]
def nextFibonacci(lastNumber,secondLastNumber):
return lastNumber+secondLastNumber
lastNumber=1
secondLastNumber=0
count=0
while(count<int(length)):
series.append(lastNumber)
temp=nextFibonacci(lastNumber,secondLastNumber)
secondLastNumber=lastNumber
lastNumber=temp
count+=1
print(series) | true |
51c7cdf895daf7909396c98145de469e35e384a4 | Mona6046/python | /practicepython/Palindrome.py | 425 | 4.53125 | 5 | #Ask the user for a string and print out whether this string is a palindrome or not
def isPalandrome(string):
#reverse String
reverseString=string[::-1]
if(string==reverseString):
return True
return False
#ask for input string
inputString=input("Enter the string :")
flag=isPalandrome(inputString)
if(flag==True):
print ("String is palindrome")
else:
print ("String is not palindrome")
| true |
fefaf855f502ac0318244a948d76faa02acb5469 | black-star32/cookbook | /2/2.2.2.py | 2,030 | 4.15625 | 4 | # 检查字符串开头或结尾的一个简单方法是使用 str.startswith()
# 或者是 str.endswith() 方法。
filename = 'spam.txt'
print(filename.endswith('.txt'))
print(filename.startswith('file:'))
url = 'http://www.python.org'
print(url.startswith('http:'))
# 检查字符串开头或结尾的一个简单方法是使用 str.startswith()
# 或者是 str.endswith() 方法。
import os
filenames = os.listdir('.')
print(filenames)
print([name for name in filenames if name.endswith('1.2.py')])
print(any(name.endswith('.py') for name in filenames))
from urllib.request import urlopen
def read_data(name):
if name.startswith(('http:', 'https:', 'ftp')):
return urlopen(name).read()
else:
with open(name) as f:
return f.read()
# 奇怪的是,这个方法中必须要输入一个元组作为参数。
# 如果你恰巧有一个 list 或者 set 类型的选择项,
# 要确保传递参数前先调用 tuple() 将其转换为元组类型。
choices = ['http:', 'ftp:']
url = 'http://www.python.org'
# print(url.startswith(choices))
print(url.startswith(tuple(choices)))
# startswith() 和 endswith() 方法提供了一个非常方便的方式
# 去做字符串开头和结尾的检查。 类似的操作也可以使用切片来实现,
# 但是代码看起来没有那么优雅。
filename = 'spam.txt'
print(filename[-4:] == '.txt')
url = 'http://www.python.org'
print( url[:5] == 'http:' or url[:6] == 'https:' or url[:4] == 'ftp:')
# 正则表达式去实现,这种方式也行得通,但是对于简单的匹配实在是有点小材大用了,
# 本节中的方法更加简单并且运行会更快些。
import re
url = 'http://www.python.org'
res = re.match('http:|https:|ftp:', url)
print(res)
# 和其他操作比如普通数据聚合相结合的时候 startswith() 和 endswith() 方法是很不错的。
# 比如,下面这个语句检查某个文件夹中是否存在指定的文件类型:
# if any(name.endswith(('.c', '.h')) for name in listdir(dirname)): | false |
bab6b20b217df90aa53245a9188ac8744ba69082 | learndevops19/pythonTraining-CalsoftInc | /training_assignments/Day_05/ExceptionHandling/Day05_Excp_Assignment3.py | 955 | 4.21875 | 4 | '''
3. Complete the below program to run successfully:
a. Write user defined exception class for User_defined_exception1, User_defined_exception2
b. Handle the user defined exception writing #appropriate message to user
# we need to guess this alphabet till we get it right
'''
alphabet = 'k'
class SmallerAlphabetException(Exception):
def __init__(self,msg):
self.msg = msg
class GreaterAlphabetException(Exception):
def __init__(self,msg):
self.msg = msg
while True:
try:
foo = input( "Enter an alphabet: ")
if foo < alphabet:
raise SmallerAlphabetException("Entered alphabet {} is smaller than alphabet {}".format(foo,alphabet))
elif foo > alphabet:
raise GreaterAlphabetException("Entered alphabet {} is greater than alphabet {}".format(foo,alphabet))
except SmallerAlphabetException as sae:
print(sae)
except GreaterAlphabetException as gae:
print(gae)
else:
print("Congratulations! You guessed it correctly.")
| true |
16a1aeb6af9b419aee184b8d7ea1d38db887d964 | learndevops19/pythonTraining-CalsoftInc | /training_assignments/Day_01/Bhairavi_Alurkar/data_types_8.py | 342 | 4.15625 | 4 | #!/usr/bin/python
"""
Python program to add the 10 to all the values of a dictionary.
"""
def add_10_to_each_value():
sample_input = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
for each in sample_input:
sample_input[each] += 10
return sample_input
if __name__ == "__main__":
res = add_10_to_each_value()
print(res)
| true |
f9c58f1338d19540bcff6478b4e52eb5b1d56734 | learndevops19/pythonTraining-CalsoftInc | /Day_04/Sample_Codes/sample_generator_expression.py | 205 | 4.3125 | 4 | # Initialize the list
my_list = [1, 3]
# List comprehension
lst = [x ** 2 for x in my_list]
print(lst)
# Generator Expression
gen = (x ** 2 for x in my_list)
print(gen)
print(next(gen))
print(next(gen))
| true |
2e2491a162c69e4682738bc5a915b5f8adf7d3be | learndevops19/pythonTraining-CalsoftInc | /training_assignments/Day_03/circle.py | 402 | 4.25 | 4 |
import math
from math import pi
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return (pi * math.pow(self.radius,2))
if __name__ == "__main__":
print("Enter the radius of circle: ",end = " ")
radius = int(input("Enter radius of circle: "))
circle1 = Circle(radius)
print("Area of circle is : {}".format(circle1.area())) | true |
4c4b7384a09a591938f114853701218ce801fa44 | learndevops19/pythonTraining-CalsoftInc | /Day_03/sample_class_and_object.py | 1,679 | 4.8125 | 5 | #!/usr/bin/env python
"""
Program shows how Class and Object are work in Python
"""
class Employee:
"""
Class Employee with employee name and pay details
"""
# Constructor
def __init__(self, first, last, pay):
"""
Initialize method
:param first: Employee first name
:param last: Employee last name
:param pay: Employee salary
"""
self.first = first
self.last = last
self.pay = pay
# instance method
def get_fullname(self):
"""
Instance method to show full name of Employee
:return: Full name of Employee
"""
return f"Fullname: {self.first} {self.last}"
# representation of object
def __repr__(self):
"""
Magic method for representational format of object
:return: reprasentation in 'First - Last' name
"""
return f"Representation: {self.first} - {self.last}"
if __name__ == "__main__":
# creating object of Employee class
emp_1 = Employee("John", "Lee", 10000)
emp_2 = Employee("David", "Smith", 20000)
# instance method call
print(emp_1.get_fullname())
print(emp_2.get_fullname())
# using repr we can have representation of object when we print
print(emp_1)
print(emp_2)
# Type of object
print(type(emp_1))
# Checking object belongs to which class
if isinstance(emp_1, Employee):
print("Employee object")
else:
print("Non employee")
# memory locations for each object
print(id(emp_1), id(emp_2))
# Documentation string(Doc string)
print("Doc string", emp_1.__doc__)
print(help(emp_1))
| true |
33cb5b2cf89af347803c101abededa4c8e1bfc9d | learndevops19/pythonTraining-CalsoftInc | /training_assignments/Day_01/Bhairavi_Alurkar/data_types_10.py | 375 | 4.3125 | 4 | #!/usr/bin/python
"""
Python program to print second largest number
"""
def find_second_largest_number():
sample_input = [-8]
new_list = list(set(sample_input))
if len(new_list) >= 2:
new_list.sort()
return new_list[-2]
else:
return new_list[0]
if __name__ == "__main__":
res = find_second_largest_number()
print(res)
| true |
24ac2c73db874648bfe0d9098e2cacaf32545876 | learndevops19/pythonTraining-CalsoftInc | /training_assignments/Day_03/ClassAbstarctOperation.py | 1,148 | 4.375 | 4 |
from abc import ABC, abstractmethod
class AbstractOperation(ABC):
def __init__(self,operand1, operand2):
self.op1 = operand1
self.op2 = operand2
@abstractmethod
def operation(self):
return None
class Addition(AbstractOperation):
def __init__(self,op1,op2):
super().__init__(op1,op2)
def operation(self):
return self.op1 + self.op2
class Subtraction(AbstractOperation):
def __init__(self,op1,op2):
super().__init__(op1,op2)
def operation(self):
return self.op1 - self.op2
class Multiplication(AbstractOperation):
def __init__(self,op1,op2):
super().__init__(op1,op2)
def operation(self):
return self.op1 * self.op2
if __name__ == "__main__":
add = Addition(5,5)
subtract = Subtraction(10,5)
multiply = Multiplication(5,5)
print("Addition of {} and {} is {}".format(add.op1,add.op2,add.operation()))
print("Subtraction of {} and {} is {}".format(subtract.op1,subtract.op2,subtract.operation()))
print("Multiplication of {} and {} is {}".format(multiply.op1,multiply.op2,multiply.operation()))
| false |
7f3d40b3e6db391218e051b870cd2213612912fb | learndevops19/pythonTraining-CalsoftInc | /Day_01/sample_flow_control.py | 1,287 | 4.125 | 4 | # Flow Control example
# if, elif else example
x = "one"
if x == "one":
print("one is selected")
elif x == "two":
print("two is selected")
else:
print("Something else is selected")
# if -- else:
if x == "one":
print("one is selected")
else:
print("Something else is selected")
for i in in range(2, 100, 2);
# prints a list of even numbers uptil 98
# Note: 100 is exclusive in range function
print(i)
# Use of break statement inside loop
for val in "string":
if val == "i":
break
print(val)
print("The end")
# Program to show the use of continue statement inside loops
for val in "string":
if val == "i":
continue
print(val)
print("The end")
# In this program,
# we check if the number is positive or
# negative or zero and
# display an appropriate message
num = 3.4
# Try these two variations as well:
# num = 0
# num = -4.5
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
# With example to open a file
with open('output.txt', 'w') as f:
f.write('Hi there!')
# Function example:
def is_prime(num):
for i in range(2, int(num/2)+1):
if num % i == 0:
break
else:
return True
return False
| true |
2886a20c5d07a53e536f94750c7aee68f24ea8f2 | learndevops19/pythonTraining-CalsoftInc | /Day_07/sample_asyncio_doesnot_reduce_cpu_time.py | 801 | 4.28125 | 4 | """
Module to understand time performance impact using asyncio for CPU extensive operations
"""
import asyncio
import time
COUNT = 50000000 # 50 M
async def countdown(counter):
"""
function decrements counter by one each time, until counter becomes zero
Args:
counter (int): counter value
"""
while counter > 0:
counter -= 1
async def main():
"""
async function to create tasks and run them at same time
"""
task1 = asyncio.create_task(countdown(COUNT // 2))
task2 = asyncio.create_task(countdown(COUNT // 2))
start = time.time()
# Start both tasks at same time
await task1
await task2
end = time.time()
print("Time taken in seconds -", end - start)
if __name__ == "__main__":
asyncio.run(main())
| true |
bd8e6a35ac8394229a5cfc596d2bda9be673ca1a | learndevops19/pythonTraining-CalsoftInc | /training_assignments/Day_01/Nitesh_Mahajan/assignment_1.py | 1,149 | 4.59375 | 5 | #!usr/bin/env python
"""
This program generates factorial or fibonacci series based on user inputs
"""
def find_factorial():
"""
This function takes a number from user and generates it factorial
Args:
Returns:
"""
num = int(input("Enter number to find factorial:"))
factorial = num
for i in range(1, num):
factorial = factorial*i
print("Factorial is: {}".format(factorial))
def find_fibonacci():
"""
This function takes a count from user and generates it fibonacci series upto the count
Args:
Returns:
"""
count = int(input("Enter count to generate fibonacci series:"))
fibb = [1]
total = 0
while len(fibb) < count:
total += fibb[-1]
fibb.append(total)
total = fibb[-2]
print("Fibonacci Series is: {}".format(fibb))
if __name__ == '__main__':
print("1: Generate Factorial")
print("2: Generate Fibonacci series")
choice = input("Enter operation to perform:")
if choice == '1':
find_factorial()
elif choice == '2':
find_fibonacci()
else:
print("Invalid selection! Please enter 1 or 2") | true |
7a93506cd68520d63eb4106ea3a107965772aed5 | learndevops19/pythonTraining-CalsoftInc | /training_assignments/Day_03/solution_01.py | 260 | 4.21875 | 4 | import math
class Circle:
def area_of_circle(radius):
return (math.pi*(math.pow(radius,2)))
if __name__ == '__main__':
radius = int(input('Enter the radius of circle'))
print('area of circle is {}'.format(Circle.area_of_circle(radius))) | true |
9a859b29234323955e4c023cd9384819ccee01eb | learndevops19/pythonTraining-CalsoftInc | /Day_01/sample_list_operations.py | 1,132 | 4.40625 | 4 | """List operations"""
fruits = ["orange", "apple", "pear", "banana", "apple"]
print("value of list: ", fruits)
fruits.append("grape") # append element at end
fruits.insert(0, "kiwi") # insert element at 0th index
print("fruits after fruits.append('grape') & fruits.insert(0, 'kiwi'): ", fruits)
fruits.extend(["orange", "pear"]) # takes iterable and extend the list
print("fruits after fruits.extend(['orange', 'pear'])", fruits)
print("fruits.count('apple'): ", fruits.count("apple"))
# list.copy() - returns swallow copy of list
fruits_new = fruits.copy()
fruits_new.append("mango")
print(f"fruits_new: {fruits_new} and fruits: {fruits}")
print(
"fruits after fruits.sort():", fruits.sort()
) # sort in ascending default if 'reverse=True' then descending
fruits.remove("apple") # removes 1st occurence
print("fruits after fruits.remove('apple'): ", fruits)
print("result of fruits.pop(1): ", fruits.pop(1))
print("fruits after fruits.pop(1): ", fruits) # if no index then removes last
fruits.clear()
print("after fruits.clear(): ", fruits) # empty the list
del fruits
print("after 'del fruits': ", fruits) # NameError
| true |
b97b17a502db05b99a82e2ddd612083cac4a06cb | learndevops19/pythonTraining-CalsoftInc | /training_assignments/Day_02/Nitesh_Mahajan/assignment_1.py | 547 | 4.34375 | 4 | def func(*args, a=[]):
a.append(args)
print(id(a))
print(a)
func(1, 2, 3)
"""A new list 'a' is created with default value [] and
all the arguments packed in a tuple because of *args will get append in the list"""
func(7, 8, 9, a=[])
"""As we are passing a list again, it will create a new list 'a' again
and will append new args to this list instead of first created list"""
func(8, 9, 10)
"""This time we are not passing the the list 'a' hence it will consider the default list in the function
and will append new *args to it"""
| true |
2a2ffe2a607939a4a05daf20808a2477145182d9 | learndevops19/pythonTraining-CalsoftInc | /training_assignments/Day_03/ques4.py | 1,016 | 4.1875 | 4 | from abc import ABC, abstractmethod
class AbstractOperation(ABC):
def __init__(self, o1, o2):
self.o1 = o1
self.o2 = o2
def operation(self):
pass
class Add(AbstractOperation):
def __init__(self, o1, o2):
super().__init__(o1, o2)
def operation(self):
return self.o1+self.o2
class Sub(AbstractOperation):
def __init__(self, o1, o2):
super().__init__(o1, o2)
def operation(self):
return self.o1-self.o2
class Mul(AbstractOperation):
def __init__(self, o1, o2):
super().__init__(o1, o2)
def operation(self):
return self.o1*self.o2
class Div(AbstractOperation):
def __init__(self, o1, o2):
super().__init__(o1, o2)
def operation(self):
return self.o1/self.o2
if __name__ == '__main__':
add = Add(1, 2)
print(add.operation())
sub = Sub(1, 2)
print(sub.operation())
mul = Mul(1, 2)
print(mul.operation())
div = Div(1, 2)
print(div.operation())
| false |
ad17413c509743100ac3695ae4999576ecc30f76 | learndevops19/pythonTraining-CalsoftInc | /training_assignments/Day_01/kshipra_namjoshi/select_operation.py | 1,243 | 4.40625 | 4 | """
Module to choose function and perform operation for the specified user input.
"""
import math
def generate_factorial(num):
"""
Calculates factorial of a number.
Args:
num: Number whose factorial is to be calculated.
"""
print(f"Factorial of {num} is {math.factorial(num)}.")
def fibonnaci(num):
"""
Calculates fibonacci series.
Args:
num: Count till which fibonacci is to be calculated.
"""
fibo_series = []
count = 0
n1 = 0
n2 = 1
if num < 0 or num == 0:
print("Invalid choice")
elif num == 1:
print(f"Fibonacci series upto {num} is [{num-1}].")
else:
while count < num:
fibo_series.append(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
print(f"Fibonacci series upto {num} is {fibo_series}.")
if __name__ == '__main__':
choice = str(input("Enter function to perform:"))
if choice not in ["factorial", "fibonacci"]:
print("Invalid choice.")
else:
num = int(input("Number to perform function on:"))
if choice == "factorial":
generate_factorial(num)
elif choice == "fibonacci":
fibonnaci(num)
| true |
7f1663fd43a3b34d9f6159bcd27bc1cda6eadc9c | andy90009/pythonLearn | /lesson01/sorted.py | 1,026 | 4.40625 | 4 |
# sorted()
# 排序算法
# 排序也是在程序中经常用到的算法。无论使用冒泡排序还是快速排序,排序的核心是比较两个元素的大小。
# 如果是数字,我们可以直接比较,但如果是字符串或者两个dict呢?直接比较数学上的大小是没有意义的,
# 因此,比较的过程必须通过函数抽象出来
# sorted()函数就可以对list进行排序
print (sorted([36, 5, -12, 9, -21]))
# sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序,例如按绝对值大小排序
# key指定的函数将作用于list的每一个元素上,并根据key函数返回的结果进行排序
print (sorted([36, 5, -12, 9, -21],key=abs))
print (sorted(['bob', 'about', 'Zoo', 'Credit']))
print (sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower))
# 进行反向排序,不必改动key函数,可以传入第三个参数reverse=True
print (sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)) | false |
36a86e3737d5a7d868c2a77b3e512a6599e7c317 | rachelli12/Module8 | /more_fun_with_collections/dictionary_update.py | 1,648 | 4.4375 | 4 | """
Program: name: dictionary_update.py
Author: Rachel Li
Last date modified: 06/27/2020
The purpose of this program is to calculate average scores using dictionary
"""
def get_test_scores():
'''
use reST style
:param scores_dict: this represents the dictionary
:param num_score: this represents the number of scores
:param score: this repesents the score
:return: this returns the score in dictionary
:keyError: this raises exception
'''
scores_dict = dict()
# prompt user to input the number of test score
try:
num_score = int(input("How many test scores? "))
if num_score < 0:
print('Invalid input')
raise ValueError
else:
for x in range(0, int(num_score)):
score = int(input('Enter test score: '))
if score < 0 and score > 100:
print("Invalid input")
raise ValueError
else:
# if input valid, add to scores_dict
# dict.update()
scores_dict.update({x : score})
except ValueError:
raise ValueError
return scores_dict
def average_scores(dict_avg):
'''
use reST style
:param dict_avg: this represents the dictionary
:return: returns the average scores in dictinoary
'''
#use len() to determine num_scores for calculation
total = 0
for score,value in dict_avg.items():
total += value
#returns average scores
return str('Average:' + str(total/len(dict_avg)))
if __name__ == '__main__':
print(average_scores(get_test_scores()))
| true |
d9c38a318ee421daa289ec14b5bfa05554830f2c | shcqupc/Alg_study | /AIE23/20191102_feature_engineering/a0_python/basic_syntax/4_List.py | 630 | 4.21875 | 4 | #Insert a element
listT1=['a','b','c','d','e','f']
list = []
dic = {"name":"harry"} #json
listT1.append('g') # at the end of the list
print("1st")
print(listT1)
listT1=['a','b','c','d','e','f']
listT1.insert(0,'0') # at the particular position
print("2nd")
print(listT1)
#Clear the position
listT1=['a','b','c','d','e','f']
print("3rd")
del listT1[0]
print(listT1)
#Remove the element
listT1=['a','b','c','d','e','f']
print("5th")
listT1.remove('b')
print(listT1)
#Length of the list
print("6th Length of the list:")
print(len(listT1))
#Range func.
print("7th Length of the list:")
listT3=list(range(2,10,2))
print(listT3)
| false |
0498fe45d30127d7e290df70e7a582d675855ea3 | shreeyamaharjan/Assignment | /Functions/QN17.py | 257 | 4.15625 | 4 | result = (lambda c: print("The string starts with given character") if c.startswith(ch) else print(
"The string doesnot start with given character"))
ch = input("Enter any character : ")
string = str(input("Enter any string : "))
print(result(string))
| true |
83dc56455d5a17ad6f8918f411a1216a94368709 | YutoNakanishi/python_text | /bmi.py | 443 | 4.1875 | 4 | #BMI判定プログラム
wight = float(input("体重(kg)は?"))
height = float(input("身長(cm)は?"))
#BMIの計算
height = height / 100
bmi = wight / (height * height)
#BMIの値に応じて結果を分岐
result = ""
if bmi < 18.5:
result = "ヤセ型"
#if(18.5 <= bmi) and (bmi < 25):
if(18.5 <= bmi < 25):
result = "標準"
if 25 <= bmi:
result = "でぶ"
#結果を表示
print("BMI :",bmi)
print("判定 :",result)
| false |
6f55859a819e8f17a5a61ee9f93373b7857d6044 | benben123/algorithm | /myAlgorithm/py/TwoPointer/isPalindrome.py | 1,080 | 4.25 | 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: false
"""
class Solution:
def isPalindrome2(self, s):
"""
:type s: str
:rtype: bool
note: start < end is very important inside the second while loop
"""
start, end = 0, len(s) - 1
while start < end:
while start < end and not s[start].isalpha() and not s[start].isdigit():
start += 1
while start < end and not s[end].isalpha() and not s[end].isdigit():
end -= 1
if s[start].lower() == s[end].lower():
start += 1
end -= 1
else:
return False
return True
if __name__ == "__main__":
lst = "A man, a plan, a canal: Panama"
test = Solution().isPalindrome2(lst)
print test | true |
f517ae85c0fd7014784ddda976194f084d8b4166 | runmeat6/ETF-Comparator | /_0_read_data.py | 1,052 | 4.1875 | 4 | """
This file has the function to read in the data
Key to naming conventions:
camelCase global (and imported) variables and function parameters
CamelCase class names
snake_case variables not intended to be used globally and function names
"""
import csv
def load_data_with_csv(fileName, delimiterCharacter=',', headerRowsToSkip=1):
"""
By default, this function reads comma separated value data
and skips one header row
It takes parameters:
fileName (path included as part of it)
and optionally:
delimiterCharacter (data separation character)
headerRowsToSkip (number of rows at the head that are not part of the data)
It returns a list slice starting after the headerRowsToSkip through the end
"""
csv_list = None # establish the csv_list variable outside of the with scope
with open(fileName, encoding='utf-8') as csv_file:
csv_data = csv.reader(csv_file, delimiter=delimiterCharacter)
csv_list = [ row for row in csv_data ]
return csv_list[headerRowsToSkip:]
| true |
49efdb4c3b918568218cee3ded8c594e4ff13e20 | rush1007/Python-Assignment | /task3.py | 2,638 | 4.1875 | 4 | # 1. Create a list of 10 elements of four different data types like int, string, complex and float.
lst = [1, "Hello", 3.2, 2+3j, "Consultadd", 4, 5.5, 4+9j, "Training", 20]
print(lst)
# 2. Create a list of size 5 and execute the slicing structure
lst = [1, 2, 3, 4, 5]
sli = lst[2:4]
print(sli)
# 3. Write a program to get the sum and multiply of all the items in a given list.
lst = [1, 2, 3, 4, 5]
add = 0
multiply = 1
for i in range(len(lst)):
add += lst[i]
print("Addition of all the numbers in the list:", add)
for i in range(len(lst)):
multiply *= lst[i]
print("Multiplication of all the numbers in the list:", multiply)
# 4. Find the largest and smallest number from a given list.
lst = [25, 45, 15, 40, 55, 100, 1, 30, 20, 200, 0, 21, 25, -4]
max = 0
min = lst[0]
for i in range(len(lst)):
if min > lst[i]:
min = lst[i]
if lst[i] > max:
max = lst[i]
print("Max number in the list:", max)
print("Min number in the list:", min)
# 5.Create a new list which contains the specified numbers after removing the even numbers from a predefined list.
odd_lst = []
lst = [1, 2, 3, 4, 5]
for i in range(len(lst)):
if lst[i] % 2 != 0:
odd_lst.append(lst[i])
print(odd_lst)
# 6. Create a list of elements such that it contains the squares of the first and last 5 elements between 1 and 30 (both included).
lst = []
for i in range(1, 6):
lst.append(i * i)
for i in range(26, 31):
lst.append(i * i)
print(lst)
# 7. Write a program to replace the last element in a list with another list.Sample input: [1,3,5,7,9,10],
# [2,4,6,8]Expected output: [1,3,5,7,9,2,4,6,8]
lst = [1, 3, 5, 7, 9, 10]
new_lst = [2, 4, 6, 8]
lst[-1:] = new_lst
print(lst)
# 8. Create a new dictionary by concatenating the following two dictionaries: # Sample input:a={1:10,2:20}
# b={3:30,4:40}Expected output: {1:10,2:20,3:30,4:40}
a = {1: 10, 2: 20}
b = {3: 30, 4: 40}
a.update(b)
print(a)
# 9. Create a dictionary that contain numbers in the form(x:x*x) where x takes all the values between 1 and n(both 1
# and n included). Sample input:n=5 Expected output: {1:1, 2:4, 3:9, 4:16, 5:25}
x = {}
for i in range(1, 6):
x[i] = i * i
print(x)
# 10. Write a program which accepts a sequence of comma-separated numbers from console and generates a list and a
# tuple which contains every number in the form of string.
# Sample input: 34,67,55,33,12,98
# Expected output: [‘34’,’67’,’55’,’33’,’12’,’98’] (‘34’,’67’,’55’,’33’,’12’,’98’)
lst = []
tup = ()
inp = input("Enter a string of number: ")
lst.append(inp)
tup = tuple(lst)
print(lst, tup) | true |
e6e420e5ff0d52c33140ed5122e5b6aceaa7c85c | HorseSF/xf_Python | /day13/code/11-子类重写父类方法.py | 1,048 | 4.125 | 4 | # 继承的特点:如果一个类A继承自类B,有类A创建出来的实例对象都能直接使用类B里定义的方法
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def sleep(self):
print(self.name + '正在睡觉')
class Student(Person):
def __init__(self, name, age, school):
# self.name = name
# self.age = age
# 调用父分类方法的两种方式:
# 1. 父类名.方法名(self, 参数列表)
# Person.__init__(self, name, age)
# 2. 使用super
super(Student, self).__init__(name, age)
self.school = school
def sleep(self):
print(self.name + '正在课间休息时睡觉')
def study(self):
print(self.name + '正在学习')
s = Student('jerry', 20, '春田花花幼稚园')
s.sleep()
print(Student.__mro__)
# 1. 子类的实现和父类的实现完全不一样时,子类可以选择重写父类方法
# 2. 子类在父类的基础上又有更多的实现
| false |
37455f6ae7a52bbc82600ca4f920c315d51050f6 | AbhishekJunnarkar/AWS_Configuration_Eval_using_Lambda_boto3 | /pythonbasics/07_Control-statements_ifelse-elif_while_continue_break.py | 879 | 4.15625 | 4 | x = 10
y = 20
if x > y:
print('x is greater then y')
else:
print('y is greater then x')
# ------IF elif example -------#
'''
If marks are >=60, first class
if marks are <60 and >=50, second class
if marks are <50 and >=35, third class
if marks <35, failed
'''
marks = 34
if marks >= 60:
print("first class")
elif marks >= 50:
print("second class")
elif marks >= 35:
print("third class")
else:
print("Failed")
# --------while example----- #
data = 1
while data <= 10:
print(data)
data = data + 1;
# ----- Continue example------#
print('##### continue example ######')
x = [1, 2, 0, 7, 1.5]
a = 2
for data in x:
if data == 0:
continue;
a = data * a;
print(a);
# -----Break example -----#
print('##### break example ######')
x = [1, 2, 0, 7, 1.5]
a = 2
for data in x:
if data == 0:
break;
a = data * a;
print(a);
| true |
a4524689f10677f3be217bcb9af0fc07816b28d7 | Gabospa/30DaysOfCode | /day25.py | 891 | 4.25 | 4 | """
A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Given a number, n , determine and print whether it's Prime or Not prime.
Note: If possible, try to come up with a O(n**0.5) primality algorithm,
or see what sort of optimizations you come up with for an O(n) algorithm.
Be sure to check out the Editorial after submitting your code!
"""
def test_prime(number):
prime = True
sqrt = round(number ** 0.5)
if number == 1:
print('Not prime')
else:
for i in range(2,sqrt+1):
if number % i == 0:
prime = False
break
if prime == True:
print('Prime')
else:
print('Not prime')
if __name__ == '__main__':
size = int(input())
for _ in range(size):
number = int(input())
test_prime(number)
| true |
9b0b9d5e3bc8b81fe0f7f21c87c4d730833d2038 | Gabospa/30DaysOfCode | /day14.py | 977 | 4.125 | 4 | """
Complete the Difference class by writing the following:
- A class constructor that takes an array of integers as a parameter and saves it to the elements instance variable.
- A computeDifference method that finds the maximum absolute difference between any numbers in and stores it in the instance variable.
"""
class Difference:
def __init__(self, a):
self.__elements = a
# Two loop cycles that check abs diference between elements and keep the max
def computeDifference(self):
max_value = 0
for i in range(len(self.__elements)):
for j in range(i+1, len(self.__elements)):
result = abs(self.__elements[i]-self.__elements[j])
if result > max_value:
max_value = result
self.maximumDifference = max_value
# End of Difference class
_ = input()
a = [int(e) for e in input().split(' ')]
d = Difference(a)
d.computeDifference()
print(d.maximumDifference) | true |
4692f2b7be7783a84b8e0d360ef670095b56909d | venkor/Python3Learning | /ex14.py | 980 | 4.28125 | 4 | #Imports the sys module (library)
from sys import argv
#requires 2 arguments to run
script, user_name, nickname = argv
#Our new prompt looks like this now, it's a string variable with two ">" and a space
prompt = '>> '
#Some little chit-chat with the user - using formatting to input the variables given when running script
print(f"Hi {user_name}, I'm the {script} script.")
print("I'd like to ask you a few questions.")
print(f"Do you like me {user_name}?")
likes = input(prompt)
print(f"Heard, that they call you {nickname} in da hood, right?")
#Asking some additional information, using formatting
print(f"Where do you live {user_name}?")
lives = input(prompt)
print("What kind of computer do you have?")
computer = input(prompt)
#printing the summary of what have been gathered from the user. 3 quotes are used with formatting.
print(f"""
Alright, so you say {likes} about liking me.
You live in {lives}. Not sure where that is.
And you have {computer} computer. Nice.
""")
| true |
d189a891c35afa86029c686d28a7dc5b418a8401 | venkor/Python3Learning | /ex37_Old_Style_String_Formats.py | 1,360 | 4.25 | 4 | print("""
OLD STYLE STRING FORMATS:
---------------------------------
Escape: Description: Example:
% d Decimal integers (not floating point). "%d" % 45 == '45'
% i Same as %d. "%i" % 45 == '45'
% o Octal number. "%o" % 1000 == '1750'
% u Unsigned decimal. "%u" % -1000 == '-1000'
% x Hexadecimal lowercase. "%x" % 1000 == '3e8'
% X Hexadecimal uppercase. "%X" % 1000 == '3E8'
% e Exponential notation, lowecase 'e'. "%e" % 1000 == '1.000000e+03'
% E Exponential notation, uppercase 'E'. "%E" % 1000 == '1.000000E+03'
% f Floating point real number. "%f" % 10.34 == '10.340000'
% F Same as %f. "%F" % 10.34 == '10.340000'
% g Either %f or %e, whichever is shorter. "%g" % 10.34 == '10.34'
% G Same as %g but uppercase. "%G" % 10.34 == '10.34'
% c Character format. "%c" % 34 == '""'
% r Repr format(debugging format). "%r" % int =="<type 'int'>"
% s String format. "%s there" % 'hi' == 'hi there'
% % A percent sign. "%g%%" % 10.34 == '10.34%'""")
| false |
2b336be9bcf0c54898aa3c08669770fd875ef347 | rahdirs11/CodeForces | /python/capitalize.py | 223 | 4.125 | 4 | # this is basically to perform capitalize operation where
# you have to make just the first letter upper-case
word = input().lstrip()
try:
print(word if word[0].isupper() else word[0].upper() + word[1: ])
except:
pass
| true |
b408bdfea6160eb710eaf8cf126ecd7bea3848ad | lastduxson/Early-Python-Code | /test.py | 244 | 4.15625 | 4 | # Code for Assignment01
#
print("Please enter your name as instructed below")
first = input("What is your first name? ")
last = input("What is your last name? ")
print("Thank you ",first,last)
input("Press ENTER to end this interview")
| true |
2665ed95928f883516190c7668d9dd21e3cefc3f | aman003malhotra/FlaskTwitterClone | /shopping_cart.py | 254 | 4.125 | 4 | num_of_items = int(input("Enter How many items did you buy?"))
sum = 0
for i in range(1, num_of_items):
amount = int(input("What is the amount of the {} item".format(str(i))))
sum += amount
print("The total price of all the items is {}$".format(sum)) | true |
31d92732ea298e8cf28b9ab55cb9000055787fe0 | TriniBora/ISFDyT166 | /ProgramaciónOrientadaObjetos/RepasoPython/Funciones/Ejercicio1.py | 1,131 | 4.125 | 4 | '''Escribir una función que calcule el área de un círculo y otra que calcule el volumen de un
cilindro usando la primera función.'''
import math
def calcular_area(radio):
'''La función calcular_area recibe un valor numérico y devuelve el área del circulo cuyo radio es dicho valor numérico.'''
return math.pi * math.pow(radio, 2)
def calcular_volumen(radio, altura):
'''La función calcular_volumen recibe dos valores numéricos, que representan radio y altura de un cilindro respectivamente. Llama a la función calcular_area y luego calcula el volumen del cilindro.'Retorna el volumen del cilindro.'''
area = calcular_area(radio)
return area * altura
#MAIN
radio = float(input("Ingrese un valor numérico que indique el radio del círculo: "))
altura = float(input("Ingrese un valor numérico que indique la altura del cilindro: "))
area = calcular_area(radio)
print(f'El área del círculo de radio {radio} es {area:.2f} unidades cuadradadas.')
volumen = calcular_volumen(radio, altura)
print(f'El volumen del cilindro de radio {radio} y altura {altura} es {volumen:.2f} unidades cúbicas.') | false |
1befe27d199a33e015e531e222d190cf48f43495 | VolkRiot/LP3THW-Lessons | /lists.py | 564 | 4.125 | 4 | the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# simple for loop
for number in the_count:
print(f'This is count {number}')
for fruit in fruits:
print(f'The fruit is {fruit}')
for i in change:
print(f'The change value is {i}')
elements = []
# for i in range(0, 6):
# print(f'Adding element {i} to list')
# elements.append(i)
# Alternative is to use range function directly
elements = range(0, 6)
for i in elements:
print(f'Element in list is {i}')
| true |
30ea9900d10c5e7228ef84b2f79604e5397b6086 | jordanstarrk/DataStructures | /src/nodes.py | 1,371 | 4.53125 | 5 | # -----------------------------------------------------------
# Python3 implementation of a Node class with 3 methods.
# This Node Class is used to implement more complex data
# structures in the same directory, such as LinkedLists,
# Stacks, Queues.
#
# -----------------------------------------------------------
class Node:
def __init__(self, value, link_node=None):
self.value = value
self.link_node = link_node
def set_link_node(self, link_node):
self.link_node = link_node
def get_link_node(self):
return self.link_node
def get_value(self):
return self.value
# -----------------------------------------------------------
# Uncomment below to see an example of using the nodes.
# I create 3 Nodes, link them together, and then remove the
# middle Node.
# -----------------------------------------------------------
# # Create 3 Nodes.
# front = Node("front node")
# middle = Node("middle node")
# end = Node("end node")
# #Link 3 Nodes.
# front.set_link_node(middle) # [front] --> [middle]
# middle.set_link_node(end) # [front] --> [middle] --> [end]
# print(front.get_link_node().get_value()) # Print to see that the front Node is linked with the 'middle node'
# #Remove the 'middle' node.
# front.set_link_node(end)
# print(front.get_link_node().get_value()) # Print to see that the front Node is linked with the end Node.
| true |
704fe4dd3c0f54de4d68eaa077244bd3b07768b2 | raijelisaumailagir0383/03_RPS | /01_get_userchoice_v2.py | 635 | 4.375 | 4 | # checks user enters rock / paper / scissors
def rps_checker():
valid = False
while not valid:
# asks user to choose and puts their answer into lowercase
response = input("Choose: ").lower()
# checks user response and either returns it or asks question again
if response == "r" or response == "rock":
return "rock"
elif response == "s":
return "scissors"
elif response == "p":
return "paper"
else:
print("Please enter 'rock, paper or scissors'")
# **** main routine *****
user_choice = rps_checker()
print(user_choice)
| true |
b47f8b7cef93dca5331f9b7fd19a857e8b389a12 | mactheknight/Lab9 | /Lab9-Finished.py | 2,623 | 4.4375 | 4 | ############################################
# #
# 70pt #
# #
############################################
# Create a celcius to fahrenheit calculator.
# Multiply by 9, then divide by 5, then add 32 to calculate your answer.
# TODO:
# Ask user for Celcius temperature to convert
# Accept user input
# Calculate fahrenheit
# Output answer
print "Please enter Celcius"
UserInput = int(raw_input())
print UserInput * 9/5 + 32
############################################
# #
# 85pt #
# Who has a fever? #
############################################
# Create a for loop that will search through temperatureList
# and create a new list that includes only numbers greater than 100
myList = [102,98,96,101,100,99,103,97,98,105]
# Insert for loop here
for x in myList:
if x > 100:
print x
# This should print [102,101,103,105]
############################################
# #
# 100pt #
# Patient Diagnosis #
############################################
# Create a program that tests if patients needs to be admitted to the hospital.
# Ask the user for their temperature, and if they have been sick in the last 24 hours.
# Additionally, ask if the user has recently travelled to West Africa.
# The program should continue to run until there are no patients left to diagnose (i.e. a while loop).
# Criteria for Diagnosis:
# - A temperature of over 105F
# - A temperature of over 102F and they have been sick in the last 24 hours
# - A temperature over 100, OR they've been sick in the last 24 hours, AND they've recently travelled to West Africa.
print "What is your temperature?"
userInput = int(raw_input())
print "Have you been sick in the last 24 hours?"
userInput2 = raw_input()
print "Have you recently travelled to West Africa?"
userInput3 = raw_input()
if userInput >= 105:
print "Go to the hospital."
else:
if userInput2 == "yes" and userInput > 102:
print "Go to the hospital."
else:
if userInput > 100 or userInput2 == "yes":
print "Go to the hospital."
if userInput <= 105:
print "Good news, you can go home."
else:
if userInput2 == "no" and userInput2 < 102:
print "Good news, you can go home."
else:
if userInput3 == "no":
print "Good news, you can go home."
| true |
6934de03a1eda1c24790fde1071c2d90a5c8031e | roxana-hgh/change_number-base | /change_number-base.py | 2,807 | 4.375 | 4 | # convert postive decimal numbers to other base 2-10
# Author: Roxana Haghgoo
# get base from user
run = True
while run:
base = input(">>> Please enter the 'base' you want to convert to: ")
try:
base = int(base)
if base >= 0 and base < 11:
run = False
else:
print("\n> please type a number in range(2-10)! \n")
except:
print("\n> please type a number! \n")
# lists of powers of base numbers
list1 = [base ** i for i in range(50)]
list1.sort(reverse=True)
list2 = list1.copy()
indexs = []
# get a decimal number from user
run = True
while run:
decimal = input('>>> Please enter a decimal number: ')
try:
decimal = int(decimal)
if decimal > 0:
run = False
else:
print("\n> please type a postive number \n")
except:
print("\n> please type a number! \n")
num = decimal
# find decimal number position between power numbers and replace it, and subtract main number
for i in list1:
if num >= i:
indexs.append(list1.index(i))
list2[list1.index(i)] = num // i
num = num % i
continue
# replace numbers that didnt change with 0
for i in range(len(list2)):
if i not in indexs:
list2[i] = 0
# convert number to string
def not_zero():
for i in list2:
if i != 0 :
return list2.index(i)
# display
new = list2[not_zero()::]
new = map(str, new)
res = ''.join(new)
print(f'>>> The {base}-base form of {decimal} is: >>> {res}')
# -----------------------------------------------------------------------------------------------------
# old code
# # get base from user
# base = int(input("Please enter the base you want to convert to: "))
# # lists of powers of base numbers
# list1 = [base ** i for i in range(30)]
# list2 = [base ** i for i in range(30)]
# list1.sort(reverse=True)
# list2.sort(reverse=True)
# indexs = []
# # get a decimal number from user
# decimal = int(input('Please enter a decimal number: '))
# num = decimal
# # find decimal number position between power numbers and replace it, and subtract main number
# for i in list1:
# if num >= i:
# indexs.append(list1.index(i))
# list2[list1.index(i)] = num // i
# num = num % i
# continue
# # replace numbers that doesnt change with 0
# for i in range(len(list2)):
# if i not in indexs:
# list2[i] = 0
# # convert number to string to display
# def not_zero():
# for i in list2:
# if i != 0 :
# return list2.index(i)
# new = list2[not_zero()::]
# new = map(str, new)
# res = ''.join(new)
# print(f'The {base}-base form of {decimal} is: >>> {res}')
| true |
bb60c95442d8b734feb4159c2158b6cea9e03a1a | Moura93/CursoPython | /desafio3.py | 637 | 4.1875 | 4 | '''
AUTOR: Felipe Moura Wanderley
3º desafio: RECEBER PESO, ALTURA E SEXO DE 3 PESSOAS CALCULAR O IMC E APRESENTAR NA TELA OS RESULTADOS
IMC CLASSIFICAÇÃO
<18,5 Magreza
18,5~24,9 Saudável
25,0~29,9 Sobrepeso
30,0~34,9 Obesidade grau 1
35,0~39,9 Obesidade grau 2
>40 Obesidade grau 3
'''
usuario =[]
for x in range(2):
nome = str(input('Digite o nome da pessoa ' + str(x) + ': '))
peso = input('Digite o peso da pessoa: ')
altura = input('Digite a altura da pessoa: ')
sexo = str(input('Digite o sexo da pessoa: '))
imc = float(peso/(altura*altura))
pessoa = [nome, peso, altura, sexo, imc]
usuario.append(pessoa)
print()
| false |
5968f45a98d8284a6b98302579923deb3ab1425a | IngMosri/221-3_40129_DeSoOrOb | /proyecto final/search_book_menu.py | 1,853 | 4.125 | 4 | #!/usr/bin/python3
class Search_book:
def search_book_menu():
correcto=False
num=0
while(not correcto):
try:
num = int(input("choose the following option : "))
correcto=True
except ValueError:
print('Error, choose a valid option ')
return num
def show_search_book_menu():
salir = False
opcion = 0
while not salir:
print ("1. For search book")
print ("2. Exit ")
print ("choose one option ")
opcion = Search_book.search_book_menu()
if opcion == 1:
book_search = input(" Enter the name of the book: ")
# opening a text file
file1 = open("books_inventory.txt", "r")
# setting flag and index to 0
flag = 0
index = 0
# Loop through the file line by line
for line in file1:
index += 1
# checking string is present in line or not
if book_search in line:
flag = 1
break
# checking condition for string found or not
if flag == 0:
print('Book', book_search , 'Not Found')
else:
print('Book', book_search , 'Found in the Inventory')
# closing text file
file1.close()
print("Book Seach Menu")
elif opcion == 2:
print ("Option 2")
salir = True
else:
print ("Choose the option beetween 1 and 3") | true |
f2a1f7f59785a573b6c891b8f75fd0f26bbaaa6c | alankrit03/Problem_Solving | /Jump_Search.py | 1,018 | 4.125 | 4 | # Python3 code to implement Jump Search
import math
def jumpSearch(arr, x, n):
# Finding block size to be jumped
step = int(math.sqrt(n))
# Finding the block where element is
# present (if it is present)
prev = 0
while arr[int(min(step, n) - 1)] < x:
prev = step
step += int(math.sqrt(n))
if prev >= n:
return -1
# Doing a linear search for x in
# block beginning with prev.
while arr[(prev)] < x:
prev += 1
# If we reached next block or end
# of array, element is not present.
if prev == min(step, n):
return -1
# If element is found
if arr[int(prev)] == x:
return prev
return -1
# Driver code to test function
arr = input().split();
n = len(arr);
for i in range(len(arr)):
arr[i]= int(arr[i])
x=int(input())
# Find the index of 'x' using Jump Search
index = jumpSearch(arr, x, n)
# Print the index where 'x' is located
print(f"Number {x} is at index {index} ")
| true |
3a03ca36e458c2ec30ef34dcffab9c5da947feaa | rpural/DailyCodingProblem | /Daily Coding Problem/spiral.py | 1,174 | 4.4375 | 4 | #! /usr/bin/env python3
''' Daily Coding Problem
This problem was asked by Amazon.
Given a N by M matrix of numbers, print out the matrix in a clockwise spiral.
For example, given the following matrix:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]
You should print out the following:
1
2
3
4
5
10
15
20
19
18
17
16
11
6
7
8
9
14
13
12
'''
matrix = [[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]
width = len(matrix[0])
height = len(matrix)
print("width = {}, height = {}".format(width, height))
for i in matrix:
print(i)
ws = 0
hs = 0
w = width
h = height
while (ws < w) and (hs < h):
for i in range(ws, w):
print(matrix[hs][i])
hs += 1
for i in range(hs, h):
print(matrix[i][w-1])
w -= 1
for i in range(w-1, ws-1, -1):
print(matrix[h-1][i])
h -= 1
for i in range(h-1, hs, -1):
print(matrix[i][ws])
ws += 1
| true |
eca6cc3641b8600347a1ae99eafba92851ec3348 | rpural/DailyCodingProblem | /Daily Coding Problem/romanDecode.py | 1,098 | 4.125 | 4 | #! /usr/bin/env python3
''' Daily Coding Problem
This problem was asked by Facebook.
Given a number in Roman numeral format, convert it to decimal.
The values of Roman numerals are as follows:
{
'M': 1000,
'D': 500,
'C': 100,
'L': 50,
'X': 10,
'V': 5,
'I': 1
}
In addition, note that the Roman numeral system uses subtractive notation for
numbers such as IV and XL.
For the input XIV, for instance, you should return 14.
'''
numerals = {
'M': 1000,
'D': 500,
'C': 100,
'L': 50,
'X': 10,
'V': 5,
'I': 1
}
def romanDecode(xvi):
xvi = xvi.upper()
last = 0
result = 0
for n in xvi[::-1]:
try:
d = numerals[n]
except:
print("Found a non-Roman Numeral digit in the value submitted")
return -1
if d < last:
result -= d
else:
result += d
last = d
return result
while True:
roman = input("Input a value in Roman Numerals: ")
if roman == "exit":
break
print("{} would be {}".format(roman, romanDecode(roman)))
| true |
1c0baa9eb202fa02110201b4c4783ab139dcdba7 | rpural/DailyCodingProblem | /armstrong.py | 621 | 4.375 | 4 | #! /usr/bin/env python3
''' An Armstrong number is one where the sum of the cubes of the digits add
up to the number itself. Example 371 = 3**3 + 7**3 + 1**3.
'''
def isArmstrong(value):
svalue = str(value)
digits = len(svalue)
sum = 0
for i in svalue:
sum += int(i) ** digits
if sum == value:
return True
else:
return False
limit = int(input("Input the end of the desired range: "))
count = 0
for i in range(limit+1):
if isArmstrong(i):
count += 1
print("{}. {} is an Armstrong number.".format(count, i))
print("Total found: {}".format(count))
| true |
d6924fa0196457a90bb8d5d63ac6c7d0b54d53e8 | rpural/DailyCodingProblem | /Daily Coding Problem/palindromeInt.py | 687 | 4.3125 | 4 | #! /usr/bin/env python3
''' Daily Coding Problem
This problem was asked by Palantir.
Write a program that checks whether an integer is a palindrome. For example,
121 is a palindrome, as well as 888. 678 is not a palindrome. Do not convert
the integer into a string.
'''
def reverseNum(num):
result = 0
while num > 0:
digit = num % 10
result *= 10
result += digit
num //= 10
return result
def isPalindrome(num):
rnum = reverseNum(num)
if rnum == num:
return True
return False
if __name__ == "__main__":
tests = [5, 12, 22, 121, 1234321, 1324563]
for i in tests:
print(f"{i:9d} - {isPalindrome(i)}")
| true |
cea9ced7ae3899e22d61ade2f72a5c4b41cc339e | rpural/DailyCodingProblem | /multLab0.py | 480 | 4.3125 | 4 | #! /usr/bin/env python3
# Create a multiplication table for a given value, with a specified number
# of elements.
# Input the two variables
base = 5
count = 10
# The input will be text (strings), so convert the values to integers
base = int(base)
count = int(count)
# print a title for the table
print("\n\nMultiplication Table for", base)
# Loop through the count, starting at 0, and generate the table
for i in range(0, count+1):
print(base, "times", i, "=", base * i)
| true |
8444ccbe55092a6fde4645df4b237eebd4211d98 | rpural/DailyCodingProblem | /Daily Coding Problem/maxpath.py | 1,142 | 4.15625 | 4 | #! /usr/bin/env python3
''' Daily Coding Problem
This problem was asked by Google.
You are given an array of arrays of integers, where each array corresponds to a row in a triangle of numbers.
For example, [[1], [2, 3], [1, 5, 1]] represents the triangle:
1
2 3
1 5 1
We define a path in the triangle to start at the top and go down one row at a time to an adjacent value,
eventually ending with an entry on the bottom row. For example, 1 -> 3 -> 5. The weight of the path is
the sum of the entries.
Write a program that returns the weight of the maximum weight path.
'''
sample_path = [[1], [2, 3], [1, 5, 1]]
def maxpath(triangle, row=0, pos=0, sum=0, maxsum=0):
depth = len(triangle)
sum += triangle[row][pos]
if row == depth-1:
if sum > maxsum:
return sum
else:
return maxsum
if sum > maxsum:
maxsum = sum
left = maxpath(triangle, row+1, pos, sum, maxsum)
right = maxpath(triangle, row+1, pos+1, sum, maxsum)
return max(left, right, maxsum)
if __name__ == "__main__":
print(maxpath(sample_path))
| true |
fd0b869540d974a50c65192bf2cbf67f6497c446 | Endlex-net/KeepLearning-Py | /fluent_python/data_moudle/analog_vector.py | 1,508 | 4.375 | 4 | """
这个demo中模拟了一个二维的变量
"""
from math import hypot
class Vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
# def __str__(self):
# """
# str只会在print() 和 str()中被调用
# """
# return "111"
def __repr__(self):
"""
repry用在命令行的字符串标示上(应该以无歧义的形式表现)
"""
# repr 在没有实现 str的时候,会在 str 或 print 中被调用
return 'Vector(%r, %r)' % (self.x, self.y) # 这里用%r 可以体现变量原来的类型
def __abs__(self):
return hypot(self.x, self.y)
def __bool__(self):
"""
返回布尔值
"""
# 当没有__bool__函数的时候,会自动尝试调用__len__
return bool(self.x or self.y)
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Vector(x, y)
def __mul__(self, scalar):
"""
乘法实现(忽略了乘法交换律)
"""
return Vector(self.x * scalar, self.y * scalar)
def main():
print(Vector())
print(bool(Vector()))
print(bool(Vector(1, 3)))
print(Vector(1, 3) * 3)
# print(3 * Vector(4, 6))
# TypeError unsupported operand type(s) for *: 'int' and 'Vector'
# print(Vector(1, 3) * Vector(2, 4))
# TypeError: unsupported operand type(s) for *: 'int' and 'Vector'
if __name__ == '__main__':
main()
| false |
523a2bc773dbf194591fb318503722ba465dd626 | rakeshrana80/PyProject | /guessnumber.py | 1,027 | 4.3125 | 4 | #!/usr/bin/env python
#Generate a random number between 1 and 9 (including 1 and 9).
#Ask the user to guess the number, then tell them whether
#they guessed too low, too high, or exactly right.
import random,sys
def main():
rand_number = random.randint(1,9)
count = 0
choice = "yes"
while choice.lower() != "no":
guess = input("Guess the Magic Number between 1 and 9 : ")
if guess == rand_number:
count += 1
print "You guessed the correct nmber {0} in {1} attempts : WINNER !!!".format(rand_number,count)
count = 0
sys.exit()
elif guess > rand_number:
count += 1
print "You have guessed too high, sorry try again !"
choice = raw_input("Do you want to guess again? (Yes/No) :")
else:
count += 1
print "You have guessed too low, sorry try again !"
choice = raw_input("Do you want to guess again? (Yes/No) :")
if __name__ == "__main__":
main()
| true |
45327fefb0e6ef0da43049eea53e24f431472ec0 | pruebas-lau/ejemplospython | /prueba_uno.py | 1,306 | 4.21875 | 4 | nombre = "Oli"
edad =17
#print(f"Hola {nombre} tirnes {edad} ")
#nombre = input("Tu nombre: ")
#Comentario
#if edad>18:
# print("Mayor de edad")
#else:
# print('eres una ninia')
# ---CICLO FOR ---
'''
variable=5
for i in [0,1,3,9]:
print(variable, "x", i, "=", variable*i)
print()
print("Fin")
'''
# ---LISTAS---
"""frutas=["Naranja", "Pera", "Melon", "Manzana", "Platano", "Limon"]
#frutas.append("Limon")
del frutas[1]
print(len(frutas))
"""
#Funciones
"""
name=input("Escribe tu nombre: ")
def funcion_uno(name):
print(f"Hola {name}")
funcion_uno(name)
"""
#CUENTA REGRESIVA
"""
def cuenta_regresiva(numero):
numero -= 1
if numero > 0:
print(numero)
cuenta_regresiva(numero)
else:
print("Boooooooom!")
print("Fin de la función", numero)
cuenta_regresiva(5)
"""
#FACTORIAL
"""
def factorial(numero):
print("Valor inicial ->",numero)
#print(f"{numero} x")
if numero > 1:
numero = numero * factorial(numero -1)
print("valor final ->",numero)
return numero
fac=factorial(5)
print(f"Resultado: = {fac}")
"""
class OperacionesBasicas:
def suma(self):
self.n1 = 3
self.n2 = 7
objeto = OperacionesBasicas()
objeto.suma()
resultado = objeto.n1+objeto.n2
print(resultado)
| false |
8690b3af2aae3f4c2e237eee03ef94b6f46d5461 | stanCode-Turing-demo/projects | /stanCode_Projects/weather_master/weather_master.py | 2,088 | 4.40625 | 4 | """
File: weather_master.py
-----------------------
This program should implement a console program
that asks weather data from user to compute the
average, highest, lowest, cold days among the inputs.
Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
EXIT = -100
def main():
"""
This is a Temperature information processor,
which allows users input their temperature information.
At the end, it will show the highest and the lowest temperature.
It also calculates the average temperature
and the number of cold days, which represent the days under 16 degrees.
"""
print('stanCode "Weather Master 4.0"!')
n = int(input('Next Temperature: (or ' + str(EXIT) + ' to quit)? '))
highest = n
lowest = n
total = n
times = 0
cold = 0
if n == EXIT:
print('No temperature were entered.')
else:
if n < 16:
cold = add_cold(cold)
while True:
n = int(input('Next Temperature: (or ' + str(EXIT) + ' to quit)? '))
times += 1
# putting it here isn't that logical, while it could simplify the coding
if n == EXIT:
break
elif n > highest:
highest = n
total = sum_temp(total, n)
if n < 16:
cold = add_cold(cold)
elif n < lowest:
lowest = n
total = sum_temp(total, n)
if n < 16:
cold = add_cold(cold)
else:
total = sum_temp(total, n)
if n < 16:
cold = add_cold(cold)
print('Highest temperature: ' + str(highest))
print('Lowest temperature: ' + str(lowest))
print('Average = ' + str(average(total, times)))
print(str(cold) + ' cold day(s)')
def sum_temp(s, n):
"""
:param s: int, sum of total value of temperature
:param n: int, latest information to add up
:return: s + n
"""
s += n
return s
def add_cold(c):
"""
:param c: int, temp < 16 and != -100
:return: c + 1
"""
c += 1
return c
def average(a, b):
"""
:param a: int, sum of total value
:param b: int, the amount of temp information
:return: a / b
"""
avg = a / b
return avg
#
###### DO NOT EDIT CODE BELOW THIS LINE ######
if __name__ == "__main__":
main()
| true |
99091fe6b2729b61ecd90908e6549999302dd722 | stanCode-Turing-demo/projects | /stanCode_Projects/boggle_game_solver/largest_digit.py | 1,496 | 4.5625 | 5 | """
File: largest_digit.py
Name: Josephine
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
largest_dig = 0
def main():
"""
This program recursively finds and then prints the biggest digit in 5 different integers
"""
print(find_largest_digit(12345)) # 5
print(find_largest_digit(281)) # 8
print(find_largest_digit(6)) # 6
print(find_largest_digit(-111)) # 1
print(find_largest_digit(-9453)) # 9
def find_largest_digit(n):
"""
This function will call the helper function to achieve the final goal.
:param n: int, the integer
:return: int, the biggest digit in the integer
"""
global largest_dig
largest_dig = 0
# Make sure that the integer is a positive integer.
if n < 0:
n *= -1
find_largest_digit_helper(n)
return largest_dig
def find_largest_digit_helper(n):
"""
The helper function which recursively gets each digit in the integer and compare with the former one.
:param n: int, the integer
:return: nothing / the function only records the biggest digit into the 'largest_digit' variable.
"""
global largest_dig
# Base-Case
if n == 0:
return
else:
# Get each digit in n and compare it with the current biggest digit.
if n % 10 > largest_dig:
largest_dig = n % 10
# Recursion
find_largest_digit_helper(n//10)
if __name__ == '__main__':
main()
| true |
ba696d1df208c62aa461fde8dfff3c50a7a6bbe3 | nkuang123/MIT6001x | /Lesson 3/guess my number.py | 907 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 17 21:20:11 2017
@author: normankuang
@title: Lesson 3 / Exercise: guess my number
"""
highBound = 100
lowBound = 0
guess = int((highBound + lowBound) / 2)
print("Please think of a number between 0 and 100!")
while True:
guess = int((highBound + lowBound) / 2)
print("Is your secret number " + str(guess) + "?")
userInput = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
if (userInput != "h" and userInput != "l" and userInput != "c"):
print("Please enter a valid response.")
elif(userInput == 'h'):
highBound = guess
elif(userInput == 'l'):
lowBound = guess
else:
break
print("Game over. Your secret number was " + str(guess))
| true |
dbf8016beb130087b016bbdf0640f5fd657745b5 | MitsurugiMeiya/Leetcoding | /leetcode/Array/Interval/56. 区间合并.py | 1,539 | 4.25 | 4 | """
融合interval
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
注意,这题的intervals给的是没有排序过的
"""
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
if not intervals or len(intervals) == 0: return []
intervals.sort(key = lambda x: x[0])
merge = []
for interval in intervals:
# [] or [1,3] [4,5]
if not merge or merge[-1][-1] < interval[0]:
merge.append(interval)
# [1,3] [2,4]
else:
merge[-1][-1] = max(merge[-1][-1],interval[-1])
return merge
"""
https://leetcode.com/problems/merge-intervals/solution/
Time complexity : O(nlogn)
Space complexity : O(1) (or O(n))
答案:
此题思路不难
1.首先我们得先把intervals按照第一个元素的大小排序好(从小到大)
2.然后我们遍历intervals,里面有三种情况
2.1 第一种是merge[[1,3]],interval[4,5]
那么interval最小元素已经大于merge的最右边了,所以不能融合,只能添加
2.2 第二种是merge[],所以无论第一个interval是啥,直接append
2.3 第三种是merge[[1,3]],interval[2,4]
这时候我们看出来了merge最右边大于interval的最左边,所以可以融合
这时我们要确定融合后的右边界,就是max(merge:3,interval:4)
""" | false |
4c98342d2c2274393d56ed7ace2157588e8a32a8 | debojyoti-majumder/CompCoding | /2019/2019Q1/mlsnippets/linkedList.py | 2,444 | 4.1875 | 4 | # Simple Linked list implmentation to understand python
class Node:
def __init__(self, data = None):
self.data = data
self.next = None
def setNext(self, nextNode):
self.next = nextNode
def getData(self):
return self.data
def getNext(self):
return self.next
class LinkedList:
def __init__(self, head = None):
self.head = Node(head)
def addData(self, data):
if self.head != None:
iterator = self.head
# Navigate to the last node
while iterator.getNext() != None :
iterator = iterator.getNext()
iterator.next = Node(data)
else:
self.head = Node(data)
def printAll(self):
it = self.head
while it != None:
print(it.getData(), end=" ")
it = it.getNext()
# Just a new line feed
print()
def findItem(self, data):
iterator = self.head
while iterator != None:
if iterator.data == data:
return iterator
iterator = iterator.getNext()
return None
def deleteData(self, data):
# If the node is the first node
if self.head.data == data:
self.head = self.head.getNext()
elif self.head.getNext() != None:
iterator = self.head
nextNode = iterator.getNext()
while nextNode != None:
# Node found, link needs destoying
if nextNode.getData() == data:
iterator.setNext(nextNode.getNext())
# Both reference it updated
iterator = iterator.getNext()
nextNode = nextNode.getNext()
print("Testing out linked list")
myList = LinkedList(40)
# Adding some dummy data
myList.addData(23)
myList.addData(45)
myList.addData(34)
# Simple iteration
myList.printAll()
# Finding element in the list
print(myList.findItem(45))
print(myList.findItem(15))
# Removing element from the list
myList.deleteData(23)
myList.deleteData(34)
myList.printAll()
# Removing the first node
print("After head removed")
myList.deleteData(40)
myList.printAll()
print("With bad data and head removed, list should be empty")
myList.deleteData(30)
myList.deleteData(45)
myList.printAll()
print("Again adding some data")
myList.addData(10)
myList.addData(20)
myList.printAll() | true |
b3e6b79b57203ba1d3c78a632a2360f1f2ca3e48 | zeeshan-emumba/GoogleCodingInterviewQuestions | /contiguousProduct.py | 681 | 4.125 | 4 | """
Contract:
Given an integer array nums, find the contiguous subarray within an array
(containing at least one number) which has the largest product.
input = [2, 3, -2, 4]
output = [6]
input = [-2, 0, -1]
output = 0
"""
input = [2, 3, -2, 4]
input1 = [-2, 0, -1]
def contiguousProduct(input):
largestProduct = 0
largestSubarray = [0]
for x in range(1, len(input),1):
soln = input[x-1] * input[x]
if soln > largestProduct:
largestProduct = soln
largestSubarray = [input[x-1]*input[x]]
else:
pass
return largestSubarray
print(contiguousProduct(input))
print(contiguousProduct(input1))
"""
[6]
[0]
""" | true |
1a3e3d6a385727f25aaba6872a750da2ff0d458d | yuanswife/LeetCode | /src/String/最长无重复字符子串_003_longest-substring-without-repeating-characters_medium.py | 2,792 | 4.15625 | 4 | # 给定一个字符串str,返回str的最长无重复字符子串的长度。
# 举例:
# str="abcd",返回4.
# str="abcb",最长无重复字符子串为"abc",返回3.
# Given a string, find the length of the longest substring without repeating characters.
# Example:
# Given "abcabcbb", the answer is "abc", which the length is 3.
# Given "bbbbb", the answer is "b", with the length of 1.
# Given "pwwkew", the answer is "wke", with the length of 3.
#
# Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
# 最优解 Time: O(N) Space: O(N)
# 求出以str中每个字符结尾的情况下,最长无重复字符子串的长度,并在其中找出最大值返回。
#
# 哈希表map —> 其中统计了每种字符之前出现的位置
# 整型变量Pre -> 代表以s[i-1]结尾的情况下,最长无重复子串的长度。
# ---------------_c--------
# s[i-1] s[i]
# Time: O(N)
# Space: O(N)
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
res = 0
if s is None:
return res
d = {} # 借助一个辅助键值对 来存储 某个元素最后一次出现的下标。
start = 0 # 用一个整形变量存储 当前 无重复字符的子串 开始的下标。
for i in range(len(s)):
if s[i] in d and d[s[i]] >= start:
start = d[s[i]] + 1
d[s[i]] = i
res = max(res, i - start + 1)
return res
# Time: O(n)
# Space: O(1)
class Solution2(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
longest, start, visited = 0, 0, [False for _ in range(256)]
for index, c in enumerate(s):
# ord() 函数是chr()函数(对于8位的ASCII字符串)或unichr()函数(对于Unicode对象)的配对函数,
# 它以一个字符(长度为1的字符串)作为参数,返回对应的ASCII数值,或者Unicode数值
if visited[ord(c)]:
while c != s[start]: # 当前字符和前面出现过的比较 如果不相等 设为False
visited[ord(s[start])] = False # 当前字符与前面下标为start的字符比 不一样 则s[start]设为False
start += 1 # 前面需要比较的值 往后移一步
# c和前面的字符一样 start同样需要往后移一位
start += 1
else:
visited[ord(c)] = True
longest = max(longest, index - start + 1)
return longest
if __name__ == "__main__":
print(Solution().lengthOfLongestSubstring("pwwkew")) # "abcabcbb" 3 pwwkew 3
| false |
1c30dbbf12cd68578b6a7536acad2c130dd95f2a | jaimienakayama/wolfpack_pod_repo | /eva_benton/snippets_challenge.py | 2,086 | 4.5 | 4 | print("Challenge 3.1: Debug code snippets")
#Debug each snippet in order
print()
print("Code Snippet 1:")
u = 5
v = 2
if u * v == 10:
print(f"The product of u ({u}) and v ({v}) is 10")
else:
print(f"The product of u ({u}) and v ({v}) is not 10")
# This equation requires the "==" comparison operator, "=" is not sufficient.
print()
print("Code Snippet 2:")
x = 15
y = 25
z = 30
if z < x:
print("z is less than x")
elif z > x and z < y:
print("z is between x and y")
# This code is missing the ":" colon after the elif statement that continues on to the next option.
else:
print("z is greater than y")
# This code is missing the ":" colon after uthe else statement, finalizing the result options.
print()
print("Code Snippet 3:")
#modify the comparison operator below so the assert statement passes
#update the print statement to reflect changes to the code
a = 1
b = 1
c = (a >= b)
# The value 1 cannot be greater than 1, so the comparison operator needed to be adjusted.
print(f"The value of c ({c}) is True since a ({a}) is greater than b ({b}).")
assert(c == True) #Do not change this line
print()
print("Code Snippet 4:")
#modify exactly one boolean operator in the assignment of d, so that d evaluates to False
d = (5 < 7) and not (8 < 20)
# TO DO: Explain how d is set to False in a print statement
# To set d to a False statement the "or not" has to be changed to "and not", then the statement will be False.
assert(d == False) #Do not change this line
print("d wil be False when an operator is added between True and False statements.")
print()
print("Code Snippet 5:")
#modify the comparison operator so o evalutes to true
#update the print statement to reflect the changes
m = "GOAT"
n = "goat"
o = (m != n)
print (f"The value of o ({o}) is True since Python is case-sensitive.")
assert(o == True) #Do not change this line
# This is not a true statement, "m" cannot equal "n" because Python is case sensitive.
print(f"The value of o ({o}) is True since Python is case-sensitive.")
print()
print("CHALLENGE COMPLETE!")
| true |
cbd6aec64bc11eb03d3f8f5ee88dc69331223071 | Gabruuuu/Quadratic-Equation-Calculator | /Quadratic Formula.py | 615 | 4.25 | 4 | print("Quadratics calculator ")
print("Created by Gabriel Palomero")
print("Please enter A, B, and C from the standard quadratic equation")
first_number = int ( input ( " Enter 'A' : "))
second_number = int ( input ( " Enter 'B' : "))
third_number = int ( input ( " Enter 'C' : "))
import math
quadratic_formula = ((-1*second_number) + math.sqrt((second_number**2) - (4 * first_number *third_number))) / (2 * first_number)
quadratic_formula_2 = ((-1*second_number) - math.sqrt((second_number**2) - (4 * first_number *third_number))) / (2 * first_number)
print("x =", quadratic_formula, " x =", quadratic_formula_2)
| false |
7e29c21d780749e600ee8e4b7c43ad58f0601c0d | qtccz/data-python | /algorithm/heapSort.py | 2,383 | 4.28125 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
"""
6、堆排序
堆排序(Heapsort)是指利用堆积树(堆)这种数据结构所设计的一种排序算法,
它是选择排序的一种。可以利用数组的特点快速定位指定索引的元素。
堆分为大根堆和小根堆,是完全二叉树。
大根堆的要求是每个节点的值都不大于其父节点的值,即A[PARENT[i]] >= A[i]。
在数组的非降序排序中,需要使用的就是大根堆,因为根据大根堆的要求可知,最大的值一定在堆顶。
参看引用: https://www.jianshu.com/p/d174f1862601
"""
# 指定列表下标元素交换位置并返回交换位置后列表
def swap_param(lists, i, j):
lists[i], lists[j] = lists[j], lists[i]
return lists
"""
1、首先将待排序的数组构造出一个大根堆
2、取出这个大根堆的堆顶节点(最大值),与堆的最下最右的元素进行交换,然后把剩下的元素再构造出一个大根堆
3、重复第二步,直到这个大根堆的长度为1,此时完成排序。
"""
def heap_adjust(lists, start, end):
temp = lists[start]
i = start
j = 2 * i
while j <= end:
if (j < end) and (lists[j] < lists[j + 1]):
j += 1
if temp < lists[j]:
lists[i] = lists[j]
i = j
j = 2 * i
else:
break
lists[i] = temp
def heap_sort(lists):
# 因为引入了一个辅助空间,所以使L_length = len(L) - 1
lists_length = len(lists) - 1
# 第一个循环做的事情是把序列调整为一个大根堆(heap_adjust函数)
first_sort_count = lists_length // 2
for i in range(first_sort_count):
heap_adjust(lists, first_sort_count - i, lists_length)
# 第二个循环是把堆顶元素和堆末尾的元素交换(swap_param函数),然后把剩下的元素调整为一个大根堆(heap_adjust函数)
for i in range(lists_length - 1):
lists = swap_param(lists, 1, lists_length - i)
heap_adjust(lists, 1, lists_length - i - 1)
return [lists[i] for i in range(1, len(lists))]
def main():
import numpy as np
from collections import deque
deques = deque(np.random.randint(1, 100, size=10))
deques.appendleft(0)
print("堆排序前", deques)
print("堆排序后", heap_sort(deques))
if __name__ == '__main__':
main()
| false |
283f488dbc72166d00576a9cf6d5ad0c4824d65a | smartDataDev/testing | /class_example.py | 654 | 4.15625 | 4 | # class example
class MyClass:
number = 0
name = 'noname'
age = 'under 40'
def Main():
me = MyClass()
me.number = 55
me.name = 'Martin'
me.age = 40
friend = MyClass()
friend.number = 10
friend.name = 'Susan'
friend.age = 25
default = MyClass()
print('My name is ' + me.name + ' I am ' + str(me.age) + ' and my number is: ' + str(me.number))
print('My name is ' + friend.name + ' I am ' + str(friend.age) + ' and my number is: ' + str(friend.number))
print('My name is ' + default.name + ' I am ' + str(default.age) + ' and my number is: ' + str(default.number))
Main()
| false |
5fa92196a4b441bdd1a3e67c269ae94e06ce26b5 | Libardo1/Monty-Hall-Problem | /monty_hall.py | 1,442 | 4.1875 | 4 | # Setup the Monty Hall problem to run simulations.
"""
NEEDS:
3 random values, 2 = goat, 1 = car
place values into array
"""
import random
import numpy as np
def monty_hall():
GOAT = 0
CAR = 1
solution1 = 0
solution2 = 0
for x in range(10):
doors = np.array([0,0,0])
car_location = random.randint(0,2)
# Place car in a random spot.
doors[car_location] = CAR
# Door selection.
door_selected = random.randint(0,2)
# SOLUTION 1 - LESS CHANCE
# Pick a door, and stick to it
if doors[door_selected] == CAR:
solution1 += 1
# SOLUTION 2 - Reveal a door that does not have a goat, pick the OTHER door.
# Get a door with a goat in it.
for index, value in enumerate(doors):
if value != 1 and index != door_selected:
goat_door = index
# We now have a door with a goat and the door selected.
last_door = len(doors) - (goat_door + door_selected)
#print "door selected: ", door_selected
#print "car location: ", car_location
#print "goat location: ", goat_door
if doors[last_door] == CAR:
solution2 += 1
#print "SOLUTION 1: ", solution1
#print "SOLUTION 2: ", solution2
if solution1 > solution2:
return 1
elif solution1 < solution2:
return 2
else:
return 0
print monty_hall()
| true |
ac490579f4cdd5b12bd6e6736b18e8af3bc6c9a7 | mpsb/practice | /codewars/python/cw-iq-test.py | 1,275 | 4.5 | 4 | '''
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number.
! Keep in mind that your task is to help Bob solve a real IQ test, which means indexes of the elements start from 1 (not 0)
'''
def check_even(list):
even_count = 0
odd_count = 0
for i in list:
i = int(i)
if(i % 2 == 0):
even_count += 1
else:
odd_count += 1
if(even_count > 1):
return True
if(odd_count > 1):
return False
def iq_test(numbers):
num_list = list(numbers.split(' '))
counter = 1
is_even = check_even(num_list) # to check whether list majority is even or odd
if(is_even):
for i in num_list:
i = int(i)
if(i % 2 != 0):
return counter
counter += 1
else:
for i in num_list:
i = int(i)
if(i % 2 == 0):
return counter
counter += 1 | true |
c3d1d8bbb3de9ade1c28f0e4758df3097656bf6b | devmfe/Fundamental-Python-Tutorial | /SidHW/gradientcalc.py | 766 | 4.3125 | 4 | m = 0
print("WELCOME TO SID'S GRADIENT CALCULATOR!")
print("--------------------------------------------------")
c = float(input("What is the constant term of the line? (c)\n"))
print("--------------------------------------------------")
x = float(input("Ok, now what is the x-value? (x)\n"))
print("--------------------------------------------------")
y = float(input("Ok, now what is the y-value? (y)\n"))
print("--------------------------------------------------")
m = (y - c)/x
print("Alright! The gradient of your line is: {}".format(m))
print("--------------------------------------------------")
print("Also, the equation of your line is: y = {}x + {}".format(m, c))
print("--------------------------------------------------")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.