blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b8539d28bb8c021e2dab22252092ebc86e87fbaa | moamen-ahmed-93/hackerrank_sol | /python3/map-and-lambda-expression.py | 355 | 4.15625 | 4 | cube = lambda x:x**3 # complete the lambda function
def fibonacci(n):
# return a list of fibonacci numbers
if n==1:
return [0]
if n==0:
return []
fib=list()
f1=0
f2=1
fib.append(f1)
fib.append(f2)
for i in range(n-2):
f3=f2
f2=f1+f2
f1=f3
fib.append(f2)
return fib
| true |
0a42975d6dfeb38a24f24bf93567da1c400f60fc | douglasmarcelinodossantos/Douglas_lista1_Python | /lista1_7.py | 808 | 4.34375 | 4 | """ 7. Escreva um programa que, dada uma lista de números [-2, 34, 5, 10, 5, 4, 32] qualquer,
retorne: o primeiro valor, o número de valores, o último valor, a soma, a média e a mediana.
*** Obs. Para listas com tamanho ímpar, a mediana é o valor do meio, quando ordenada
(sorted()). Para listas pares, retorne os dois valores do meio."""
import statistics
lista = [-2, 34, 5, 10, 5, 4, 32]
lista = sorted(lista)
print(f' A lista ordenada é {lista};')
print(f' o primeiro item da lista é {lista[0]};')
print(f' a lista possui {len(lista)} números;')
print(f' o último item da lista é {lista[-1]};')
print(f' a soma dos itens da lista é {sum(lista)};')
print(f' a mediana da lista é {statistics.median(lista)};')
print(f' finalmente, a média dos itens da lista é {statistics.mean(lista)}.')
| false |
18a2d5d50ba9814be337ac9c51eb5efe889961fc | srikolabalaji/gitfolder | /python/nester/build/lib/nested.py | 319 | 4.25 | 4 |
#This is a print_lol module., Its used for printing for nested list
def print_lol(the_list):
for each_item in the_list:
# Nested recurvise function where it is used for if the list have the recursive list items,
if isinstance(each_item,(list)):
print_lol(each_item);
else:
print(each_item);
| true |
8d407cdb3df258c88008c9ee80457fc7e53804a7 | Shishir-rmv/oreilly_math_fundamentals_data_science | /calculus_and_functions/task2.py | 978 | 4.125 | 4 | """
We want to find the area for the function y = .5x^2
within the range 0 and 2.
Here is a graph showing the function and area we want to calculate:
https://www.desmos.com/calculator/ihfabetgqm
Complete the code below to approximate this area by using a Reimann Sums,
which packs rectangles under the function (at their midpoints) and summing their areas.
Be sure to specify enough rectangles so we get accuracy of at least 6 decimal places.
Then execute the script
"""
# This function will pack `n` rectangles under the function `f` for the
# specified `lower` and `upper` bounds, and above the x-axis.
def approximate_integral(lower, upper, n, f):
delta_x = (upper - lower) / n
total_sum = 0
for i in range(1, n + 1):
midpoint = 0.5 * (2 * lower + delta_x * (2 * i - 1))
total_sum += f(midpoint)
return total_sum * delta_x
def my_function(x):
return ?
area = approximate_integral(lower=?, upper=?, n=?, f=?)
print(area)
| true |
0ed5e474cb4f73a785a27411bebdc5512f4a3474 | desmond241993/project-euler | /PROBLEM 7/nth_prime.py | 983 | 4.25 | 4 | '''
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
'''
import math
#function to find n th prime
def find_prime(n):
i = 2 #number for prime check
p = 0 #count of the number of primes
while True:
if(p == n): #if the no of primes counted by the algo matches the input count
return i-1 #return the corresponding prime
count = 0 #count refressed to keep track of the factors of a number
for j in range(2,int(math.sqrt(i))+1):
if i%j == 0: #if j is a factor of i
count += 1
break
if count == 0: #if count is 0 the checked number is a prime
p += 1
i += 1
n = 10001
print("The {}th prime number is {}".format(n,find_prime(n)))
| true |
449741444fa127ee64f7bedbc334e1d879bd7bec | harshithkumar2/python_programes | /factorial.py | 315 | 4.1875 | 4 | #loops
# def factorial(num):
# sum = 1
# for i in range(1,num+1):
# sum *= i
#
# return sum
#recursive way
def factorial(num):
if num ==0 or num ==1:
return 1
else:
return num*factorial(num-1)
if __name__ == "__main__":
n = int((input()))
print(factorial(n)) | false |
d8a48aacab1716fd902fcf49b32b5d1744183faa | ConstructCP/checkio | /dropbox/speech_module.py | 2,350 | 4.5 | 4 | """
Transform number to string representation: 42 -> forty two
Input: A number as an integer.
Output: The string representation of the number as a string.
https://py.checkio.org/mission/speechmodule
"""
FIRST_TEN = ["one", "two", "three", "four", "five", "six", "seven",
"eight", "nine"]
SECOND_TEN = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"]
OTHER_TENS = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy",
"eighty", "ninety"]
HUNDRED = "hundred"
def write_hundreds(hundreds: int) -> str:
""" Return string representation of hundreds part of a number """
if hundreds == 0:
return ''
return (FIRST_TEN[hundreds - 1] + ' ' + HUNDRED).strip()
def write_tens_and_ones(number: int) -> str:
""" Return string representation of dozens and ones of a number """
if number == 0:
return ''
elif 1 <= number < 10:
return FIRST_TEN[number - 1]
elif 10 <= number < 20:
return SECOND_TEN[number - 10]
else:
tens = number // 10
tens_as_string = OTHER_TENS[tens - 2]
ones = number % 10
ones_as_string = FIRST_TEN[ones - 1] if ones > 0 else ''
return (tens_as_string + ' ' + ones_as_string).strip()
def number_as_string(number: int) -> str:
""" Return string representation of number < 1000 """
if number == 0:
return 'zero'
hundreds = write_hundreds(number // 100)
tens_and_ones = write_tens_and_ones(number % 100)
as_string = (hundreds + ' ' + tens_and_ones).strip()
return as_string
def checkio(number: int) -> str:
""" Transform number into string form """
result = number_as_string(number)
return result
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio(4) == 'four', "1st example"
assert checkio(133) == 'one hundred thirty three', "2nd example"
assert checkio(12) == 'twelve', "3rd example"
assert checkio(101) == 'one hundred one', "4th example"
assert checkio(212) == 'two hundred twelve', "5th example"
assert checkio(40) == 'forty', "6th example"
assert not checkio(212).endswith(' '), "Don't forget strip whitespaces at the end of string"
print('Done! Go and Check it!')
| true |
060be54040443da1590146f5242218a5eebbbc67 | zwala/Assignments_PythonClass | /c3_number_systems.py | 1,601 | 4.5625 | 5 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
### NUMBER SYSTEM ###
''' Number System: The process of creating numbers using some set of digits
Types: Binary, Deciamal, Octal, HexaDecimal Number System
Binary Number System: {0,1}
{zeros and ones} Radix/Base: 2
Representation: 0b... ex: 0b0110010
Decimal Number Sytem: {0,1,2,3,4,5,6,7,8,9}
{all single digit numbers}, Radix/Base: 10
Representation: ... ex: 1234
Octal Number System: {0,1,2,3,4,5,6,7}
{0 to 7}, Radix/base: 8
Representation:0... ex:01234
HexaDecimal Number System: {0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F}
{0 to 9, A to F} Radix/Base: 16
Representation: 0X... ex:0X1234
int(string,base) Converts any number to decimal
bin() Converts any number to binary
oct() Converts any number to Octal
hex() Converts decimal to HexaDecimal'''
binary=raw_input("Enter a Binary number('0b'+{0,1}): ")
decimal=raw_input("Enter a Decimal number{1 to 9}: ")
octal=raw_input("Enter a Octal number('0'+{0 to 7}): ")
hexa_decimal=raw_input("Enter a HexaDecimal number('0X'+{0to9,AtoF}): ")
"""Conversion of 3 systems to Decimal """
print ""
print "The above NumberSystem when converted to Decimal:"
print "Binary to Decimal: ",int(binary,2)
print "Octal to Decimal: ", int(octal,8)
print "HexaDecimal to Decimal: ", int(hexa_decimal,16)
"""Conversion of Decimal to 3 other NumberSystems"""
print ""
print "The Decimal number converted in to 3 other NumberSystems:"
print "Decimal to Binary: ", bin(int(decimal))
print "Decimal to Octal: ", oct(int(decimal))
print "Decimal to HexaDecimal: ", hex(int(decimal))
| true |
fe8638acc4d91680a63c88beef23185ad0e1678d | ajaygupta74/ProjectEulerProblemSolution | /p4.py | 606 | 4.125 | 4 | """A palindromic number reads the same both ways. The largest
palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers. """
import math
li = []
for i in range(999,100,-1):
for j in range(999,100,-1):
n = str(i*j)
num = n[::-1] #reversing the product
if (num == n): #checking if palidrome
if int(num) > 10000: # to finding large
li.append(int(num))
print(max(li)) finding largest palidrome
"""answer = 906609 """
| true |
597f5627a0b1fa818c88cf604ac3009058342c4a | prasanganath/python | /linkedList/LinkedList.py | 2,398 | 4.28125 | 4 | # code from labSheet 3, /// complete and working
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def strnode(self):
print(self.data)
# ///////////////////////////////////////////////
# implementing linked list //code from labSheet 3
class LinkedList:
def __init__(self):
self.numnodes = 0 # The number of the nodes in linked list
self.head = None # reference to the first node
# create and insert a new node to the front of the linkedList
def insertFirst(self, data):
newNode = Node(data)
newNode.next = self.head
self.head = newNode
self.numnodes += 1
# create and insert a new node to the back of the linkedList
def insertLast(self, data):
newNode = Node(data)
newNode.next = None # because newNode is the last node
if self.head is None: # checking weather the list is empty
self.head = newNode # if empty, newNode is the head
return
lnode = self.head # lnode is a tmp reference to get to the last node
while lnode.next is not None: # getting last node
lnode = lnode.next
lnode.next = newNode # new node is now the last node
self.numnodes += 1
# remove node from the front of the linkedList
def remFirst(self):
cnode = self.head # cnode >> current node
self.head = cnode.next # new head is the second node
cnode.next = None # breaking the connection of first node with second node
del cnode
self.numnodes -= 1
# remove node from the back of the linkedList
def remLast(self):
lnode = self.head
while lnode.next is not None:
pnode = lnode
lnode = lnode.next
pnode.next = None
del lnode
self.numnodes -= 1
# get the value of the first node
def getFirst(self):
lnode = self.head
return lnode.data
# get the value of the last node
def getLast(self):
lnode = self.head
while lnode.next is not None:
lnode = lnode.next
return lnode.data
# printing the linkedList
def print_list(self):
lnode = self.head
while lnode:
lnode.strnode() # print the node
lnode = lnode.next
def getSize(self):
return self.numnodes
| true |
184e2b71365283ae423b3e103dceb76f4a515309 | lucas-sigma/Python-Brasil-Resposta-Exercicios | /Estrutura-Sequencial/ex07.py | 274 | 4.25 | 4 | # Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário.
ladoQuadrado = float(input('Digite um dos lados do quadrado: '))
areaQuadrado = ladoQuadrado * ladoQuadrado
print('Dobro da área do quadrado: ', areaQuadrado * 2) | false |
e623b568a3622efb5054b9aa8b20fc47a7cbe9db | lucas-sigma/Python-Brasil-Resposta-Exercicios | /Estrutura-Sequencial/ex10.py | 222 | 4.125 | 4 | # Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre em graus Farenheit.
celcius = float(input('Temperatura em graus Celcius: '))
farenheit = celcius * 1.80 + 32
print('Farenheit: ', farenheit) | false |
71f74c365d41cd7781b238b51e1f1ca2f8cfbb87 | vivekrj/Python-Sample | /ex3.py | 513 | 4.25 | 4 | print "I will now count my money:"
print "coins", 50 + 10 /2
print "Rupees", 100 - 25 * 3 % 4
print "Now I will do some math calculations:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print 5.0 + 1.2 + 3.8
print "Is it true that 10 +12 < 5 - 7?"
print 10 + 12 < 5 - 7
print "What is 23 + 22?", 23 + 22
print "What is 25 - 27?", 25 - 27
print "Oh, that's why it's False."
print "How about some more."
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2 | true |
d87aed72cb4fc2693bef54c87adf08c5ab12c895 | Chen-Fu/automate-the-boring-stuff-with-python | /Ch4 Comma Code.py | 670 | 4.34375 | 4 | spam = ['apples', 'bananas', 'tofu', 'cats']
'''
Write a function that takes a list value as an argument and returns a string with all
the items separated by a comma and a space, with and inserted before the last item.
For example, passing the previous spam list to the function would return 'apples,
bananas, tofu, and cats'. But your function should be able to work with any list
value passed to it. Be sure to test the case where an empty list [] is passed to your
function.
'''
def commaCode(spam):
output = ''
for word in spam[:-1]:
output += word + ', '
output = output + 'and ' + spam[-1]
return output
print(commaCode(spam))
| true |
b3c221980832b45cf09a50f20f64ad616b32721a | Combatd/coding_challenges | /python_tutorial/divisionoperator.py | 933 | 4.15625 | 4 | '''
Task
The provided code stub reads two integers, a and b, from STDIN.
Add logic to print two lines. The first line should contain the result of integer division, a // b. The second line should contain the result of float division, a/b .
No rounding or formatting is necessary.
Example
The result of the integer division 3//5 = 0 .
The result of the float division 3/5 = 0.6 .
Whiteboarding
* We can assume that both a and b will be passed in as integers.
* We will use the division operator / to return an integer and // to return a float.
* The results of a//b and a/b will be printed on their own lines.
* I do not require special formatting or rounding of numbers.
* I should make sure that b is not 0, which would be impossible
'''
from __future__ import division
if __name__ == '__main__':
a = int(raw_input())
b = int(raw_input())
if b == 0:
print('b cannot be 0')
else:
print(a//b)
print(a/b) | true |
c92aade49a6cfb89ba91368788ce91c520e0fefc | jagadeesh29/Python_programs | /5.Greeting_from_time.py | 938 | 4.15625 | 4 | #5. Get the name of the user as inputs and greet the user saying "Good Morning, <firstname>" or "Good Afternoon, <firstname>" depending upon the time of the day
def greeting_from_time():
username = input("enter your name: ")
import datetime
now = datetime.datetime.now()
time = str(now.time())
morning = 'Good Morning'
afternoon = 'Good Afternoon'
evening = 'Good Evening'
night = 'Good Night'
if(int(time[:2]) < 12):
print (morning,'-',username)
elif((int(time[:2]) >=12) and (int(time[:2]) <= 17)):
print( afternoon,'-', username)
elif(int(time[:2]) >17 and int(time[:2]) <=20):
print(evening,'-', username)
else:
print(night,'-',username)
greeting_from_time()
'''
Testcases:
INPUT OUTPUT
1. Jac Good Night - Jac
2. 56
3. @#$%^
4. -6
5. 5.5
''' | false |
087312b97c0628ecf9dc740e3960d713d4bff461 | jagadeesh29/Python_programs | /8.Prime_number.py | 1,265 | 4.25 | 4 | #8. Given a number, find whether or not it is prime
chk =2
while chk==2:
try:
chk =1
n = int(input("enter the number you want to check whether prime or not:"))
if(n<0):
print("Enter the positive numbers")
chk=2
except ValueError:
print("Enter Valid inputs")
chk=2
def is_prime(n):
if(n == 0 or n==1):
print("Not a prime")
elif n > 1:
for i in range(2, n):
if (n % i == 0):
print("not a prime number")
break
else:
print("prime")
else:
print("Enter the Valid inputs")
is_prime(n)
'''
TESTCASES:
INPUT OUTPUT
1. ASDF Enter Valid inputs
2. -3 Enter the positive numbers
3. @# Enter Valid inputs
4. 0 Not a prime
5. 1 Not a prime
6. 2 prime
7. 23 prime
8. 55 Not a Prime
9. " " Enter Valid Inputs
''' | true |
83a3499eab4bfd2863de84fd9e45a1ae6bfd0460 | hqqiao/pythonlearn | /9-Functional Programming-sorted.py | 1,533 | 4.375 | 4 | # Python内置的sorted()函数对list进行排序
# sorted()也是一个高阶函数。用sorted()排序的关键在于实现一个映射函数。
print(sorted([1, -2, 4, 5, 7, -9]))
print(sorted([1, -2, 4, 5, 7, -9], key=abs)) # 依据绝对值排序
# [-9, -2, 1, 4, 5, 7]
# [1, -2, 4, 5, 7, -9]
print(sorted(['bob', 'about', 'Zoo', 'Credit']))
# 默认情况下,对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a',结果,大写字母Z会排在小写字母a的前面
# ['Credit', 'Zoo', 'about', 'bob']
print(sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower))
# 忽略大小写,按照字母序排序,即都变为大写或者都变为小写
# ['about', 'bob', 'Credit', 'Zoo']
print(sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower, reverse=True))
# 通过reverse = True 实现反向排序
# 练习
# 假设我们用一组tuple表示学生名字和成绩:
# 请用sorted()对学生列表分别按名字排序以及按成绩从高到低排序
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
print(sorted(L, key=lambda t: t[0])) # 以元组中第一个元素作为sorted排序对象
print(sorted(L, key=lambda t: t[1], reverse=True)) # 以元组中第二个元素作为sorted排序对象,倒序排序
print(sorted(L, key=lambda t: -t[1])) # 以元组中第二个元素作为sorted排序对象,倒序排序,-t[1]
def by_name(t):
return t[0]
def by_score(t):
return t[1]
L2 = sorted(L, key=by_name)
print(L2)
L3 = sorted(L,key=by_score,reverse=True)
print(L3) | false |
c439358a83b44ecd521bd43aa0f1d0605140239f | calheira/lpthw | /ex06.py | 823 | 4.28125 | 4 | # inicializa variavel com valor numerico
types_of_people = 10
# inicializa variavel com string formatada
x = f"There are {types_of_people} types of people."
# inicializa variavel com string
binary = "binary"
do_not = "don't"
# inicializa variavel com string formatada
y = f"Those who know {binary} and those who {do_not}."
# imprime variaveis
print(x)
print(y)
print(f"I said: {x}")
print(f"I also said: '{y}'")
# inicializa variavel com valor booleano
hilarious = False
# inicializa variavel com string e espaco para formatacao
joke_evaluation = "Isn't that joke so funny?!{}"
# imprime variavel usando propriedade format
print(joke_evaluation.format(hilarious))
# inicializa variaveis com strings
w = "This is the left side of..."
e = "a string with a right side."
# concatena strings e imprime o resultado
print(w + e) | false |
c0dcf22bf2fbe767685079f2e2d4f9cd8ff5b87f | makoalex/object-oriented-prrogramming | /oop/encapsulation.py | 873 | 4.25 | 4 | """refers to information hiding, giving access to only specific information to the user """
# reduces system complexity1 and increases robustness
class Base:
def __private(self):
print('private base method')
def _protected(self):
print('protected base method only')
def public(self):
print('public method ')
self.__private()
self._protected()
class Derived(Base):
def __private(self):
print('private derived method')
def _protected(self):
print('protected derived method')
"""the second _protected method, overrides the firs, because it is not private """
d = Derived()
d.public()
"""d.__private()
print(dir(d))
d._Derived__private()"""
# printing all of the above shows that private methods are protected from being overridden in the derived class
# this is called NAME MANGLING
| true |
4576878d9563f6ca11a3ad87eb6418d41f4517b9 | PSaiRahul/Pyworks | /frequency_counter_hack.py | 548 | 4.3125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import defaultdict
from collections import Counter
#
# A clever data structure to use as a frequency counter
#
frequency = defaultdict(Counter)
# Defining some sample data
frequency['fruits']['mango'] = 9
frequency['fruits']['orange'] = 4
frequency['fruits']['banana'] = 2
# Incrementing mangoes
frequency['fruits']['mango'] += 1
# Print frequency of each fruit
print dict(frequency['fruits'])
# Get the fruit that is highest in quantity
print frequency['fruits'].most_common(1) | true |
72bfe995bb668a470bb52a31223f7b04a73ea1b0 | CaptainSherry49/Python-Beginner-Advance-One-Video | /My Practice Of Beginner Video/Chapter 6/03_if,else_operators.py | 420 | 4.25 | 4 | # Relation Operators
== ("Equals to")
>= ("Greater Than / Equal to")
<= ("Less Than / Equal to")
> ("Greater Than")
< ("Less Than")
# Logical Operators
and ("For two Bool valriable")
or ("if one is True")
not
# Logical
a = 34
b = 32
c= 32
if a > c and b > c:
print("True")
else:
print("False")
if a == c or b == c:
print("True")
else:
print("False")
| true |
ffdbe430e9ea17af584e9ac1432bec581380140b | CaptainSherry49/Python-Beginner-Advance-One-Video | /My Practice Of Beginner Video/Chapter 3/03_String_Function.py | 731 | 4.28125 | 4 | Story = "Once upon a Time there was a Youtuber who Uploaded 11 Hours Video of Python Tutorial"
# String Function
#Length Function
print(len(Story))
#ENdswith Function
print(Story.endswith("Tutorial")) #It's will return Boolean answer
print(Story.endswith("this")) #This will br Surley False
#Count Function
print(Story.count("o")) #It's will return the number of a Character that how many time the character printed
#Capitalized Function
print(Story.capitalize()) #This function Capital the first letter of the given String
#Find Function
print(Story.find("Youtuber")) #Finding the given Word and returns it's Index
# Replace Function
print(Story.replace("11","11.58")) #It will replace old string with the new given string
| true |
2403008bf42793ff0a65fdc0b0637d8756f96069 | CaptainSherry49/Python-Beginner-Advance-One-Video | /Advance Python Practice/Chapter 12 Try , Except/01_py_try.py | 414 | 4.125 | 4 | while(True):
print("press q to quit")
a = input("Enter a number:\n")
if a == "q":
break
try:
a = int(a)
if a > 87 :
print("You entered a number greater than a")
else:
print("You entered a number Less than a")
except Exception as e:
print(f"You make an error, please recheck your Code: {e}")
print("Thanks For Playing this game.") | true |
7c328bfab813375543300eb9f6eb11bb7d4633cd | ZacharyEagan/DataVis | /lab2/task2.py | 1,827 | 4.1875 | 4 | import numpy as np
#showing that python will automaticall determin array type based on
# the eliments stored
a = np.array([2,3,4])
print a
print a.dtype
#for example this one produces an array of float types
b = np.array([1.2, 2.3, 3.3, 3.4])
print b
print b.dtype
#question: what happens in a mixed type array?
c = np.array([1.2,5,6,7])
print c
print c.dtype
d = np.array([6,7,8,1.2])
print d
print d.dtype
#answer: apears it uses whatever datatype will be least lossy overall
#so if a float is present it uses float since that also can hold int
#looks like numpy is fine handling complex numbers so long as specified
e = np.array([[1,2],[3,4]], dtype=complex) #can specify type manually
print e
print e.dtype #has a native type for complex nums
f = np.array([6,7,8,1.2], dtype=int)#does not warn about loss if type
#is manually specified
print f
g = np.zeros((3,4)) #aray of dimensions filled with zeros
print "\ng" #starting to get messy so adding lables and line breaks
print g
h = np.ones((2,3,4), dtype=np.int16) #specify datatype fill with zeros
print "\nh"
print h
i = np.empty((2,3)) #random data default datatype is float
print "\ni"
print i
#now testing the arrange function with different datatypes
j = np.arange(10,30,5) #generates numbers from [10-30) in steps of 5
print "\n\nj"
print j
k = np.arange(0,2,0.3) #generates values from 0 to 2 in steps of .3
print "\nk"
print k
print "\n\n\n"
from numpy import pi
l = np.linspace(0,2,9) # for generating floats linspace is better
#generates 9 numbers from [0-2)
print l
m = np.linspace(0, 2*pi, 100) #using the pi constant
print m
print "\n\n"
n = np.sin(m) #because python is rediculous passing an unknown array
#like m into the sin function will simply evaluate sin over all m
#and return another array of the outputs
print n
#pretty cool
| true |
fc941f7af616952e172172eff2be015d13f8aa1e | RahulAdepu92/myLearning | /learn_python/method vs function.py | 1,608 | 4.21875 | 4 | ##difference between function & method
#Method is called by an object, whereas function is independent and can be called directly
str = "abc"
course = print(str) #here print is considered a "function" becuase it is universal and can be used to print string/int/float; syntax is 'function(variable)'
course1 = len(str) #here print is considered a "function" becuase it is universal and can be used to find length of string/int/float; syntax is 'function(variable)'
course2 = print(str.upper()) #-> returns ABC #here upper is considered a "method" because it is constrained and used for converting only STRING object;
#syntax is 'variable.method()' or 'object.method()'
#this STRING object has various methods like upper(), lower(), replace(), find() ....
course3 = print(str.find('b'))#-> returns 2 #here upper is considered a "method" because it is constrained and used for converting only STRING object;
#syntax is 'variable.method('char')' or 'object.method()'
print('d' in str) #-> returns boolean value TRUE/FALSE
#**Method example**
#Ex1:
class abc:
def abc_method (self):
print("hello world")
#now abc_method will be called through an object as
abc_object = abc() # object of abc class
abc_object.abc_method()
#>>> hello world
#Ex2:
import math #here, math is an imported module; is an object
print(math.ceil(2.9)) #> prints 3 #syntax is object.method()
#**Function example**
a = (1, 2, 3, 4, 5)
x = sum(a)
print(x)
#>>> 20
| true |
3b2c09af315ca6d5e6b0c570b969e70473d794ce | JeffreyLambert/MIT60001 | /ps1/ps1a.py | 627 | 4.21875 | 4 | r = 0.04
current_savings = 0
portion_down_payment = 0.25 # Portion of house to be saved
if __name__ == '__main__':
annual_salary = int(input("Enter your annual salary: "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost = int(input("Enter the cost of your dream home: "))
amount_to_save = total_cost * portion_down_payment
monthly_savings = annual_salary / 12 * portion_saved
i = 0
while current_savings < amount_to_save:
i += 1
current_savings += monthly_savings + current_savings * r / 12
print(f"Number of months: {i}") | true |
52baa9971873aac2ba5cbfef6cfe9bbce16172ed | jinjiel1994/CIS210 | /counts.py | 1,554 | 4.5625 | 5 | """
Count the number of occurrences of each major code in a file.
Authors: Jinije(Jim) li
Credits: Information from canvas
Input is a file in which major codes (e.g., "CIS", "UNDL", "GEOG")
appear one to a line. Output is a sequence of lines containing major code
and count, one per major.
"""
import argparse
def count_codes(majors_file):
"""
Make a new vairable major_check, to save the last major in loop,
in order to compare with the current major. If the current major is the same
as the former,it counts, else print the current major and the number, then
refresh number and major_check.
"""
majors = [ ]
for line in majors_file:
majors.append(line.strip())
majors = sorted(majors)
if len(majors) == 0:
print("File is empty")
return
else:
major_check = [ ]
count = 0
for major in majors:
if major == major_check or major_check == [ ]:
count = count + 1
major_check = major
else:
print(major_check, count)
count = 1
major_check = major
print(major_check, count)
def main( ):
parser = argparse.ArgumentParser(description="Count major codes")
parser.add_argument('majors', type=argparse.FileType('r'),
help="A text file containing major codes, one major code per line.")
args = parser.parse_args()
majors_file = args.majors
count_codes(majors_file)
if __name__ == "__main__":
main( )
| true |
830c82dd16ef3fe157db197f82299023ef508878 | kjuao9/coisas-de_python | /Python/1° Tri/outros exercicios.../atv12.py | 402 | 4.1875 | 4 | n1 = input("Qual o primeiro numero inteiro?")
n1 = int(n1)
n2 = input("Qual o segundo numero inteiro?")
n2 = int(n2)
n3 = float(input("Qual o numero real?"))
a = (n1 * 2)*(n2/2)
print("O produto do dobro do primeiro com metade do segundo é igual a:",a)
b = (3 * n1)+ n3
print("A soma do triplo do primeiro com o terceiro é igual a:",b)
c = n3*n3*n3
print("O terceiro elevado ao cubo é igual a:",c)
| false |
9b91971ee8219471c84b24b99948f4030171f22e | SchedulerShu/PythonLearn | /20171028/reduce.py | 2,124 | 4.375 | 4 |
from functools import reduce
##reduce
'''
官方解释如下:
Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).
The left argument, x, is the accumulated value and the right argument, y, is the update value from the sequence.
If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
If initializer is not given and sequence contains only one item, the first item is returned.
格式: reduce (func, seq[, init()])
reduce()函数即为化简函数,它的执行过程为:每一次迭代,都将上一次的迭代结果(注:第一次为init元素,如果没有指定init则为seq的第一个元素)与下一个元素一同传入二元func函数中去执行。
在reduce()函数中,init是可选的,如果指定,则作为第一次迭代的第一个元素使用,如果没有指定,就取seq中的第一个元素。
'''
def statistics(lst):
dic = {}
for k in lst:
if not k in dic:
dic[k] = 1
else:
dic[k] +=1
return dic
lst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]
print(statistics(lst))
def statistics2(lst):
m = set(lst)
dic = {}
for x in m:
dic[x] = lst.count(x)
return dic
lst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]
print (statistics2(lst))
def statistics(dic,k):
if not k in dic:
dic[k] = 1
else:
dic[k] +=1
return dic
lst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]
print (reduce(statistics,lst,{}))
#提供第三个参数,第一次,初始字典为空,作为statistics的第一个参数,然后遍历lst,作为第二个参数,然后将返回的字典集合作为下一次的第一个参数
#或者 d = {} d.extend(lst)
#print reduce(statistics,d)
#不提供第三个参数,但是要在保证集合的第一个元素是一个字典对象,作为statistics的第一个参数,遍历集合依次作为第二个参数
| false |
dcbc3d4ea84b008f2b76221877d63ad72137747f | SchedulerShu/PythonLearn | /20171028/python匿名函数.py | 1,285 | 4.21875 | 4 | '''
高阶函数可以接收函数做参数,有些时候,我们不需要显式地定义函数,直接传入匿名函数更方便。
'''
#在Python中,对匿名函数提供了有限支持。还是以map()函数为例,计算 f(x)=x2 时,除了定义一个f(x)的函数外,还可以直接传入匿名函数:
x = list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
print(x)
'''
通过对比可以看出,匿名函数lambda x: x * x实际上就是:def f(x):
return x * x
关键字lambda表示匿名函数,冒号前面的x表示函数参数。匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果。
'''
#匿名函数有个好处,因为函数没有名字,不必担心函数名冲突。此外,匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函数:
f = lambda x: x * x
print(f(5))
#同样,也可以把匿名函数作为返回值返回,比如:
def build(x, y):
return lambda x,y: x * x + y * y
print(build(3,5)) | false |
3f749edfb8ec9f6454377d30f87a260d0aa95db3 | haroon-rasheed/code_practice | /google/binary_tree.py | 1,205 | 4.375 | 4 | #!/usr/bin/env python
class Node:
"""
Tree node: left and right child + data which can be any object
"""
def __init__(self, data):
"""
Node constructor
@param data node data object
"""
self.left = None
self.right = None
self.data = data
def insert(self, data):
"""
Insert new node with data
@param data node data object to insert
"""
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
else:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
def print_tree(self):
"""
Print tree content inorder
"""
if self.left:
self.left.print_tree()
print self.data,
if self.right:
self.right.print_tree()
if __name__ == '__main__':
root = Node(8)
root.insert(3)
root.insert(10)
root.insert(1)
root.insert(6)
root.insert(4)
root.insert(7)
root.insert(14)
root.insert(13)
root.print_tree()
| false |
f3b4981aec4e343120913a5ca22b100abb0db8cb | edubd/uff2020 | /progs/p07_importa_lojas.py | 723 | 4.21875 | 4 | #P07: Importação de CSV padrão para DataFrame
import pandas as pd
#(1)-Importa a base de dados para um DataFrame
df_lojas = pd.read_csv('lojas.csv')
print(df_lojas)
#(2)-mostra o total de linhas e colunas
print('------------------------------------')
num_linhas = df_lojas.shape[0]
num_colunas = df_lojas.shape[1]
print("número de linhas: ", num_linhas)
print("número de colunas: ", num_colunas)
#(3)-primeiras linhas - head()
print('------------------------------------')
print("primeiras linhas\n: ", df_lojas.head())
#(4)-últimas linhas - tail()
print('------------------------------------')
print("primeiras linhas\n: ", df_lojas.tail())
| false |
538cf74fc6e1d50598486042ea0bd39b41ce9bf5 | fayblash/DI_Bootcamp | /Week5/Day3/XPGold.py | 2,390 | 4.46875 | 4 | # Exercise 1 : Regular Expression #1
# Instructions
# Hint: Use the RegEx (module)
import re
# Use the regular expression module to extract numbers from a string.
# Example
def return_numbers(string):
print ("".join(re.findall('\d+', string)))
# return_numbers('k5k3q2g5z6x9bn')
# // Excepted output : 532569
return_numbers('k5k3q2g5z6x9bn')
# Exercise 2 : Regular Expression #2
# Instructions
# Hint: Use the RegEx (module)
# Ask the user for their full name (example: “John Doe”), and check the validity of their answer:
# The name should contain only letters.
# The name should contain only one space.
# The first letter of each name should be upper cased.
def validate_name(name):
pattern = '[A-Z]+[a-z]+$'
# ^([A-Z]+\s)*[a-zA-Z0-9]+$
if re.search(pattern, name):
return True
else:
return False
your_name=input("Please enter your full name: ")
print(validate_name(your_name))
# Exercise 3: Python Password Generator
# Instructions
# Create a Python program that will generate a good password for you.
# Program flow:
# Ask the user to type in the number of characters that the password should have (password length) – between 6 and 30 characters.
# Validate the input. Make sure the user is inputing a number between 6 to 30. Create a loop which will continue to ask the user for an input until they enter one which is valid.
# Generate a password with the required length.
# Print the password with a user-friendly message which reminds the user to keep the password in a safe place!
# Rules for the validity of the password
import rstr
pw_string="[A-Z]\d[a-z][@#$%^&+=]"
i=4
pw_length=int(input("Enter a number between 6 and 30: "))
while i<pw_length:
pw_string+="[A-Za-z\d@$%^&+=]"
i+=1
print(rstr.xeger(pw_string))
# Each password should contain:
# At least 1 digit (0-9)
# At least 1 lower-case character (a-z)
# At least 1 upper-case character (A-Z)
# At least 1 special character (eg. !, @, #, $, %, ^, _, …)
# Once there is at least 1 of each, the rest of the password should be composed of more characters from the options presented above.
# Create a test function first!
# Do the following steps 100 times, with different password lengths:
# Generate a password.
# Test the password to ensure that:
# it fulfills all the requirements above (eg. it has at least one digit, etc.)
# it has the specified length. | true |
cd7d676855abd4b5c4bfdfb9f4f8dccb51ca5b9d | fayblash/DI_Bootcamp | /Week5/Day2/XPGold.py | 2,972 | 4.21875 | 4 | # Exercise 1: Bank Account
# Part I:
# Create a class called BankAccount that contains the following attributes and methods:
class BankAccount:
def __init__(self,balance,username,password,authenticated):
self.balance=balance
self.username=username
self.password=password
self.authenticated=authenticated
# balance - (an attribute)
# __init__ : initialize the attribute
# deposit : - (a method) accepts a positive int and adds to the balance, raise an Exception if the int is not positive.
def deposit(self,number):
if authenticated=True:
if number>0:
self.balance+=number
else:
raise Exception('You must enter a number greater than 0')
else:
raise Exception("Your username or password were invalid")
# withdraw : - (a method) accepts a positive int and deducts from the balance, raise an Exception if not positive
def withdraw(self,number):
if authenticated=True:
if number>0:
self.balance-=number
else:
raise Exception('You must enter a number greater than 0')
else:
raise Exception("Your username or password were invalid")
def authenticate(self,username,password):
if self.username==username and self.password==password:
authenticated=True
else:
authenticated=False
# Part II : Minimum balance account
# Create a MinimumBalanceAccount that inherits from BankAccount.
class MinimumBalanceAccount(BankAccount):
def __init__(self,balance,minimum_balance=0):
super().__init__(balance)
self.minimum_balance=minimum_balance
# Extend the __init__ method and accept a parameter called minimum_balance with a default value of 0.
def withdraw(self,number):
if self.balance-number>self.minimum_balance:
self.balance-=number
else:
raise Exception (f"You can't withdraw ${number} since it will drop you below your minimum balance.")
# Override the withdraw method so it only allows the user to withdraw money if the balance remains higher than the minimum_balance, raise an Exception if not.
# Part III: Expand the bank account class
# Add the following attributes to the BankAccount class:
# username
# password
# authenticated (default to False)
# Create a method called authenticate. This method should accept 2 strings a username and password. If the username and password match the instances username and password the method should set the authenticated boolean to True.
# def authenticate(self,username,password):
# if self.username==username and self.password==password:
# authenticated=True
# else:
# authenticated=False
# Edit withdraw and deposit to only work if authenticated is set to True, if someone tries an action without being authenticated raise an Exception
| true |
1c9bcfbd7d6fab3f996b193a737a5d8a81c1901c | selvs1/PycharmProjects | /Tutorial/07-string-counter.py | 633 | 4.28125 | 4 | """
Develop a function that takes a list of strings and returns a list of integers where the elements are the length of the corresponding string. Do not use any predefined functions.
Example: lst_len(["abc", "de", "fghi"]) returns [3,2,4]"""
lst = ["abc", "de", "fghi"]
def lst_len(lst):
output = []
for e in lst:
output.append(len(e))
return output
print(lst_len(lst))
# Teacher
def list_len(lst):
"""
Take a list of strings and returns a list of integer where
the values are the lenght of each string
"""
res_lst = []
for s in lst:
res_lst += [len(s)]
return res_lst
| true |
0723ec03e626c9b2ac0b296d2339220f8e96ae4d | SaraaSameer/Numerical-Computing | /Ordinary_Differential_Equations/Heun's_Method.py | 1,526 | 4.25 | 4 | # Chapter05: Ordinary Differential Equations
# Method: Heun's Method
import math
def heun_method(x0, y0, h, x, function):
# Defining inline function to obtain a value (equation_value) at given x and y
equation_value = lambda t, w: eval(function)
# Variable i is showing number of iterations
i = 1
print("\n")
print("i\t\t Xi\t\t\tYi\t\t")
# Iterate till x0 is approximated to x for which we need a y-value
while x0 < x:
k1 = equation_value(x0, y0) # f(X(i),Y(i))
k2 = equation_value(x0 + float(h/3), y0 + (float(h/3) * k1)) # f(X(i)+h/3,Y(i)+h/3*k1)
k3 = equation_value(x0 + float(2*h/3), y0 + (float(2*h/3) * k2)) # f(X(i)+2*h/3,Y(i)+2*h/3*k2)
y0 = y0 + float(h/4) * (k1 + 3*k3) # y1 = y0 + h/4 (k1 + 3*k3)
x0 = x0 + h
print(i, "\t\t", "%.3f" % x0, "\t\t", "%.4f" % y0)
i = i+1
print("\nApproximate solution at x = ", x, " is ", "%.4f" % y0)
def main():
x0 = float(input("Enter the initial value of X[X0]: "))
y0 = float(input("Enter the initial value of Y[Y0]: "))
h = float(input("Enter StepSize [h]: "))
x = float(input("Enter the value of X at which we need approximation: "))
function = input("Enter Differential Equation:[t->x and w->y] ")
heun_method(x0, y0, h, x, function)
# Test Case01: X0 =0, Y0= 1, h=0.25, x=1 and function = math.cos(2*t) + math.sin(3*t)
# Test Case02: X0 =0, Y0= 0, h=0.5, x=1 and function = t * math.exp(3*t) - 2*w
if __name__== "__main__" :
main() | false |
9b868e7d38db724b52759d3f2a40c74313d9212a | ck0807/python | /cmpsc131Lab7.py | 1,819 | 4.21875 | 4 | '''
#1
def func1():
print('here1')
def func2():
print('here2')
func1()
def func3():
func2()
func1()
func2()
func3()
#2
def func1(x):
for i in range(5):
print(i * x)
func1(3)
#3
def func1(x):
return x*2
def func2(x):
x+=2
return func1(x)
result = func2(5)
print(result)
#4
def main():
x = 4
y = 10
z = 2
func1(y, z, x)
def func1(x, y, z):
print(x / y + z)
main()
#5
def func1(x):
for i in range(2,x):
print(func2(i))
def func2(num):
return num**num
func1(5)
'''
'''
#1Write a function print_many(x) that has one parameter that expects an
#integer and prints out ‘hello’ that many times.
def print_many(x):
for i in range(x):
print("hello")
print_many(5)
'''
#2 Write a function valid_score(score) that returns True if the given
#score is in the range between 0 and 100 inclusive otherwise it returns False
def main():
score = int(input("Please enter a number between 0 and 100: "))
valid_score(score)
def valid_score(score):
if score < 0 or score > 100:
return 'False'
else:
return 'True'
result = valid_score(score)
print(result)
main()
#3 Write a function called fizz_buzz(num) that takes an integer as a parameter.
# If the number is divisible by 3, it should return “Fizz”.
# If it is divisible by 5, it should return “Buzz”.
# If it is divisible by both 3 and 5, it should return “FizzBuzz”.
# Otherwise, it should return the same number.
def main():
fb_var = int(input("pllease enter an integer: "))
result = fizz_buzz(fb_var)
print(result)
def fizz_buzz(num):
if num%3 == 0 and num%5 ==0:
return "FizzBuzz"
elif num%3 == 0:
return "Fizz"
elif num%5 ==0:
return "Buzz"
else:
return num | false |
33c1e4dc0999795d85b318ab806e43d06bbd748f | kenEldridge/jib | /LinkedList.py | 2,177 | 4.28125 | 4 | #!/usr/bin/env python
"""Singly linked list"""
__author__ = "Ken Eldridge"
__copyright__ = "Copyright 2019, Ken Eldridge"
__license__ = "GPL"
__version__ = "0.0.0"
__status__ = "Development"
class LinkedList:
def __init__(self, value=None, next=None):
"""Create a node
Args:
value (Any): whatever you want, baby!
next (LinkedList): just the next node
"""
self.value = value
self.next = next
def insert(self, node, end=True):
"""Insert a node either following a specific node (by_value) or at
the end of the list
Args:
node (LinkedList): node to insert
end (boolean): insert at the of list, if false following self
"""
if end:
while self.next:
self = self.next
self.next = node
else:
self.next, node.next = node, self.next
def remove(self, node):
"""Remove specified node. Assumes self is the head
Args:
node (LinkedList): node to remove
Returns:
head (LinkedList): return the head of the list
"""
# If the head is removed, just cut it off and return next
if self is node:
return self.next
# Save entry point to return
head = self
# Save your most recent node
last = self
# Find the node to remove
while self.next and self is not node:
# Update your most recent node
last = self
# Step into the next node
self = self.next
if self is node:
# Jump self
last.next = self.next
return head
def __iter__(self):
"""Returns self
Returns:
node (LinkedList): self
"""
self.pointer = self
return self
def __next__(self):
"""Advances to next item
Returns:
node (LinkedList): next node
"""
if self.pointer is None:
raise StopIteration
else:
node = self.pointer
self.pointer = self.pointer.next
return node
| true |
5702dc403a62a6336d39d8bac94df9efdcbc4370 | fank-cd/books_exercise_code | /剑指offer/No06_从尾到头打印链表.py | 2,000 | 4.34375 | 4 | """
输入一个链表的头结点,从尾到头反过来打印每个节点的值(只逆序输出,不反转)
链表定义如下:
struct ListNode
{ // C++
int m_nKey,
ListNode* m_pNExt
}
"""
"""
思路:
1、一种是用列表存起来,然后先进后出就完事了
2、利用递归,但问题是递归栈深了其实有问题的,所以还是第一种鲁棒性更好
"""
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
def PrintListReverse(head):
"""
用栈实现,鲁棒性较好
O(n)
"""
if head is None:
return False
stack = []
node = head
while node:
stack.append(node.data)
node = node.next
while len(stack):
print(stack.pop())
def print_list_reversingly2(node):
"""
用递归实现,鲁棒性较差
O(n)
"""
if node is None:
return
print_list_reversingly2(node.next)
print(node.data)
def print_node(head):
while head:
print(head.data)
head = head.next
if __name__ == "__main__":
n5 = Node(data=5)
n4 = Node(data=4, next=n5)
n3 = Node(data=3, next=n4)
n2 = Node(data=2, next=n3)
head = Node(data=1, next=n2)
PrintListReverse(head)
# print_node(head)
"""
扩展:反转链表
res:None
第一层循环
res:1->2->3->4->5 res = p
res:1->None res.next = res
p:2->3->4->5 p = p.next
第二层循环
res:2->3->4->5 res = p
res:2->1->None res.next = res
p:3->4->5 p = p.next
第三层循环
res:3->4->5 res = p
res:3->2->1->None res.next = res
p:4->5 p = p.next
第四层循环
res:4->5 res = p
res:4->3->2->1->None res.next = res
p:5 p = p.next
第五层循环
res:5 res = p
res:5->4->3->2->1->None res.next = res
p:None p = p.next
end...
"""
def reverseList(head):
"""
:type head: ListNode
:rtype: ListNode
"""
p, rev = head, None
while p:
rev, rev.next, p = p, rev, p.next
return rev | false |
b80d7b29cce2e88786dc8e5b29d040f30b805afc | itrowa/arsenal | /algo-lib/1_basic/Python/ArrayStack.py | 1,204 | 4.34375 | 4 | class Stack:
# 利用固定大小的"数组"来实现Stack.
# 利用数组的思维模式来实现Stack. (数组用python的list来模拟)
# 利用list, 咳咳(有点自欺欺人) 把list想象成可以mutable但是不能改变长度的array就行..
# 也就是说self.l没有len(), pop(), push()....
# 关于数组的下标:
# 1. 不使用[0],而是从1开始
# 2. latest元素放在数组后面(下标增大的方向.)
def __init__(self, cap):
self.l = [None] * cap # python用于初始化长度为cap的空list("数组")的语法
self.N = 0 # size of Stack, 注意这个不等于实际的数组长度.
self.cap = cap # 初始化时数组的长度.
def __repr__(self):
return self.l.__repr__()
def isEmpty(self):
return (self.l == [])
# push
# latest元素加在数组后面.
def push(self, item):
self.l[self.N+1] = item
self.N += 1
def pop(self):
item = self.l[self.N]
self.l[self.N] = None
self.N -= 1
return item
def size(self):
return N
s = Stack(10)
s.push(1)
s.push(2)
s.push(3) | false |
c132cc87cf8f0b11928f5a14147d0e6d8141b022 | itrowa/arsenal | /algo-lib/4_graph/graph-cp.py | 2,707 | 4.375 | 4 | # Graph definition in think complexity.
class Graph(dict):
def __init__(self, vs=[], es=[]):
"""create a new graph. (vs) is a lst of vertices, es is a list of edges."""
for v in vs:
self.add_vertex(v)
for e in es:
self.add_edge(e)
def add_vertex(self, v):
"""add v to the graph"""
self[v] = {}
def add_edge(self, e):
"""add e to the graph by adding an entry in both directions.
if there is already an edge connecting these vertices, then replace it."""
v, w = e
self[v][w] = e
self[w][v] = e # 无向图所以两边都有.
def get_edge(self, vs):
"""read a list of vertices(vs) and return a edge if they are
connected. or return None."""
v, w = vs
try:
if v in self[v][w] and w in self[v][w]:
return self[v][w]
elif v in self[w][v] and w in self[w][v]:
return self[w][v]
except:
return None
def remove_edge(self, e):
"""remove an edge (e) from the graph."""
for v in self:
for i in self[v]:
if self[v][i] == e:
del self[v][i] # 如何直接把它删除掉?
def vertices(self):
"""return a list of vertices in the graph."""
return [v for v in self]
def edges(self):
"""return a list of edges in the graph."""
result = []
for i in self:
for j in self[i]:
if self[i][j] not in result:
result.append(self[i][j])
return result
def out_vertices(self, v):
"""return a list of vertices that come out from given vertice (v).
"""
return [i for i in self[v] if self[v][i]]
def out_edges(self, v):
"""return a list of edges that come out from given vertex (v)."""
return [self[v][i] for i in self[v] if self[v][i]]
def add_all_edges(self):
"""connect each vertices from scratch to produce a complete graph."""
class Vertex(object):
def __init__(self, label=''):
self.label = label
def __repr__(self):
return 'Vertex(%s)' % repr(self.label)
__str__ = __repr__
class Edge(tuple):
def __new__(cls, e1, e2):
return tuple.__new__(cls, (e1, e2))
def __repr__(self):
return 'Edge(%s, %s' % (repr(self[0]), repr(self[1]))
__str__ = __repr__
v = Vertex('v')
w = Vertex('w')
e = Edge(v, w)
print(e)
g = Graph([v, w], [e])
print(g)
# test get_edge()
x = Vertex('x')
y = Vertex('y')
f = Edge(x,y)
g.add_vertex(x)
g.add_vertex(y)
g.add_edge(f)
g.edges()
g.get_edge([x,y])
g.edges() | false |
94cb3db06fc489fb5fa2a8937cfbaba3cfc0b7dd | itrowa/arsenal | /algo-lib/2_sort/Selection.py | 764 | 4.15625 | 4 | # selection sort / 选择排序(冒泡排序) (升序)
# 把数组分为两部分, 前半部分是已排序的, 后半部分是未排序的.
# 刚开始只有后半部分, 所以先从0号元素开始依次比较所有在它后面的元素,
# 对于索引为0的元素来说, 遍历所有后面的元素,找出最小的,若0处元素比最小的还大,
# 则交换, 索引0处的元素就排序完毕, 然后继续处理索引为1, 2处的..
# 对list"数组"排序
def sort(array):
N = len(array)
for i in range(N):
for j in range(i+1, N):
if array[i] > array[j]:
array[i], array[j] = array[j], array[i]
# test
if __name__ == "__main__":
#
l = ["S","O","R","T","E","X","A","M","P","L","E"]
sort(l) | false |
2c7e084a7a5011646eb24c4d55bdad381913478a | SwanyeeAung/calculator-project | /calc.py | 833 | 4.15625 | 4 | gender = input("What is your gender?")
weight = input("What is your weight in lb?")
height = input("What is your height?")
sizes = {
(130, "5'5") : "XS",
(150, "5'9") : "XS",
(151, "5'5") : "S",
(160, "5'9") : "S",
(161, "5'5") : "M",
(170, "5'9") : "M",
(171, "5'6") : "L",
(180, "5'8") : "L",
(171, "5'9") : "M",
(180, "6'") : "M",
(181, "5'7") : "L",
(190, "6'1") : "L",
}
def height_to_inches(height):
return (int(height.split("'")[0])*12) + int(height.split("'")[1])
def size(height, weight, gender):
height = height_to_inches(height)
for i in sizes:
if (height_to_inches(i[1]) <= height) and (i[0] <= weight):
if (height_to_inches(i[1]) + 3 > height) and (i[0] + 9 > weight):
return sizes[i]
print(size("5'10", 180, "male"))
| false |
44e5ca891b7c7e39be1eb742c568729424a6a15c | hariharanragothaman/leetcode-solutions | /src/1796_second_largest_digit_in_a_string.py | 692 | 4.1875 | 4 | """
Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.
An alphanumeric string is a string consisting of lowercase English letters and digits.
Example 1:
Input: s = "dfa12321afd"
Output: 2
Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.
Example 2:
Input: s = "abc1111"
Output: -1
Explanation: The digits that appear in s are [1]. There is no second largest digit.
"""
class Solution:
def secondHighest(self, s: str) -> int:
s = sorted(set([int(c) for c in s if c.isdigit()]), reverse=True)
if s and len(s) >= 2:
return s[1]
return -1
| true |
7d11e812569e5f564807b336fda98b2116d41878 | dodosiz/codeCademy-Projects | /python/RPS.py | 1,244 | 4.125 | 4 | """The programm is the classic game of rock paper scissors against the computer"""
from random import randint
from time import sleep
options = ["R", "P", "S"]
LOSE_MESSAGE = "You lost my friend, I am sorry."
WIN_MESSAGE = "Bravo my friend, you won!"
def decide_winner(user_choice, computer_choice):
print "So you chose %s." % user_choice
print "Computer selecting..."
sleep(1)
print "Computer chose %s." % computer_choice
try:
user_choice_index = options.index(user_choice)
except ValueError:
print "Hey man watch out your typing!"
return
computer_choice_index = options.index(computer_choice)
if user_choice_index == computer_choice_index:
print "It's a tie!"
elif user_choice_index == 0 and computer_choice_index == 2:
print WIN_MESSAGE
elif user_choice_index == 1 and computer_choice_index == 0:
print WIN_MESSAGE
elif user_choice_index == 2 and computer_choice_index == 1:
print WIN_MESSAGE
else:
print LOSE_MESSAGE
def play_RPS():
print "Rock Paper Scissors!"
user_choice = raw_input("Select R for Rock, P for Paper, or S for Scissors.\n>>").upper()
computer_choice = options[randint(0,len(options)-1)]
decide_winner(user_choice, computer_choice)
play_RPS() | true |
0d74d1a7aa580701dfe7915a830b046a04e46c4f | diligentaura/oldpypractice | /Input Practice.py | 1,000 | 4.21875 | 4 | #Practice Input Thingy
#name
name = input ("Please enter your name:")
print ("")
#grade input
grade1 = input (name + " please enter your 1st Grade:")
grade2 = input (name + " please enter your 2nd Grade:")
grade3 = input (name + " please enter your 3rd Grade:")
grade4 = input (name + " please enter your 4th Grade:")
grade5 = input (name + " please enter your 5th Grade:")
grade6 = input (name + " please enter your 6th Grade:")
grade7 = input (name + " please enter your 7th Grade:")
grade8 = input (name + " please enter your 8th Grade:")
print ("")
#gradeSum
gradeSum = (int (int (grade1) + int (grade2) + int (grade3) + int (grade4) + int (grade5) + int (grade6) + int (grade7) + int (grade8)))
#grade print and gradeAvg
print ("Here are the sum of all your grades, " + name + ": " + str (gradeSum))
gradeAvg = (int (gradeSum)/8)
print ("")
gradeAvgRound = ("%0.2f" % gradeAvg)
print ("Here is the average of all your grades, " + name + ": " + str (gradeAvgRound))
| false |
2e126b13750fb42c5cb7d0e668b1e226d5e45d80 | PragathiNS/online-courses | /Python/numbers.py | 888 | 4.15625 | 4 | # Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'.
# Once 'done' is entered, print out the sum, count, average, largest and smallest of the number.
# If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.
# Enter 7, 2, bob, 10, and 4 and match the output below.
num = 0
total = 0.0
largest = None
smallest = None
while True:
sval = input('Enter a number: ')
if sval == 'done':
break
try:
fval = float(sval)
except:
print ('Invalid Input')
continue
num = num + 1
total = total + fval
# Largest
if largest is None:
largest = fval
elif largest < fval:
largest = fval
# Smallest
if smallest is None:
smallest = fval
if smallest > fval:
smallest = fval
print (total, num, total/num, largest, smallest)
| true |
f07e40554747f054f0b1d263997308b927ec8cf6 | JaleelSavoy/PythonTheHardWayExercises | /ex1 to ex3.py | 935 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 24 17:18:13 2016
@author: jalee
"""
print("Hello World!")
print("Hello Again")
print("I like typing this.")
print("This is fun.")
print("Yay! Printing.")
print("I'd much rather you 'not'.")
print("I \"said\" do not touch this.")
#comment comment comment
print("I could have code like this.") #comment comment
print("This will run.") #comment comment comment
print("I will now count my chickens: ")
print("Hens", 25 + 30 / 6)
print("Roosters", 100 - 25 * 3 % 4)
print("I will now count the eggs:")
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
print("Is it true that 3 + 2 < 5 -7?")
print(3 + 2 < 5 - 7)
print("What is 3 + 2?", 3 + 2)
print("What is 5 - 7?", 5 - 7)
print("Oh, that's why it's False.")
print("How about some more.")
print("Is it greater?", 5 > -2)
print("Is it greater or equal?", 5 >= -2)
print("Is it less or equal?", 5 <= -2)
| true |
2734e78416d17cad84c3276f53f65165464c8c86 | seyed-ali-mirzaee-zohan/Assignment-1 | /number2.py | 329 | 4.25 | 4 | a=float(input("Please enter the size of the first side : "))
b=float(input("Please enter the size of the second side : "))
c=float(input("Please enter the size of the third side : "))
if a<b+c and b<a+c and c<a+b :
result="The shape can be drawn"
else :
result="!! Error.The shape cannot be drawn !!"
print(result) | true |
0a572d5c0edffd63f373c1cd70de306360f7750c | neham0521/CS-1 | /Check point 1/Temperature_jacket.py | 343 | 4.125 | 4 | import sys
try:
temp_Celcius = float(input('Enter temperature in Celcius'))
except:
print('Error: Enter a numeric value for temperature')
sys.exit()
if temp_Celcius < 20:
print('Bring a heavy Jacket!')
elif temp_Celcius >=20 and temp_Celcius<=30:
print('Bring a light Jacket!')
else:
print('Please do not bring any Jacket!')
| true |
4c3048a0684a582834323e34f9172e6547aec90a | PierreColombo/CERN-data-classification | /Project 1/source/basic_functions/standardize.py | 1,059 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Project 1
group #28
pierre.colombo@epfl.ch
christian.tresch@epfl.ch
juraj.korcek@epfl.ch
"""
import numpy as np
def standardize(x, mean_x=None, std_x=None, skipped_cols=list()):
"""
Standardize the original data set except for columns listed in skipped_cols parameter.
Used to skip standardizing of categorical variable.
:param x: input variables (N, D)
:param mean_x: mean to be subtracted; if not provided it is calculated on x
:param std_x: std to be devided by; if not provided it is calculated on x
:param skipped_cols: columns to be skipped in standardization (e.g. for categorical variable)
:return: standardized x, mean used for standardization, std used for standardization
"""
mask = np.ones(x.shape[1], dtype=bool)
mask[skipped_cols] = False
if mean_x is None:
mean_x = np.mean(x, axis=0)
mean_x[~mask] = 0
tx = x - mean_x
if std_x is None:
std_x = np.std(x, axis=0)
std_x[~mask] = 1
tx[:, std_x > 0] = tx[:, std_x > 0] / std_x[std_x > 0]
return tx, mean_x, std_x
| true |
33ab2a2b78d48720517056ca92dedf6df0a5e7b3 | Vinay234/MachineLearning | /Coding_practice/Sorting_algos.py | 1,046 | 4.21875 | 4 | # insertion sort
# start with element at i= and place that element in sorted sequence from to n-1
#sorting ascending a number
def insertion_sort_asc(arr):
for i in range(1,len(arr)):
temp=arr[i]
j=i-1
while j>=0 and arr[j]>temp:
arr[j+1]=arr[j]
j-=1
arr[j+1]=temp
def bubble_sort(arr):
for i in range(0,len(arr)):
for j in range(1,len(arr)):
if arr[j-1]>arr[j]:
temp=arr[j]
arr[j-1],arr[j]=temp,arr[j-1]
def selection_sort_desc(arr):
#finds by repeatedly finding the minimum part
for i in range(len(arr)):
max_index=i
for j in range(i+1,len(arr)):
if arr[j]>arr[max_index]:
max_index=j
arr[i],arr[max_index]=arr[max_index],arr[i]
print(insertion_sort_asc([3, 9, 2, 5, 90, 3, 2]))
arr=[3, 9, 2, 5, 90, 3, 2]
insertion_sort_asc(arr)
print(arr)
arr=[3, 9, 2, 5, 90, 3, 2]
bubble_sort(arr)
print(arr)
arr=[3, 9, 2, 5, 90, 3, 2]
selection_sort_desc(arr)
print(arr) | false |
cf1735e12cb76047597f959d4c82844ed5b9dc85 | JosephCamarena/Python | /2 converter.py | 412 | 4.21875 | 4 | #converting kilometers to miles
print("How many kilometers did you cycle today?")
kms = input()
miles = float(kms)/1.60934
miles = round(miles, 2)
print(f"Your {kms}km ride was {miles}mi")
# print(f"That is equal to {round(miles, 2)} miles") | returns miles with 2 decimal places
# print(f"That is equal to {miles} miles") | prints a long decimal number
# round(thing to round, how many decimal points)
| true |
d48159f7441a31f74c6405ba0ddd44e0621d0d00 | marcusshepp/dotpy | /training/guessinggame.py | 779 | 4.21875 | 4 | # Guessing game
# creating var for the entry and the answer
n = 0
actualnum = 50
# make sure that the program loops if the wrong answer is entered
while n != actualnum:
# reassign n to the input value
n = int(raw_input("Guess a number: "))
# if the input is greater than the answer it will tell you
if n > actualnum:
print "Too high! "
# if the input is less than the answer it will tell you
elif n < actualnum:
print "Too low! "
# if the input is equal to the answer it will tell you
else:
print "There we go!"
# keep track of how many times the user guesses
total = 0
while n != actualnum:
total += n
if total == 3:
print "that took you three tries"
elif total == 2:
print "that took two tries"
elif total == 1:
print "that only took one try" | true |
c1faf4dd0031b1e8ff69173bdecb1c10a17e692b | kylehatcher/WOBC-Python | /exercise3.py | 1,986 | 4.65625 | 5 | import sys
"""
For this exercise, you will be given at least three command line arguments. The first two will be integers; the third will be a string. Use what you have learned so far to create a program which accomplishes the following:
Prints the larger of the two integers. If they are equal, do not print either one.
If the word "time" appears in the string, print the sum of the integers.
If both the integers are odd, or one of them is a multiple of 3, print the string.
If there are more than three command line arguments (excluding the filename), print the word "error".
"""
def exercise3(args):
args = validate(args)
#Prints the larger of the two integers. If they are equal, do not print either one.
if args[0] > args[1]:
print(args[0])
elif args[1] > args[0]:
print(args[1])
#If the word "time" appears in the string, print the sum of the integers.
if 'time' in args[2]:
print(args[0]+args[1])
#If both the integers are odd, or one of them is a multiple of 3, print the string
if (args[0]%2 and args[1]%2) or not (args[0]%3) or not (args[1]%3):
print(args[2])
#If there are more than three command line arguments (excluding the filename), print the word "error".
if len(args) > 3:
print('error')
def validate(args):
"""Validates that 1st and 2nd arguments are integers and 3rd is a string"""
try:
if len(args) < 3:
raise Exception("Not enough arguments")
args[0] = int(args[0])
args[1] = int(args[1])
except Exception as e:
print(e)
print('\nPlease provide at least 2 integers followed by 1 string')
exit()
return(args)
if __name__ == "__main__":
#Make sure there are enough arguments given to run
if len(sys.argv) > 1:
#Strip the script filename we don't need it
exercise3(sys.argv[1:])
else:
#Pass it on through and let the vaildater do it's job
validate(sys.argv) | true |
b9efaf0f23d21b4ed3d145d9a3a76fd761ca3c4f | SnehaAS-12/Day-17 | /day17.py | 1,264 | 4.21875 | 4 | #Create a connection for DB and print the version using a python program
import sqlite3
try:
sqlite_Connection = sqlite3.connect('temp.db')
conn = sqlite_Connection.cursor()
print("\nDatabase created and connected to SQLite.")
sqlite_select_Query = "select sqlite_version();"
conn.execute(sqlite_select_Query)
record = conn.fetchall()
print("SQLite Database Version is: ", record)
conn.close()
except sqlite3.Error as error:
print("Error while connecting to sqlite.", error)
finally:
if (sqlite_Connection):
sqlite_Connection.close()
print("The SQLite connection is closed.")
#Create a multiple tables & insert data in table
import sqlite3
conn = sqlite3 . connect ( 'mydatabase.db' )
cursor = conn.cursor ()
cursor.execute("CREATE TABLE Salesman12(salesman_id n(5), name char(30), city char(35), commission decimal(7,2));")
s_id = input('\n\nSalesman ID:')
s_name = input('Name:')
s_city = input('City:')
s_commision = input('Commission:')
cursor.execute("""INSERT INTO salesman(salesman_id, name, city, commission)VALUES (?,?,?,?)""", (s_id, s_name, s_city, s_commision))
conn.commit ()
print ( 'Data entered successfully.' )
conn . close ()
if (conn):
conn.close()
print("The SQLite connection is closed.") | true |
897d2a1ac8d012db4a7b1a4a0ba438208975b65b | FractalArt/chaos_exercises | /ch3/ex3_4_2.py | 1,822 | 4.34375 | 4 | """
This script generates the plots to provide graphs helping to solve exercise 3.4.2.
The differential equation is given by:
x' = r*x - sinh(x)
An obvious fixed point is x* = 0 and the remaining piece of the bifurcation diagram
can be drawn by inverting the plot of r(x) = sinh(x) / x, albeit without the stability
information.
"""
import matplotlib.pyplot as plt
import numpy as np
def r(x):
"""
Express r in terms of the fixed point x*.
This is done to obtain the bifurcation diagram for x* != 0.
"""
return np.sinh(x) / x
if __name__ == "__main__":
# Plot r as a function of the fixed points
# Inverting the axes of this plot, we obtain the bifurcation
# diagram, albeit without the stability information (although,
# if we know the general appearance of sub and supercritcal
# pitchfork bifurcations, we can infer the stability of the
# fixed points from the information of whether they appear
# to the right of the bifurcation (stable) or to the left (unstable)).
x_vals = np.linspace(-1, 1, 1000)
r_vals = r(x_vals)
plt.plot(x_vals, r_vals)
plt.title(r"$r$ as a function of the fixed points $x^*$")
plt.xlabel(r"$x^*$")
plt.ylabel(r"$r(x^*)$")
plt.show()
# Compare rx and sinh(x) to determine the fixed points (from their intersection)
# as well as their stability.
x_vals = np.linspace(-3, 3, 1000)
def rx(x, r):
return x*r
plt.plot(x_vals, np.sinh(x_vals), label=r"$\sinh(x)$")
plt.plot(x_vals, rx(x_vals, -1), label=r"r=-1")
plt.plot(x_vals, rx(x_vals, 0), label=r"r=0")
plt.plot(x_vals, rx(x_vals, 1), label=r"r=1")
plt.plot(x_vals, rx(x_vals, 2), label=r"r=2")
plt.title(r"$rx$ vs $\sinh(x)$")
plt.xlabel("$x$")
plt.ylabel("$f(x)$")
plt.legend()
plt.show()
| true |
19c6e2edacac2cefee48d45b5ee5854d9f55023e | leetcode-notes/UniversityAssignments | /Programming in Python/Laboratorul 1/problem_5.py | 1,407 | 4.25 | 4 | def get_spiral_order(matrix):
"""
:param matrix: the matrix to be traversed in spiral order
:return: the string that contains the spiral order
"""
spiral_order = ""
top = 0
left = 0
bottom = len(matrix) - 1
right = len(matrix[0]) - 1
direction = 0
while top <= bottom and left <= right:
if direction == 0: # left to right
for index in range(left, right + 1):
spiral_order += matrix[top][index]
top += 1
elif direction == 1: # top to bottom
for index in range(top, bottom + 1):
spiral_order += matrix[index][right]
right -= 1
elif direction == 2: # right to left
for index in range(right, left - 1, -1):
spiral_order += matrix[bottom][index]
bottom -= 1
elif direction == 3: # bottom to top
for index in range(bottom, top - 1, -1):
spiral_order += matrix[index][left]
left += 1
direction = (direction + 1) % 4
return spiral_order
def main():
"""
Prints the string that contains a matrix of characters in spiral order.
"""
matrix = [["f", "i", "r", "s"], ["n", "_", "l", "t"], ["o", "b", "a", "_"], ["h", "t", "y", "p"]]
print(get_spiral_order(matrix))
if __name__ == '__main__':
main()
| true |
a29320b93f27b568e1c00a104907914ec140eba2 | ragaranjith/assignments | /finding diameter area and circumference for the given radius of a circle.py | 335 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 10:48:57 2020
@author: ragar
"""
#program to find the area circumference and perimeter of the circle for a given radius
r=float(input("enter the radius of the circle:"))
diam=2*r
circumference=2*(22/7)*r
area=(22/7)*(r**2)
print(diam)
print(circumference)
print(area) | true |
fb7e8b425fe5eb41ca3b99011866d00e277608c1 | EmineKala/Python-101 | /Python/Hafta4/alistirma1.py | 643 | 4.25 | 4 | #romeo.txt dosyasını açın ve satır satır okuyun. Her satırı, split() fonksiyonunu kullanarak satırı bir String listesine bölün .
#Program bir kelime listesi oluşturmalıdır.
#Her satırdaki her kelime için, kelimenin zaten listede olup olmadığını kontrol edin ve eğer listedeyse tekrar eklemeyin.
#Program tamamlandığında, ortaya çıkan kelimeleri alfabetik sıraya göre sıralayın ve yazdırın.
list = list()
file = open( "romeo.txt")
for line in file:
print(line.rstrip())
words = (line.lower()). split()
for word in words:
if word not in list:
list.append(word)
list.sort()
print(list)
| false |
039c48cd656ae766b90117c2330514a47c8bef75 | gabrielSSimoura/ListEnds | /main.py | 500 | 4.15625 | 4 | # Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25])
# and makes a new list of only the first and last elements of the given list.
# For practice, write this code inside a function
import random
def generateList():
randomlist = []
for i in range(0, 15):
n = random.randint(1, 30)
randomlist.append(n)
return randomlist
def main():
list = generateList()
newLis = [list[0], list[-1]]
print(list)
print(newLis)
main()
| true |
88474861f412b17f6f719da9b8d05a790d6bbe07 | agarrharr/code-rush-101 | /something-learned/Algorithms and Data-Structures/python/linkedlist/swap_in_pairs.py | 921 | 4.125 | 4 | """
Given a linked list, swap every two adjacent nodes
and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space.
You may not modify the values in the list,
only nodes itself can be changed.
"""
class Node:
def __init__(self, x=0):
self.val = x
self.next = None
def swap_pairs(head:"Node")->"Node":
if not head:
return head
start = Node()
pre = start
pre.next = head
while pre.next and pre.next.next:
a = pre.next
b = pre.next.next
pre.next, a.next, b.next = b, b.next, a
pre = a
return start.next
if __name__ == "__main__":
n = Node(1)
n.next = Node(2)
n.next.next = Node(3)
n.next.next.next = Node(4)
res = swap_pairs(n)
while res:
print(res.val, end=" ")
res = res.next
print("should be 2 1 4 3 ")
| true |
480037b23ddda97ebf393d7858b3df05fc234c8e | yolotester/learngit | /HmVideoCode/hm_python_basic/05_高级数据类型/hm_15_字符串统计操作.py | 414 | 4.28125 | 4 | str = "hello python"
# 1、统计字符串长度
print(len(str))
# 2、统计 子字符串 在 字符串中出现的次数
print(str.count("o"))
print(str.count("ooo")) # 子字符串在字符串中不存在,返回0
# 3、某一个 子字符串 第一次出现的 索引
print(str.index("o"))
print(str.index("ooo")) # 注意:子字符串在字符串中不存在,报错!ValueError: substring not found | false |
6c707fbac911c6cd4b8a3da7a73a13fb57a08d6a | koking0/Algorithm | /LeetCode/Problems/92.Reverse Linked List II/92.Reverse Linked List II.py | 2,118 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-H -*-
# @Time : 2020/1/29 21:37
# @File : 92.Reverse Linked List II.py
# ----------------------------------------------
# ☆ ☆ ☆ ☆ ☆ ☆ ☆
# >>> Author : Alex
# >>> QQ : 2426671397
# >>> Mail : alex18812649207@gmail.com
# >>> Github : https://github.com/koking0
# ☆ ☆ ☆ ☆ ☆ ☆ ☆
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
global current_head
if m == n:
return head
if m == 1:
head_node, tail_node, help_node = self.reversed(head, n - m + 1)
tail_node.next = help_node
return head_node
count = 1
need_head = head
while head:
if count == m:
head_node, tail_node, help_node = self.reversed(head, n - m + 1)
current_head.next = head_node
head = tail_node
head.next = help_node
count += 1
current_head = head
head = head.next
return need_head
def reversed(self, head: ListNode, num):
"""反转指定数目的链表,返回反转后的头节点、尾节点和下一段链表的头结点"""
count, head_node, tail_node, help_node = 0, None, None, None
while count < num:
help_node = head.next
head.next = head_node
head_node = head
head = help_node
count += 1
if tail_node is None:
tail_node = head_node
return head_node, tail_node, help_node
if __name__ == '__main__':
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node5.next = None
a = Solution()
node = a.reverseBetween(node1, 2, 4)
while node:
print(node.val)
node = node.next
| false |
5856b2c37361e5f44517e430032994a7aa290f0d | koking0/Algorithm | /算法与数据结构之美/Algorithm/Recursion/01.Hanoi/01.Hanoi.py | 413 | 4.125 | 4 | def hanoi(n, start, helper, target):
"""
:param n: 表示盘子的个数
:param start: 表示起始柱子
:param helper: 表示辅助柱子
:param target: 表示目标柱子
"""
if n > 0:
hanoi(n - 1, start, target, helper)
print(f"Move {n} from {start} to {target}")
hanoi(n - 1, helper, start, target)
if __name__ == '__main__':
hanoi(3, "A", "B", "C")
| false |
34715ba86482021eeafec1c429a7dfbf6d1a0a2f | dwrowell/Automate-the-boring-stuff-code-practice | /collatz.py | 351 | 4.25 | 4 | def collatz(number):
while number>1:
if number%2==0:
number = number//2
print(number)
elif number%2!=0:
number = (3*number+1)
print(number)
print('COLLLLLAAAATZZZ!!!!!!!')
print('Please enter a number')
number = int(input())
collatz(number)
| false |
95b4067ef7f4eb0e312cac5d63d01052749c8662 | HomeroValdovinos/hello-world | /Cursos/devf/Lesson05/indexing_tuples.py | 519 | 4.1875 | 4 | # -*- coding: utf-8 -*-
def indexing_tuplas():
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print "Esto trae n_tuple", n_tuple
print(n_tuple[1][2])
indexing_tuplas()
def cambiando_elementos():
my_tuple = (4, 2, 3, [6, 5])
my_tuple[3][0] = 9 # Con esto cambiamos el valor la posicion 3 ([6,5]), en especifico el valor 0 (6) y se cambia a 9
print (my_tuple)
# my_tuple[1] = 9 #Esto no se puede, porque tuple no soporta la asignación de elmentos
cambiando_elementos()
| false |
dba98afd0fe89025a09d987802a855949f8c88eb | Bl4ky113/clasesHaiko2021 | /listas.py | 1,212 | 4.53125 | 5 | # Son arrays o listas de datos que podemos crear
# Sus index o posiciones inician desde 0 hasta la cantidad de datos que tenga
list = [10, 11, 12, 5, 15, 21]
# Se usa el [] para obtener los datos dentro de esta lista y dentro el index del dato
print(list[0])
print(list[2])
print(list[5])
# Se usan valores negativos para ir en la dirección inversa de los datos
# No se puede usar -0, solo -1
print(list[-1])
print(list[-3])
try:
print(list[-6])
except:
print("Se pasa del largo del array")
# Se puede obtener una parte de los datos usando "Slicing", poniendo un index [1], dos puntos [1:] y otro index [1:5]
# Se va a posicionar en el 1er index y va a mostrar todos los datos entre ese y el 2do index
# O se puede dejar en blanco el 1er index y va a mostrar todos los datos desde el inicio hasta el 2do index [:3]
# O se puede dejar en blanco el 2do index y va a mostrar todos los datos desde el 1er index hasta el final [1:]
print(list[1:5])
print(list[:3])
print(list[1:])
# Existen diferentes metodos para los Arrays, los cuales nos permiten modificar, organizar, eliminar, agregar los datos y los index de estos
print(list.sort(reverse = True))
print(list.append(120))
print(list.reverse())
| false |
1453a9b22cdadbf0ba92ffe363e392f6fca11d50 | roshanrobotics/python-program | /longest.py | 222 | 4.28125 | 4 | List= input("Please input a List of words to checked : ")
lenght = 0
for words in List.split():
if len(words) > lenght:
lenght = len(words)
print ("The lenght of longest word is",lenght)
| true |
c88f06340bae9353130c64c1ee25be89474758fa | Akavov/PythonDss | /SLice/slic.py | 573 | 4.15625 | 4 | #demonstrate slice of strings
word="pizza"
print(word[:])
print(
"""
0 1 2 3 4 5
+--+--+--+--+--+
| p| i| z| z| a|
+--+--+--+--+--+
-5-4 -3 -2 -1
"""
)
print("Enter start and end index for slice 'pizza' which you want")
print("Press Enter to exit, not enter start index")
start=None
while start!="":
start=(input("\nStart index: "))
if start:
start=int(start)
finish=int(input("End index: "))
print("Slice word[",start,":",finish,"] looks like",end=" ")
print(word[start:finish])
input("\n\nPress enter to exit")
| false |
672fbf5a5eef6474b757ec8148bc7d69b9c261d9 | Akavov/PythonDss | /Records2/records2.py | 826 | 4.15625 | 4 | #Record v2.0
#Demonstrate nested sequences
scores=[]
choice=""
while choice=="":
print(
"""
Record 2.0
0- Exit
1- Show records
2- Append record
"""
)
choice=input("Your choice: ")
print()
#exit
if choice=="0":
print("Good bye!")
#show table of records
elif choice=="1":
print("Records \n")
print("NAME\tRESULT")
for entry in scores:
score,name=entry
print(name,"\t",score)
#add a score
elif choice=="2":
name=input("Input player`s name: ")
score=int(input("Input his result: "))
entry=(score,name)
scores.append(entry)
scores.sort(reverse=True)
scores=scores[:5]
#wrong choice
else:
print("Sorry, no such number in menu",choice)
input("\n\nPress enter to exit")
| true |
2569c868e5d9fb68e96b52b33daefce6720427ad | Ruben1819/Evidencia1-Estructura-de-datos- | /lista(ejer7).py | 1,301 | 4.21875 | 4 | separador = ("*" * 15) + "\n"
#creacion de listas
#lista vaica
lista_vacia=list()
otra_lista=[]
lista1 =[1 , 2 , 3 , 4]
print(lista1)
print(separador)
pass#sirve como marcador de posicion
lista1.append(5)
print(lista1)
lista1.append((6,7))#una lista puede ser elemento de otra lista
print(lista1)
print(separador)
pass
#remover elementos de una lista
lista1.remove((6,7))
print(lista1)
print(separador)
#ordenar elementos
#sort
lista_origi=[3,4,2]
print(lista_origi)
lista_origi.sort()
print(lista_origi)
pass
#sorted
lista_or2=[23,10,30,5]
lista_ordenada=sorted(lista_or2)
print(f"La lista original = {lista_or2} , y la version ordenada es {lista_ordenada}")
print(separador)
pass
#compresion de listas
print(f"Lista original = {lista_origi}")
#sin compresion
lista1_al_doble=[]
for valor in lista1:
lista1_al_doble.append(valor * 2 )
print(f"Lista resultante de cada elemento al doble = {lista1_al_doble}")
pass
#con compresion
lista1_al_doble =[valor * 2 for valor in lista1]
print(f"Mimos resultado pero con la compresion de listas ={lista1_al_doble}")
pass
#compresion pero con condicion
lista_valores_pares=[valor for valor in lista1 if (valor % 2 == 0)]
print(f"Solamente se agregan los elementos par : {lista_valores_pares}")
| false |
ef34da759b7dfac50ab1a7a0bb51627f3953d946 | lizhe960118/TowardOffer | /专题学习/树/isBalancedTree.py | 1,229 | 4.125 | 4 | """
Definition of TreeNode:
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class ReturnType:
def __init__(self, is_balanced, depth):
self.is_balanced = is_balanced
self.depth = depth
class Solution:
"""
@param root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def isBalanced(self, root):
# write your code here
result = self.helper(root)
return result.is_balanced
def helper(self, root):
if root is None:
return ReturnType(True, 0)
left = self.helper(root.left)
right = self.helper(root.right)
result = ReturnType(True, max(left.depth, right.depth) + 1)
if left.depth - right.depth > 1 or right.depth - left.depth > 1:
result.is_balanced = False
if (left.is_balanced != True) or (right.is_balanced != True):
result.is_balanced = False
return result
if __name__ == '__main__':
node1 = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(3)
node1.left = node2
node1.right = node3
root = node1
print(Solution().isBalanced(root)) | true |
4c4ecf625b4ee3eee47cdf2ef4d0ca86f1c400a1 | akshar-raaj/Project-Euler | /euler4.py | 802 | 4.21875 | 4 | #!/usr/bin/python
def isPalindrome(number):
"""stringRepresentationOfNumber=str(number)
if stringRepresentationOfNumber == stringRepresentationOfNumber[::-1]:
return True
return False"""
return str(number) == str(number)[::-1]
def findHighestPalindrome():
"""highestPalindrome=1
for i in range(100,1000):
for j in range(100,1000):
product=i*j
if(isPalindrome(product) and product>highestPalindrome):
highestPalindrome=product"""
numbers = (i * j for i in xrange(100, 1000) for j in xrange(100, 1000) if isPalindrome(i * j))
highestPalindrome = max(numbers)
print "Largest palindrome made from the product of two 3-digit numbers is %d" % (highestPalindrome,)
findHighestPalindrome()
| true |
bcf258d4477e47281b59017a098ea7dd313d34d0 | m-RezaFahlevi/we_still_learning_gitGithub | /pythonFiles/linked_list.py | 1,589 | 4.375 | 4 | #Create Node Class
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
self.previous = None
#We still have no idea what is this code
#use for :)
def __str__(self):
return str(data)
#method for print the list
def __print_list_forwards__(self):
temp = self
while(temp):
print(f'{temp.data} --> ', end="")
temp = temp.next
print(None)
def __print_list_backwards__(self):
temp = self
while(temp):
print(f'{temp.data} --> ', end="")
temp = temp.previous
print(None)
def __display_the_address__(self):
temp = self
while(temp):
print(f'{hex(id(temp))} --> ', end="")
temp = temp.next
print(None)
#Allocate the data for each node
st_node = Node("st_data")
nd_node = Node("nd_data")
thrd_node = Node("thrd_data")
#Linked the node
st_node.next = nd_node
nd_node.next = thrd_node
nd_node.previous = st_node
thrd_node.previous = nd_node
#use the method
st_node.__print_list_forwards__()
thrd_node.__print_list_backwards__()
st_node.__display_the_address__()
#Insert new node between the linked_node
new_node = Node("new_data")
nd_node.next = new_node
new_node.previous = nd_node
new_node.next = thrd_node
print("\nAfter insert the new node between linked_node\n")
st_node.__print_list_forwards__()
thrd_node.__print_list_backwards__()
st_node.__display_the_address__()
#print(hex(id(st_node))) // This is for display the memory address of variable
| true |
367faf082af1ce659525413509732a7faa968b8e | slashtea/Hands-On-python | /lists.py | 447 | 4.3125 | 4 | __author__ = 'shannon'
# Lists are mutable (changeable) sequences of objects.
fruits = ['apple', 'strawberry', 'kiwi']
for eachFruit in fruits:
print(eachFruit)
# Print the first element.
print('\nFirst fruit', fruits[0])
# Append a new Element.
fruits.append('banana')
# Display new Elements.
for eachFruit in fruits:
print(eachFruit)
# List constructor
newList = list('characters')
print('\n')
for list in newList:
print(list)
| true |
35a0e66776f0e7f42cfa6baeacb32312056f81bc | bksahu/dsa | /dsa/patterns/two_pointers/triplet_with_smaller_sum.py | 1,146 | 4.25 | 4 | """
Given an array arr of unsorted numbers and a target sum, count all triplets in it such
that arr[i] + arr[j] + arr[k] < target where i, j, and k are three different indices.
Write a function to return the count of such triplets.
Example 1:
Input: [-1, 0, 2, 3], target=3
Output: 2
Explanation: There are two triplets whose sum is less than the target: [-1, 0, 3], [-1, 0, 2]
Example 2:
Input: [-1, 4, 2, 1, 3], target=5
Output: 4
Explanation: There are four triplets whose sum is less than the target:
[-1, 1, 4], [-1, 1, 3], [-1, 1, 2], [-1, 2, 3]
"""
def search_pair(arr, firstIdx, target):
first = arr[firstIdx]
left, right = firstIdx+1, len(arr)-1
curr_count = 0
while left < right:
if arr[left] + arr[right] + first < target:
curr_count = right - left
left += 1
else:
right -= 1
return curr_count
def solution(arr, target):
arr.sort()
count = 0
for i in range(len(arr)):
count += search_pair(arr, i, target)
return count
if __name__ == "__main__":
print(solution([-1, 0, 2, 3], 3))
print(solution([-1, 4, 2, 1, 3], 5)) | true |
39d355a09c23c73ad90c60a9e98d0ac281afd4c9 | bksahu/dsa | /dsa/patterns/sliding_window/permutation_in_a_str.py | 1,964 | 4.21875 | 4 | """
Permutation in a String
#######################
Given a string and a pattern, find out if the string contains any permutation of the pattern.
Permutation is defined as the re-arranging of the characters of the string. For example, “abc”
has the following six permutations:
abc
acb
bac
bca
cab
cba
If a string has ‘n’ distinct characters it will have n! permutations.
Example 1:
Input: String="oidbcaf", Pattern="abc"
Output: true
Explanation: The string contains "bca" which is a permutation of the given pattern.
Example 2:
Input: String="odicf", Pattern="dc"
Output: false
Explanation: No permutation of the pattern is present in the given string as a substring.
Example 3:
Input: String="bcdxabcdy", Pattern="bcdyabcdx"
Output: true
Explanation: Both the string and the pattern are a permutation of each other.
Example 4:
Input: String="aaacb", Pattern="abc"
Output: true
Explanation: The string contains "acb" which is a permutation of the given pattern.
"""
from collections import Counter
def solution(s, p):
if len(p) > len(s):
return False
window_start, matched, pattern_frequency = 0, 0, Counter(p)
for window_end in range(len(s)):
right_char = s[window_end]
if right_char in pattern_frequency:
pattern_frequency[right_char] -= 1
if pattern_frequency[right_char] == 0:
matched += 1
if matched == len(pattern_frequency):
return True
if window_end >= len(p) - 1:
left_char = s[window_start]
if left_char in pattern_frequency:
if pattern_frequency[left_char] == 0:
matched -= 1
pattern_frequency[left_char] += 1
window_start += 1
return False
if __name__ == "__main__":
print(solution("oidbcaf", "abc"))
print(solution("odicf", "dc"))
print(solution("bcdxabcdy", "bcdyabcdx"))
print(solution("aaacb", "abc"))
| true |
2e3fa7c6b95241c6793558040c65718d27a77095 | bksahu/dsa | /dsa/patterns/k_way_merge/k_smallest_number_in_m_sorted_array.py | 1,006 | 4.28125 | 4 | """
Given ‘M’ sorted arrays, find the K’th smallest number among all the arrays.
Example 1:
Input: L1=[2, 6, 8], L2=[3, 6, 7], L3=[1, 3, 4], K=5
Output: 4
Explanation: The 5th smallest number among all the arrays is 4, this can be verified from the merged
list of all the arrays: [1, 2, 3, 3, 4, 6, 6, 7, 8]
Example 2:
Input: L1=[5, 8, 9], L2=[1, 7], K=3
Output: 7
Explanation: The 3rd smallest number among all the arrays is 7.
"""
from heapq import heappush, heappop
def find_kth_smallest(lists, k):
minHeap = []
for i, l in enumerate(lists):
heappush(minHeap, (l[0], 0, i))
while minHeap and k:
currNum, currNumIdx, currListIdx = heappop(minHeap)
k -= 1
if currNumIdx+1 < len(lists[currListIdx]):
heappush(minHeap, (lists[currListIdx][currNumIdx+1], currNumIdx+1, currListIdx))
return currNum
if __name__ == "__main__":
print(find_kth_smallest([[2,6,8], [3,6,7], [1,3,4]], 5))
print(find_kth_smallest([[5,8,9], [1,7]], 3)) | true |
bfdfdfc12e3852a88e1f26d8e677b9a3588a2ab6 | bksahu/dsa | /dsa/patterns/fast_and_slow_pointers/rearrange_linkedlist.py | 1,743 | 4.28125 | 4 | """
Given the head of a Singly LinkedList, write a method to modify the
LinkedList such that the nodes from the second half of the LinkedList
are inserted alternately to the nodes from the first half in reverse order.
So if the LinkedList has nodes 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null, your method
should return 1 -> 6 -> 2 -> 5 -> 3 -> 4 -> null.
Your algorithm should not use any extra space and the input LinkedList should be
modified in-place.
Example 1:
Input: 2 -> 4 -> 6 -> 8 -> 10 -> 12 -> null
Output: 2 -> 12 -> 4 -> 10 -> 6 -> 8 -> null
Example 2:
Input: 2 -> 4 -> 6 -> 8 -> 10 -> null
Output: 2 -> 10 -> 4 -> 8 -> 6 -> null
"""
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def print_list(self):
temp = self
while temp is not None:
print(str(temp.value) + " ", end='')
temp = temp.next
print()
def reverse(head):
prev = None
while head:
next = head.next
head.next = prev
prev = head
head = next
return prev
def reorder(head):
slow, fast = head, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
second_half = reverse(slow)
curr = head
while second_half.next:
next = curr.next
curr.next = Node(value=second_half.value)
curr.next.next = next
curr = next
second_half = second_half.next
if __name__ == "__main__":
head = Node(2)
head.next = Node(4)
head.next.next = Node(6)
head.next.next.next = Node(8)
head.next.next.next.next = Node(10)
head.next.next.next.next.next = Node(12)
head.print_list()
reorder(head)
head.print_list() | true |
f36dcd3cdc73c3b7ea5a88c74a0bcb4bf2bc7c8a | bksahu/dsa | /dsa/patterns/dp/matrix_chain_multiplication/palindrome_partition.py | 1,198 | 4.59375 | 5 | """
Given a string, a partitioning of the string is a palindrome partitioning if every substring of the partition is a palindrome.
For example, “aba|b|bbabb|a|b|aba” is a palindrome partitioning of “ababbbabbababa”. Determine the fewest cuts needed for a
palindrome partitioning of a given string. For example, minimum of 3 cuts are needed for “ababbbabbababa”. The three cuts are
“a|babbbab|b|ababa”. If a string is a palindrome, then minimum 0 cuts are needed. If a string of length n containing all different
characters, then minimum n-1 cuts are needed.
"""
def palindromePartition(s):
def isPalindrome(x):
return x[::-1] == x
def backtrack(i, j):
if i >= j or isPalindrome(s[i:j+1]):
return 0
minCuts = float("inf")
for k in range(i, j):
minCuts = min(
minCuts,
1 + backtrack(i,k) + backtrack(k+1, j)
)
return minCuts
return backtrack(0, len(s)-1)
if __name__ == "__main__":
print(palindromePartition("geek"))
print(palindromePartition("aaaa"))
print(palindromePartition("abcde"))
print(palindromePartition("abbac")) | true |
29f01caf0b3308256e79fc91dd622f942e0e0d24 | bksahu/dsa | /dsa/patterns/fast_and_slow_pointers/palindrome_linkedlist.py | 1,571 | 4.1875 | 4 | '''
Given the head of a Singly LinkedList, write a method to check if the LinkedList
is a palindrome or not.
Your algorithm should use constant space and the input LinkedList should be in the original
form once the algorithm is finished. The algorithm should have O(N)O(N) time complexity where
‘N’ is the number of nodes in the LinkedList.
Example 1:
Input: 2 -> 4 -> 6 -> 4 -> 2 -> null
Output: true
Example 2:
Input: 2 -> 4 -> 6 -> 4 -> 2 -> 2 -> null
Output: false
'''
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def reverse(head):
prev = None
while head:
next = head.next
head.next = prev
prev = head
head = next
return prev
def is_palindromic_linked_list(head):
slow, fast = head, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
slow = reverse(slow)
temp = slow
while slow and head:
if slow.value != head.value:
break
slow = slow.next
head = head.next
reverse(temp)
return True if not slow or not head else False
if __name__ == "__main__":
head = Node(2)
head.next = Node(4)
head.next.next = Node(6)
head.next.next.next = Node(6)
head.next.next.next.next = Node(4)
head.next.next.next.next.next = Node(2)
print("Is palindrome: " + str(is_palindromic_linked_list(head)))
head.next.next.next.next.next.next = Node(2)
print("Is palindrome: " + str(is_palindromic_linked_list(head))) | true |
69474616e1d72950ecc024ee19bc3fb7349df336 | bksahu/dsa | /dsa/patterns/bitwise_xor/image_horizontal_flip.py | 1,383 | 4.59375 | 5 | """
Given a binary matrix representing an image, we want to flip the image horizontally, then invert it.
To flip an image horizontally means that each row of the image is reversed. For example, flipping [0, 1, 1] horizontally results in [1, 1, 0].
To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [1, 1, 0] results in [0, 0, 1].
Example 1:
Input: [
[1,0,1],
[1,1,1],
[0,1,1]
]
Output: [
[0,1,0],
[0,0,0],
[0,0,1]
]
Explanation: First reverse each row: [[1,0,1],[1,1,1],[1,1,0]].
Then, invert the image: [[0,1,0],[0,0,0],[0,0,1]]
Example 2:
Input: [
[1,1,0,0],
[1,0,0,1],
[0,1,1,1],
[1,0,1,0]
]
Output: [
[1,1,0,0],
[0,1,1,0],
[0,0,0,1],
[1,0,1,0]
]
"""
# def flip(image):
# flipped_image = [[] for _ in range(len(image))]
# for i in range(len(image)):
# for j in range(len(image[i])-1, -1, -1):
# flipped_image[i] += image[i][j] ^ 1,
# return flipped_image
def flip(image):
c = len(image)
for row in image:
for i in range((c+1)//2):
row[i], row[c - i - 1] = row[c - i - 1] ^ 1, row[i] ^ 1
return image
if __name__ == "__main__":
print(flip([
[1, 0, 1],
[1, 1, 1],
[0, 1, 1]
]))
print(flip([
[1, 1, 0, 0],
[1, 0, 0, 1],
[0, 1, 1, 1],
[1, 0, 1, 0]
]))
| true |
87d3a102983ea5dc59029cf4f7eb2455c9f85372 | bksahu/dsa | /dsa/patterns/depth_first_search/diameter_of_tree.py | 1,519 | 4.34375 | 4 | """
Given a binary tree, find the length of its diameter. The diameter of a tree is the number of nodes on
the longest path between any two leaf nodes. The diameter of a tree may or may not pass through the root.
Note: You can always assume that there are at least two leaf nodes in the given tree.
"""
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class TreeDiameter:
def __init__(self):
self.treeDiameter = 0
def find_diameter(self, root):
self.dfs(root)
return self.treeDiameter
def dfs(self, root):
if not root:
return 0
leftHeight = self.dfs(root.left)
rightHeight = self.dfs(root.right)
self.treeDiameter = max(self.treeDiameter, leftHeight + rightHeight + 1)
return max(leftHeight, rightHeight) + 1
if __name__ == "__main__":
treeDiameter = TreeDiameter()
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.right.left = TreeNode(5)
root.right.right = TreeNode(6)
print("Tree Diameter: " + str(treeDiameter.find_diameter(root)))
root.left.left = None
root.right.left.left = TreeNode(7)
root.right.left.right = TreeNode(8)
root.right.right.left = TreeNode(9)
root.right.left.right.left = TreeNode(10)
root.right.right.left.left = TreeNode(11)
print("Tree Diameter: " + str(treeDiameter.find_diameter(root))) | true |
76627309af6320971e9c0a2f07c42d3efd7eecbf | bksahu/dsa | /dsa/patterns/merge_intervals/max_cpu_load_v2.py | 1,461 | 4.1875 | 4 | '''
We are given a list of Jobs. Each job has a Start time, an End time, and a CPU load when
it is running. Our goal is to find the maximum CPU load at any time if all the jobs are
running on the same machine.
Example 1:
Jobs: [[1,4,3], [2,5,4], [7,9,6]]
Output: 7
Explanation: Since [1,4,3] and [2,5,4] overlap, their maximum CPU load (3+4=7) will be when both the
jobs are running at the same time i.e., during the time interval (2,4).
Example 2:
Jobs: [[6,7,10], [2,4,11], [8,12,15]]
Output: 15
Explanation: None of the jobs overlap, therefore we will take the maximum load of any job which is 15.
Example 3:
Jobs: [[1,4,2], [2,4,1], [3,6,5]]
Output: 8
Explanation: Maximum CPU load will be 8 as all jobs overlap during the time interval [3,4].
'''
def find_max_cpu_load(starts, ends, loads):
starts.sort()
ends.sort()
max_load = loads[0]
i, j = 1, 0
res = 0
while i < len(starts) and j < len(ends):
if starts[i] <= ends[j]:
max_load += loads[i]
i += 1
else:
max_load -= loads[j]
j += 1
res = max(res, max_load)
return res
if __name__ == "__main__":
print("Maximum CPU load at any time: " + str(find_max_cpu_load([1,2,7], [4,5,9], [3,4,6])))
print("Maximum CPU load at any time: " + str(find_max_cpu_load([6,2,8], [7,4,12], [10,11,15])))
print("Maximum CPU load at any time: " + str(find_max_cpu_load([1,2,3], [4,4,6], [2,1,5])))
| true |
5f240e667e9d851ba8b677d26b17dd3b4e034d18 | roselandroche/cs-module-project-hash-tables | /applications/crack_caesar/crack_caesar.py | 653 | 4.125 | 4 | # Use frequency analysis to find the key to ciphertext.txt, and then
# decode it.
# Your code here
'''
U
Input -> text file
Output -> print decoded text
Rules
Punctuation and spaces are immutable
All input and output should be UPPERCASE
Task
Find the key to decode the cipher
Decode it
Show the plain text
Utilize frequency analysis to decode
P
Bring over list of chars in order of most frequent use
Create dict
key: alphabet chars (uppercase)
value: percentage of use
Match dict vs list letter percentages
Decode into new string
Print string
''' | true |
dd2b6899597fad48e3e85e036d9a613776a385b0 | IslaMurtazaev/PythonApplications | /CodeAcademy/classes.py | 2,115 | 4.21875 | 4 | # # Class definition
# class Animal(object):
# """Makes cute animals."""
# # For initializing our instance objects
# def __init__(self, name, age, is_hungry):
# self.name = name
# self.age = age
# self.is_hungry = is_hungry
# # Note that self is only used in the __init__()
# # function definition; we don't need to pass it
# # to our instance objects.
# zebra = Animal("Jeffrey", 2, True)
# giraffe = Animal("Bruce", 1, False)
# panda = Animal("Chad", 7, True)
# print(zebra.name, zebra.age, zebra.is_hungry)
# print(giraffe.name, giraffe.age, giraffe.is_hungry)
# print(panda.name, panda.age, panda.is_hungry)
# class Animal(object):
# """Makes cute animals."""
# is_alive = True
# def __init__(self, name, age):
# self.name = name
# self.age = age
# def description(self):
# print(self.name)
# print(self.age)
# hippo = Animal('Hippo',3)
# print(hippo.is_alive)
# hippo.description()
# class ShoppingCart(object):
# """Creates shopping cart objects
# for users of our fine website."""
# items_in_cart = {}
# def __init__(self, customer_name):
# self.customer_name = customer_name
# def add_item(self, product, price):
# """Add product to the cart."""
# if not product in self.items_in_cart:
# self.items_in_cart[product] = price
# print product + " added."
# else:
# print product + " is already in the cart."
# def remove_item(self, product):
# """Remove product from the cart."""
# if product in self.items_in_cart:
# del self.items_in_cart[product]
# print product + " removed."
# else:
# print product + " is not in the cart."
class Weird(object):
def __init__(self, x, y):
self.y = y
self.x = x
def getX(self):
return x
def getY(self):
return y
class Wild(object):
def __init__(self, x, y):
self.y = y
self.x = x
def getX(self):
return self.x
def getY(self):
return self.y
X = 7
Y = 8
print(w1.getY(X,Y)) | false |
667edf520740cf679a565ad5228adb78499a09fa | arvindreddyyedla/test | /emailValidation.py | 1,921 | 4.21875 | 4 | # A valid email address has four parts:
# Validation information was studied from https://help.returnpath.com/hc/en-us/articles/220560587-What-are-the-rules-for-email-address-syntax-
# Recipient name
# @ symbol
# Domain name
# Top-level domain
# Email validation and domain extraction program
#re module give us support to in python to test or check regular expresions
import re
regularExpEmail = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[a-z|A-Z]{2,}\b'
# explain above any character before . and @ followed by . and ensuring only one @ in the whole string
# function returning whether the given string is valid email or not
def returnEmailValidation(emailAddress):
# checking whether email is valid from method from the re module
# and verify the match
valid = re.fullmatch(regularExpEmail, emailAddress)
if (re.fullmatch(regularExpEmail, emailAddress)):
return 1
else:
return 0
#infinte loop intilization
while True:
# Input from user to get the email
email = input("\nPlease enter email to validate : ")
try:
# Checking for the empty string case and verify the same
if len(email) == 0:
print("Please enter a string to validate. Provided empty string")
continue
# email validation from the method
isEmailValid = returnEmailValidation(email) == 1
if isEmailValid:
splitEmail = email.split('@')
# extracting domain on verifying email in success case
print("\n"+email+" is valid email.\nYour domain name is "+splitEmail[1])
else:
print("\n"+email+" is not a valid email")
except:
print("\n"+email+" is not a valid email")
#expecting user input to verify the break the infinite loop.
userChoice = input("\nPress enter to provide more email ids or type 999 to exit: ")
if userChoice == "999":
break
print("\n") | true |
07330e4276117b86a53d325e3d8825d843d88a76 | Trishmcc/Pands-Problem-Sheet | /secondString.py | 415 | 4.25 | 4 | #This program will input a string and output every second letter in reverse order.
#Author:Trish OGrady
#I used input to input a string.
inputString = input ('Enter a string:')
#For my output I am reversing the string using splicing.
#I used two semi colons in square brackets to omit one or more characters.
#I used -2 as it allows every second letter to be chosen in reverse order.
print (inputString[::-2])
| true |
05b55f391d7507a0d1fbbcaf4795377956d080c9 | AkankshaKaple/Machine_Learning_Algorithms | /Matrices/Transpose.py | 284 | 4.1875 | 4 | # 6. Write a program to find transpose matrix of matrix Y in problem 1
Matrix_1 = [[12, 7, 3], [4, 5, 6], [7, 8, 9]]
Matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(len(Matrix_1)):
for j in range(len(Matrix_1[i])):
Matrix[j][i] = Matrix_1[i][j]
print(Matrix)
| false |
e1aa4654bf007a810208f5974bf6deaedec0a4c9 | AkankshaKaple/Machine_Learning_Algorithms | /Probability/Probability_24.py | 778 | 4.28125 | 4 | # 24. : Imagine that you have three urns that you cannot see into. Urn1 is 90% green balls and 10% red. Urn2 is
# 50% green and 50% blue. Urn3 is 20% green, 40% red, and 40% blue. You can’t tell which urn is which. You
# randomly select an urn and then randomly select a ball from it. The ball you drew is green.
# What is the probability that it came from urn1?
p_urn1 = p_urn2 = p_urn3 = 1/3
p_green_given_urn1 = 0.9
p_red_given_urn1 = 0.5
p_green_given_urn2 = 0.1
p_blue_given_urn2 = 0.5
p_green_given_urn3 = 0.2
p_red_given_urn3 = 0.4
p_blue_given_urn3 = 0.4
total_probability = (p_urn1 * p_green_given_urn1) + (p_urn2 * p_green_given_urn2)+ (p_urn3 * p_green_given_urn3)
p_urn1_given_green = (p_urn1 * p_green_given_urn1)/total_probability
print(p_urn1_given_green) | true |
8bdb08fb80ee2e9802fff089a13b302d0a9eca36 | AkankshaKaple/Machine_Learning_Algorithms | /Matrices/Multiplication_of_matrix_and_vector.py | 511 | 4.21875 | 4 | # 3. Write a program to perform multiplication of given matrix and vector
# X = [[ 5, 1 ,3], [ 1, 1 ,1], [ 1, 2 ,1]], Y = [1, 2, 3]
Matrix_1 = [[5, 1, 3], [1, 1, 1], [1, 2, 1]]
Row_Matrix = [1, 2, 3]
Resultant_Matrix = [0,0,0]
for row_index in range(len(Row_Matrix)):
value = 0
for column_index in range(len(Matrix_1[row_index])):
value = Matrix_1[column_index][row_index] * Row_Matrix[column_index] + value
# print(val)
Resultant_Matrix[row_index] = value
print(Resultant_Matrix) | false |
b6deffe45d6af191e5a732b74d1584b7481f7b4b | lorenzoMcD/Algorithms-and-Data-Structures | /Algorithms and Data Structures/recursion/reverseString.py | 385 | 4.25 | 4 | # write a recursive function called reverse which accepts a string and returns
# a new string in reverse
# ex.
# reverse(' awesome') // 'emosewa'
# reverse('rithmschool') // 'loohcsmhtir'
def reverse(someString):
if len(someString) < 1 :
return(someString)
temp = someString[0]
reverse(someString[1:])
print(temp, end='')
reverse('awesome')
| true |
e1e63ddf1cd779127c6f36a80de7d292a018a199 | lorenzoMcD/Algorithms-and-Data-Structures | /Algorithms and Data Structures/Searching Algorithms/naiveLinearSearch.py | 476 | 4.15625 | 4 | ## naive Linear Search implementation
# write function that accepts an array and value
# loop through the array and check if the current
# array element is wqual to the value
# If it is , return the index at which the element
# is found
# If the value is never found, return -1
def LinearSearch(arr,target):
i = 0
for item in arr:
if (item == target):
return i
i+=1
return -1
print(LinearSearch([1,2,3,4,5,6,7],5))
| true |
a41c0b7309d000cffd0dc7b92d6c8decd10dbee9 | Nomad95/python-50-interview-questions | /1/SingleElementList.py | 287 | 4.125 | 4 | """
Korzystając z podanej listy A, stwórz listę B, która będzie
zawierać tylko unikalne elementy z listy A.
A = [1,2,3,3,2,1,2,3]
"""
A = [1,2,3,3,2,1,2,3]
# 1
B = list(set(A))
print(B)
# 2
B2 = []
for el in A:
if not B2.__contains__(el):
B2.append(el)
print(B2) | false |
24e141613873cf15502c9b92b3fe018553d37356 | Nomad95/python-50-interview-questions | /4/2d3dArrays.py | 349 | 4.15625 | 4 | """
Jakiej struktury danych użyłbyś do zamodelowania
szafki, która ma 3 szuflady, a w każdej z nich znajdują się
3 przegródki?
Stwórz taki model i umieść stringa "długopis" w
środkowej przegródce środkowej szuflady.
"""
T = [[[""] for x in range(3)] for x in range(3)]
T[1][1][0] = "Długopis"
print(T)
for x in T:
print(x)
| false |
186738b9f7386068df83c22be29343a88fd6416c | Wh1te-Crow/text-analysis | /dict.py | 2,736 | 4.125 | 4 | alphabet = "абвгдежзийклмнопрстуфхцчшщыьэюя"
alphabet_with_space = " "+alphabet
Dictionary={}
def create_dict():
#'mws' monograms with spaces
#'bwsf'bigrams with spaces The first way to choose
#'bf' bigrams without spaces The first way to choose
#'bwss'bigrams with spaces The second way to choose
#'bs' bigrams with spaces The second way to choose
Dictionary['mws']=Dictionary['m']=Dictionary['bwsf']=Dictionary['bf']=Dictionary['bwss']=Dictionary['bs']={}
for i in alphabet_with_space:
for j in alphabet_with_space:
Dictionary['bwsf'][i+j]=0
for i in alphabet:
for j in alphabet:
Dictionary['bf'][i+j]=0
Dictionary['bwss'],Dictionary['bs']=Dictionary['bwsf'],Dictionary['bf']
for i in alphabet_with_space:
Dictionary['mws'][i]=0
def print_dict():
def print_table_ws(key):
Table = {}
Table[0] = list(" "+alphabet)
for i in range(1,32):
Table[i]=list(alphabet[i-1])
for i in range(len(alphabet)):
for j in range(len(alphabet)):
Table[i+1]=Table[i+1]+[(Dictionary[key][alphabet[i]+alphabet[j]])]
for i in range(0,32):
Temp=""
for j in range(len(Table[i])):
Temp+=str(Table[i][j])+(5-len(str(Table[i][j])))*" "
Table[i]=Temp[0:len(Temp)]
Temp=""
for i in range(len(Table)):
Temp+=str(Table[i])+"\n"
Table = Temp
print(Table)
def print_table(key):
Table = {}
Table[0] = list(" "+alphabet)
for i in range(1,32):
Table[i]=list(alphabet[i-1])
for i in range(len(alphabet)):
for j in range(len(alphabet)):
Table[i+1]=Table[i+1]+[(Dictionary[key][alphabet[i]+alphabet[j]])]
for i in range(0,32):
Temp=""
for j in range(len(Table[i])):
Temp+=str(Table[i][j])+(5-len(str(Table[i][j])))*" "
Table[i]=Temp[0:len(Temp)]
Temp=""
for i in range(len(Table)):
Temp+=str(Table[i])+"\n"
Table = Temp
print(Table)
def print_number_of_letters():
temp_arr=list(alphabet_with_space)
temp_Arr = []
for i in temp_arr:
temp_Arr+=[Dictionary['mws'][i]]
Flag = True
while Flag:
Flag = False
for i in range(len(temp_Arr)-1):
if temp_Arr[i]<temp_Arr[i+1]:
temp_Arr[i],temp_Arr[i+1]=temp_Arr[i+1],temp_Arr[i]
temp_arr[i],temp_arr[i+1]=temp_arr[i+1],temp_arr[i]
Flag = True
for i in temp_arr:
Temp_string = "["+i+"]: "+str(Dictionary['mws'][i])
print(Temp_string)
print('<---digrams first way without spaces--->')
print_table('bf')
print('<---digrams first way with spaces--->')
print_table_ws('bwsf')
print('<---digrams second way without spaces--->')
print_table('bs')
print('<---digrams second way with spaces--->')
print_table_ws('bwss')
print('<---number of letters--->')
print_number_of_letters()
create_dict()
print_dict()
| false |
6cd9e37be10fffe2f81d38f6fb4099dcc8722fb6 | wildxmxtt/Python-Year-one- | /Lab 7/L07-12.py | 1,165 | 4.3125 | 4 | # leapYear.py
# File name: L07-12
# Description: A program that accepts calander dates
# By: Matthew Wilde
# 11-9-2020
def dateValid(month, day, year):
leap = True
if (year % 4) != 0:
leap = False
else:
if (year % 100) == 0:
if (year % 400) ==0:
leap = False
if month > 12 or day > 31:
print("This date is invalid.")
else:
if day <= 28:
print("This date is valid.")
elif month == 2 and day == 29:
if leap == False:
print("This date is invalid.")
else:
print("This date is valid.")
elif day == 31:
if month == 2 or 4 or 6 or 11:
print("This date is invalid")
else:
print("This date is valid")
else:
print("The date is valid.")
def main():
dateStr = input("Enter a date (month/day/year) ")
monthStr, dayStr, yearStr = dateStr.split("/")
month = int(monthStr)
day = int(dayStr)
year = int(yearStr)
d = dateValid(month, day, year)
main()
| true |
70d442b6db6b6e9cc8ab34855109dae994b99ce4 | wildxmxtt/Python-Year-one- | /Lab 3/molecularWeightOfCarbohydrate_PE3.py | 645 | 4.15625 | 4 | # molecularWeightOfCarbohydratePE3.py
# A program to computes the molecular weight of a carbohydrate (in
# grams per mole) based on the number of hydrogen, carbon, and oxygen
# atoms in the molecule.
# by: Matthew Wilde
# 9-25-2020
import math
def main():
hydroA = eval(input("Enter the number of number of hydrogen atoms "))
carbA = eval(input("Enter the number of number of carbon atoms "))
oxeyA = eval(input("Enter the number of number of oxeygen atoms "))
combinedA = (hydroA *1.00794) + (carbA * 12.0107) + (oxeyA * 15.9994)
print("The combined weight of the atoms is ", combinedA)
main()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.