blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c866045f8650d004b4541b8a06365930eddc9b5c | SiddharthandTiger/Sid | /P5.py | 570 | 4.1875 | 4 | a= float(input("Enter your height 'ONLY NUMERICAL VALUE':-"))
b= input("Enter your height unit (i.e. the value you have given above is in cm or m or feets or inches):-")
c= float(input("enter your weight in KG:-"))
if(b=='cm'):
print('your BMI is',c/((a/100)**2))
elif(b=='m'):
print('your BMI is',c/(a**2))
elif(b=='feets'):
print('your BMI is',c/((a*0.3048)**2))
elif(b=='inches'):
print('your BMI is',c/((a*0.0254)**2))
else:
print("Only give value in the units which are given above")
| true |
3facb7b380373a4c610f4e795b52395c5268fb75 | paulobonfim/praticando-python | /calculadora.py | 1,031 | 4.25 | 4 | print("")
print("**************Python Calculator*****************")
print("")
print("Selecione o número da operação desejada:")
print("")
print("1 - Soma")
print('2 - Subtração')
print('3 - Multiplicação')
print('4 - Divisão')
def soma(num1,num2):
return num1 + num2
#essa opção com a função soma eu usei o retunr pq quero colocar
#os valores que serão digitados pelo usuário "3 + 2 = 5"
def subt(num1, num2):
if num1 >= num2:
print(num1-num2)
else:
print("Opção inválida")
def multi(num1,num2):
print(num1*num2)
#nesse caso, não usei o return, usei o print direto; aqui
#o usuário so verá o resultado final e não a espressão "3 * 2 = 6"
def div(num1,num2):
print(num1/num2)
opcao = input('Digite sua opção(1/2/3/4): ')
num1 = int(input('Digite o primeiro número: '))
num2 = int(input('Digite o segundo número: '))
if opcao == "1":
print(num1, " + ", num2, " = ", soma(num1,num2))
elif opcao == "2":
subt(num1,num2)
elif opcao == "3":
multi(num1,num2)
else:
div(num1,num2) | false |
f30e704333cd8ce32839e928a993fca50a3cdc01 | Leandro-Kogan/python_script | /herencia.py | 1,818 | 4.125 | 4 | """La herencia hace referencia a dos clases, una padre y la otra clase hija
como por ejemplo podemos decir que hay una clase llamada persona, donde tenemos
las caracteristicas pertenecientes a cualquier persona y luego tenemos una clase
llamada empleado, donde se le adjudicaran atributos especificos pertenecientes
a un empleado, pero tambien tendra los atributos de la clase padre PERSONA """
class persona:
def __init__(self, nombre, edad):
self.nombre = nombre
self.edad = edad
#Para imprimir los datos de un objeto creado a partir de una clase y que nos
#figuren los atributos y no la direccion de la memoria en la que se encuentra
#usaremos __str__ que devuelve una cadena de texto:
def __str__(self):
return "Nombre "+ self.nombre+", edad "+str(self.edad)
def saludo(self):
print(f"Mi nombre es {self.nombre} y tengo {self.edad}")
#Al crear la clase empleado le especificamos que hereda las caracteristicas de
#la clase PERSONA:
class empleado(persona):
def __init__(self, nombre, edad, sueldo):#Aqui hemos agregado tambien los atributos
#de la clase padre (persona) ya que al crearse un objeto de clase empleado
#deberia tener tambien los atributos de la clase persona.
super().__init__(nombre, edad)
self.sueldo = sueldo
#"""Con super().__init__(nombre, edad) estamos haciendo referencia a los atributos
#de la clase padre, luego con self definimos los atributos de la clase hija"""
def datos(self):
print(f"Nombre {self.nombre}, edad {self.edad}, salario {self.sueldo}")
def __str__(self):
return super().__str__()+ " salario "+ str(self.sueldo)
per1 = persona("Koko", 36)
per1.saludo()
print(per1)
empleado1 = empleado("Jorge", 49, 7000)
empleado1.datos()
print(empleado1) | false |
aa9168455b376a7e4ff03366b971f4de63a16bc9 | gurpsi/python_projects | /python_revision/11_tuple.py | 1,039 | 4.34375 | 4 | '''
List a = [1,2,3]
List occupies more space as we have more number of methods available with it and it is mutable.
i.e. Add, Remove, Change data.
Tuple b = (1,4,6,9)
Occupies less memory as we have less number of methods available with it, and it is immutable.
i.e. Cannot be changed.
'''
import sys
import timeit
# print(dir(sys))
list_eg = [1,2,3,"a","b","c",True,3.14]
tuple_eg = (1,2,3,"a","b","c",True,3.14)
print("List size = ", sys.getsizeof(list_eg))
print("Tuple size = ", sys.getsizeof(tuple_eg))
# In terms of big data sets tuple is created more quickly than lists.
list_test = timeit.timeit(stmt="[1,2,3,4,5]", number=1000000)
tuple_test = timeit.timeit(stmt="(1,2,3,4,5)", number=1000000)
print("List time:", list_test)
print("Tuple time:", tuple_test)
# Tuple Assingment:
test = 1, # The comma is necessary to tell python that we want it in tuple.
test2 = 1,2,3
test3 = (3,)
test4 = (1,2,3,4)
print(test,'\t',type(test))
print(test2,'\t',type(test2))
print(test3,'\t',type(test3))
print(test4,'\t',type(test4)) | true |
9579290c232afeaa6b436a5de107239a35697fee | jyotikasingh133/Jyotika-Singh | /hello.py | 1,484 | 4.34375 | 4 | #dictionary data type in python
>>> student={"name":"jyotika", "age":19} #NAME,AGE: KEYS & JYOTIKA,AGE ARE VALUES#
>>> student
{'name': 'jyotika', 'age': 19}
>>> student["name"]
'jyotika'
>>> student["age"]=21 #AGE IS UPDATED FROM 19 TO 21
>>> student
{'name': 'jyotika', 'age': 21}
>>> student["college"]="ITS" #WE ADDED ONE MORE KEY THAT IS COLLEGE IN THE DICTIONARY
>>> student
{'name': 'jyotika', 'age': 21, 'college': 'ITS'}
>>> del student["college"] #DEL KEYWORD IS USED TO DELETE THE KEY COLLEGE#
>>> student
{'name': 'jyotika', 'age': 21}
>>> student.keys() #TOTAL NO. OF KEYS ARE MENTIONED USING KEYS() FUNCTION#
dict_keys(['name', 'age'])
>>> student.values()
dict_values(['jyotika', 21]) #TOTAL NO. OF VALUES ARE MENTIONED USING VALUES() FUNCTION#
>>> student1={"college":"ITS","rollno.":1}
>>> student1
{'college': 'ITS', 'rollno.': 1}
>>> student.update(student1) #UPDATING THE DICTIONARY STUDENT USING UPDATE() F(n)#
>>> student
{'name': 'jyotika', 'age': 21, 'college': 'ITS', 'rollno.': 1}
>>> student.clear() #CLEARING THE DICTIONARY USING CLEAR() F(n)#
>>> student
{}
>>> del student
>>> student
Traceback (most recent call last): #AS WE HAVE DELETED THE DICTIONARY USING DEL() FUNCTION,
File "<pyshell#18>", line 1, in <module> #SO, NOTHING IS LEFT AND THUS ERROR OCCURS#
student
NameError: name 'student' is not defined
>>>
| false |
49ae693e992687dc0034379a74e4a6c072b758f6 | csfx-py/hacktober2020 | /fizzBuzz.py | 392 | 4.34375 | 4 | #prints fizzz if number is divisible by 3
#prints buzz if number is divisible by 5
#prints fizzbuzx if divisible by both
def fizzbuzz(number):
if(number%3 == 0 and number%5 == 0):
print("fizzbuzz")
elif(number%3 == 0):
print("fizz")
elif(number%5 == 0):
print("buzz")
else:
print(number)
number = int(input("Enter Number: "))
fizzbuzz(number)
| true |
76cfbd5e7ea13120b5c46dff5febce0b24e6988d | csfx-py/hacktober2020 | /python-programs/data-visualization-matplotlib-pandas/retail_visualize.py | 2,685 | 4.21875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
if __name__ == '__main__':
retail_csv = pd.read_csv("BigMartSalesData.csv")
# 1. Plot Total Sales Per Month for Year 2011. How the total sales have increased over months in Year 2011.
df = retail_csv.query("Year == 2011").filter(["Month", "Quantity"]).groupby(["Month"], as_index=False).sum()
x = df["Month"]
y = df["Quantity"]
plt.plot(x, y)
plt.grid()
plt.xlabel("Month")
plt.ylabel("Sales quantity")
plt.title("Month vs quantity sales year 2011")
plt.show()
# Which month has lowest Sales ? -> february
# 2. Plot Total Sales Per Month for Year 2011 as Bar Chart
plt.bar(x, y)
plt.grid()
plt.xlabel("Month")
plt.ylabel("Sales quantity")
plt.title("Month vs quantity sales year 2011 in bar chart")
plt.show()
# Enhancement to show the value of the bar
plt.xlabel("Month")
plt.ylabel("Sales quantity")
plt.title("Month vs quantity sales year 2011 in bar chart #Enhancement ")
plt.barh(x,y)
for index,value in enumerate(y):
plt.text(value, index, str(value))
plt.show()
# Is Bar Chart Better to visualize than Simple Plot? -> yes
# 3. Plot Pie Chart for Year 2011 Country Wise.
df_pie = retail_csv.query("Year == 2011").filter(["Country", "Quantity"]).groupby(["Country"], as_index=False).sum()
Country_list = df_pie["Country"].tolist()
quantity_list = df_pie["Quantity"].tolist()
# for making exploding graph logic. Can also be done in list comprehension
expod_tup = []
count_max = max(quantity_list)
for i in quantity_list:
if i == count_max:
i = i / 100000000
expod_tup.append(i)
else:
i = 0
expod_tup.append(i)
print(expod_tup)
explode = tuple(expod_tup)
# Country contributes highest towards sales shown exploded
plt.figure(figsize=(30, 8))
plt.pie(quantity_list, labels=Country_list, autopct='%1.1f%%', explode=explode)
plt.show()
# Enhancement on implementing parameters shadow=True, startangle=90
plt.pie(quantity_list, labels=Country_list, autopct='%1.1f%%', explode=explode, shadow=True,startangle=90)
plt.show()
# 4. Plot Scatter Plot for the invoice amounts and see the concentration of amount.
df_scatter = retail_csv.filter(["InvoiceDate", "Amount"]).groupby(["InvoiceDate"], as_index=False).sum()
xa = df_scatter['InvoiceDate']
xb = df_scatter['Amount']
plt.scatter(xa, xb)
plt.ylim(20000, 50000)
plt.show()
# Enhancement to change colour of the scatter
plt.scatter(xa, xb,c="red")
plt.show()
| true |
cc90a561902bfc788ade5a2925905bba658db3cd | MJ702/pythonprogamming | /cryptography/method/caesar_cipher.py | 430 | 4.21875 | 4 | def encrypt(text, key):
result = ""
for i in range(len(text)):
char = text[i]
if char.isupper():
result += chr((ord(char) + key - 65) + 65)
else:
result += chr((ord(char) + key - 97) + 97)
return result
text = str(input("Enter your string to encrypt data: "))
key = int(input("Enter you key values: "))
ciphertext = encrypt(text, key)
print("Cipher: " + ciphertext)
| true |
27bdbaddd1b0b3dd7092969aa78fada7b29992e2 | MJ702/pythonprogamming | /pyton/oparators/bitwise.py | 1,290 | 4.5 | 4 | # bitwise operators are used to compare binary number
# &, | , ^ ,~ , << , >>
# bitwise AND
print("\nAND")
print(10 & 4)
"""
Returns 1 if both the bits are 1 else 0.
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary
a & b = 1010
&
0100
= 0000
= 0 (Decimal)
"""
# bitwise OR
print("\nOR")
print(10 | 4)
"""
Returns 1 if either of the bit is 1 else 0.
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary
a & b = 1010
|
0100
= 1110
= 14 (Decimal)
"""
# bitwise XOR
print("\nXOR")
print(10 ^ 12)
"""
Returns 1 if one of the bit is 1 and other is 0 else returns false.
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary
a & b = 1010
^
0100
= 1110
= 14 (Decimal)
"""
# bitwise NOT
print("\nNOT")
print(~10)
"""
Returns one’s compliement of the number.
a = 10 = 1010 (Binary)
~a = ~1010
= -(1010 + 1)
= -(1011)
= -11 (Decimal)
"""
# bitwise left shift
print("\nLEFT SHIFT")
print(5 << 1)
print(5 << 2)
"""
a = 5 = 0000 0101
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20
"""
# bitwise right shift
print("\nRIGHT SHIFT")
print(5 >> 1)
print(5 >> 2)
| false |
a220e724eaa168abd6b75365c1dfe4c2a8866f53 | doa-elizabeth-roys/CP1404_practicals | /prac_3/password_check.py | 440 | 4.125 | 4 | MIN_LENGTH = 8
def main() :
password = get_password(MIN_LENGTH)
print_asterisks(ACTUAL_LENGTH)
ACTUAL_LENGTH = len(password )
if ACTUAL_LENGTH < MIN_LENGTH :
print ( "Enter a password with atleast {} characters".format ( MIN_LENGTH ) )
password = input ( "Enter password: " )
else :
print_asterisk(ACTUAL_LENGTH)
def print_asterisk(ACTUAL_LENGTH):
for i in range (len( password )):
print ( "*", end='' )
main ()
| false |
d24086a0e9a5e5ddf882e0b5d3b829d304041e23 | doa-elizabeth-roys/CP1404_practicals | /prac_05/word_occurrences.py | 440 | 4.40625 | 4 | user_input = input("Text:")
word_count_dict = {}
words = user_input.split()
print(words)
for word in words:
word_count_dict[word] = word_count_dict.get(word,0) + 1
words = list(word_count_dict.keys())
words.sort()
# use the max function to find the length of the largest word
length_of_longest_word = max((len(word) for word in words))
for word in words:
print("{:{}} : {}".format(word, length_of_longest_word, word_count_dict[word])) | true |
607fa56c3bbec30c64ed08ef5c1b06cdac2e2410 | whdesigns/Python3 | /1-basics/6-review/2-input/1-circle.py | 399 | 4.53125 | 5 | import math
# Read radius from user
print("Please enter radius")
radius = float(input())
# Calculate area and circumference
area = math.pi * (radius * radius)
# alternative
# math.pi * (radius ** 2)
# math.pi * pow(radius, 2) # Best for more advanced code
circumference = 2 * math.pi * radius
# Display result
print("Area is", round(area, 2))
print("Circumference is", round(circumference, 2))
| true |
36f6cc335f53c4c86fd0de9576278e9c38367115 | maread99/pyroids | /pyroids/lib/physics.py | 418 | 4.15625 | 4 | #! /usr/bin/env python
"""Physics Functions.
FUNCTIONS
distance() Direct distance from point1 to point2
"""
import math
from typing import Tuple
def distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:
"""Return direct distance from point1 to point2."""
x_dist = abs(point1[0] - point2[0])
y_dist = abs(point1[1] - point2[1])
dist = math.sqrt(x_dist**2 + y_dist**2)
return dist | true |
3f56f4b41784ae7476834a851926d9e578501808 | AndreeaEne/Daily-Programmer | /Easy/239.py | 1,266 | 4.125 | 4 | # Back in middle school, I had a peculiar way of dealing with super boring classes. I would take my handy pocket calculator and play a "Game of Threes". Here's how you play it:
# First, you mash in a random large number to start with. Then, repeatedly do the following:
# If the number is divisible by 3, divide it by 3.
# If it's not, either add 1 or subtract 1 (to make it divisible by 3), then divide it by 3.
# The game stops when you reach "1".
# While the game was originally a race against myself in order to hone quick math reflexes, it also poses an opportunity for some interesting programming challenges. Today, the challenge is to create a program that "plays" the Game of Threes.
def add(steps, nr):
steps.append(nr)
def pairwise(it):
it = iter(it)
while True:
yield next(it), next(it)
def gameOfThrees(nr):
steps = []
while nr != 1 :
if nr % 3 == 0 :
# add(steps, nr)
print("%d %d" % (nr, 0))
nr /= 3
# add(steps, "0")
elif (nr-1) % 3 == 0 :
# add(steps, nr)
print("%d %d" % (nr, -1))
nr = (nr - 1) / 3
# add(steps, "-1")
else:
# add(steps, nr)
print("%d %d" % (nr, +1))
nr = (nr + 1) / 3
# add(steps, "1")
print (1)
# for i in pairwise(steps):
# print(i)
gameOfThrees(31337357) | true |
43a6204ab7f836ebf6c5b97403fc6df968a1aafc | laplansk/learnPythonTheHardWay | /ex6.py | 1,041 | 4.40625 | 4 | # These declare and instantiate string variables
# in the case of x, %d is replaced by 10
# in the case of y, the first %s is replaced by the value of binary
# and the second is replaced by the value of do_not
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
# These put the values of x and y into stdout, which makes
# them display on the console
print x
print y
# self-explanatory at this point
print "I said: %r" % x
print "I also said: '%s'." % y
# this declare a boolean and assigns it the values false
hilarious = False
# This creates a string with a format variable within
# since no value is provided to go in its place, one will be needed
# at its time of use. Otherwise the actual %r will remain as part of the string
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side"
# This prints the concatenation of the strings w and e
print w + e
| true |
ef5407467b1a7da16a79c927729f4d157f042499 | nishantml/Data-Structure-And-Algorithms | /recusrion/program-1.py | 261 | 4.1875 | 4 | def fun1(x):
if x > 0:
print(x)
fun1(x - 1)
print('completed the setup now returning')
fun1(3)
"""
In Above First printing was done the recursive call was made
Printing was done at calling time that before the function was called
""" | true |
0281244f624f9d6c3d83e1a2294d327a000132d7 | nishantml/Data-Structure-And-Algorithms | /startup-practice/get_indices.py | 596 | 4.15625 | 4 | """
Create a function that returns the indices of all occurrences of an item in the list.
Examples
get_indices(["a", "a", "b", "a", "b", "a"], "a") ➞ [0, 1, 3, 5]
get_indices([1, 5, 5, 2, 7], 7) ➞ [4]
get_indices([1, 5, 5, 2, 7], 5) ➞ [1, 2]
get_indices([1, 5, 5, 2, 7], 8) ➞ []
Notes
If an element does not exist in a list, return [].
Lists are zero-indexed.
Values in the list will be value-types (don't need to worry about nested lists).
"""
def get_indices(lst, el):
ind = []
for i in range(len(lst)):
if el == lst[i]:
ind.append(i)
return ind
| true |
f92c49b214c64a797c8e6276ffd068f3e6ac5478 | nishantml/Data-Structure-And-Algorithms | /Hash/keyword-rows.py | 1,270 | 4.21875 | 4 | """
Given a List of words, return the words that can be typed using letters of alphabet on only one row's
of American keyboard like the image below.
Example:
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
Note:
You may use one character in the keyboard more than once.
You may assume the input string will only contain letters of alphabet.
"""
from typing import List
class Solution:
def findWords(self, words: List[str]) -> List[str]:
row1 = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'];
row2 = ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']
row3 = ['z', 'x', 'c', 'v', 'b', 'n', 'm']
inteligentWords = []
for word in words:
Hash = {'first': 0, 'second': 0, 'third': 0}
for letter in list(word.lower()):
if letter in row1:
Hash['first'] = Hash['first'] + 1
if letter in row2:
Hash['second'] = Hash['second'] + 1
if letter in row3:
Hash['third'] = Hash['third'] + 1
if Hash['first'] == len(word) or Hash['second'] == len(word) or Hash['third'] == len(word):
inteligentWords.append(word)
return inteligentWords
| true |
3da81d30e6f07bceff071f6b48da10100f2cf4b8 | nishantml/Data-Structure-And-Algorithms | /complete-dsa/array/maxSubArray.py | 849 | 4.15625 | 4 | """
53. Maximum Subarray
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Example 2:
Input: nums = [1]
Output: 1
Example 3:
Input: nums = [0]
Output: 0
Example 4:
Input: nums = [-1]
Output: -1
Example 5:
Input: nums = [-100000]
Output: -100000
"""
from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
current_sum = 0
max_sum = nums[0]
for num in nums:
if current_sum + num > num:
current_sum += num
else:
current_sum = num
if current_sum > max_sum:
max_sum = current_sum
return max_sum | true |
207b15ac6ca59619d6a17eab2ad4064d111f39b2 | nishantml/Data-Structure-And-Algorithms | /basics-data-structure/queue/implementQueueUsingLinkedList.py | 1,735 | 4.21875 | 4 | class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.first = None;
self.last = None;
self.length = 0;
def enqueue(self, data):
new_node = Node(data)
if self.first is None:
self.first = new_node;
self.last = new_node;
else:
self.last.next = new_node; # point new_node to the lastNode next pointer
self.last = new_node; # new creaed should be the last of itself
self.length += 1
return self
def dequeue(self):
if self.first is None:
return None;
if self.first == self.last:
self.last = None;
leaderNode = self.first
self.first = self.first.next
self.length -= 1
return leaderNode.data
def peek(self, position='first'):
if (self.length == 0):
return self.first
else:
if (position == 'first'):
return self.first.data
else:
return self.last.data
def lookup(self):
cur_node = self.first
if cur_node is None:
print("Stack Underflow")
else:
while cur_node is not None:
print('<-', cur_node.data, end=' ')
cur_node = cur_node.next
print('')
return
myQueue = Queue()
myQueue.enqueue(1)
myQueue.enqueue(2)
myQueue.enqueue(3)
print('\nLast node is ->', myQueue.peek('last'))
print('\nFirst node is ->', myQueue.peek())
print('Before deleting')
myQueue.lookup();
print('After deleting')
myQueue.dequeue()
myQueue.dequeue()
# myQueue.dequeue()
myQueue.lookup();
| true |
b03744213e17b2f45a3990ec4cb803c1ef49fb77 | nishantml/Data-Structure-And-Algorithms | /basics-data-structure/queue/implementQueueUsingArray.py | 1,714 | 4.125 | 4 | class Queue:
def __init__(self):
self.array = []
self.length = 0
# adding the data to the end of the array
def enqueue(self, data):
self.array.append(data)
self.length += 1
return
# popping the data to the start of the array
def dequeue(self):
poped = self.array[0]
self.array.pop(0)
self.length -= 1
return poped
def reverse(self):
left = 0;
right = self.length - 1;
while left < right:
self.array[left], self.array[right] = self.array[right], self.array[left]
left += 1
right -= 1
return self
def reverseTillKElement(self, k):
if k > self.length:
print('index out of bound')
return
left = 0;
right = k - 1;
while left < right:
self.array[left], self.array[right] = self.array[right], self.array[left]
left += 1
right -= 1
return self
# array traverse
def lookup(self):
for val in self.array:
print(' <-', val, end="")
def peek(self):
return self.array[0]
myQueue = Queue()
print('\nLength of array is ->', myQueue.length)
myQueue.enqueue(1)
myQueue.enqueue(2)
myQueue.enqueue(3)
myQueue.enqueue(4)
myQueue.lookup()
print('\n After reverse')
# myQueue.reverse()
myQueue.reverseTillKElement(3)
myQueue.lookup()
# print('\nLength of array is ->', myQueue.length)
# print('\nFirst in array is ->', myQueue.peek())
# print('\ndequeue value is ->', myQueue.dequeue())
# myQueue.lookup()
# print('\nLength of array is ->', myQueue.length)
# print('\nFirst in array is ->', myQueue.peek())
print('\n')
| true |
40dcadcd7aa500001b2a52db747ee1bf3f340ef8 | andrewar/primes_challenge | /primes/primes.py | 1,562 | 4.15625 | 4 | import sys
def print_primes(n):
"""Print out the set of prime numbers, and their multiples"""
primes_list = get_primes(n)
mult_table = {}
# Get the largest val for the formatting fields
cell_size = len(str(primes_list[-1]**2))
print(" %*s"%(cell_size, " "), end=" ")
for i in range(len(primes_list)):
print(" %*s"%(cell_size, primes_list[i]), end=' ')
print(" ")
for i in range(len(primes_list)):
print(" %*s"%(cell_size, primes_list[i]), end=' ')
for j in range(len(primes_list)):
val = 0
if mult_table.get((i,j)):
val = mult_table[(i,j)]
elif mult_table.get((j,i)):
val = mult_table[(j,i)]
else:
val = primes_list[i]*primes_list[j]
mult_table[(j,i)] = val
print(" %*s"%(cell_size, val), end=' ')
print("")
def get_primes(n):
""" Get (n) primes """
primes = []
x = 2
while len(primes) < n:
if is_prime(x):
primes.append(x)
x+=1
return primes
def is_prime(x):
""" Determine if a number is prime """
if x==2 or x==3:
return True
for i in range(2,int(x/2)+1):
if x%i == 0:
return False
return True
if __name__=="__main__":
if len(sys.argv) != 1:
print("Please enter the number of primes you want.")
try:
print_primes(int(sys.argv[1]))
except ValueError:
print("%s is not a number. Please enter a number."%(sys.argv[1]))
| true |
33cbd8235d4731b0497356f6768effe36034cca3 | datadave/machine-learning | /brain/converter/calculate_md5.py | 1,348 | 4.4375 | 4 | #!/usr/bin/python
'''@calculate_md5
This file converts an object, to hash value equivalent.
'''
import hashlib
def calculate_md5(item, block_size=256*128, hr=False):
'''calculate_md5
This method converts the contents of a given object, to a hash value
equivalent.
@md5.update, generate an md5 checksum fingerprint, of the given file.
Calling this method repeatedly, is equivalent to a single call with
the concatenation of all arguments:
md5.update(a), md5.update(b)
is equivalent to the following:
md5.update(a+b)
In some cases, the entire file is too large as a single argument to
the checksum update operation. Therefore, it is best practice to break
the operation into smaller chunks.
@block_size, the block size to break the supplied object (item).
@hr, determines whether to use the default 'digest' method, or to use the
'hexdigest' algorithm.
Note: block size directly depends on the block size of the filesystem.
'''
md5 = hashlib.md5()
# use lambda anonymous function to iterate given object
for chunk in iter(lambda: item.read(block_size), b''):
md5.update(chunk)
# return the digest of strings passed into 'update'
if hr:
return md5.hexdigest()
return md5.digest()
| true |
0fc21bdcf2ef872f72b86a5b581289533e34eba6 | mevans86/rosalind | /signed_permutations.py | 978 | 4.125 | 4 | import itertools
import math
def list_of_signed_permutations(n):
"""Lists all possible signed permutations of +-1, 2, 3, ..., n."""
ret = [ ]
for mult in list(itertools.product([-1, 1], repeat=n)):
for perm in list(itertools.permutations(range(1, n+1))):
ret.append(tuple([x * y for x, y in zip(list(mult), perm)]))
return ret
# end list_of_permutations
def number_of_signed_permutations(n):
"""Returns the number of signed permutations of n items."""
return math.factorial(n) * 2**n
# end number_of_signed_permutations
# main block
filename = raw_input("Path to Rosalind Input File: ").strip()
try:
f = open(filename, "r")
except IOError:
print "A file does not exist at this location, or some other I/O error occurred. Peace out!"
sys.exit()
n = int(f.readline())
print "Possible signed permutations of %d objects:" % n
print number_of_signed_permutations(n)
print "\n".join([" ".join([str(item) for item in perm]) for perm in list_of_signed_permutations(n)]) | true |
aa9cce79ad87722276485c7f47d71dfd922d7de6 | PFSWcas/CS231n_note | /python/Assignment2/test_as_strided.py | 1,153 | 4.125 | 4 | import numpy as np
def rolling_window(a, window):
"""
Make an ndarray with a rolling window of the last dimension
Parameters
----------
a : array_like
Array to add rolling window to
window : int
Size of rolling window
Returns
-------
Array that is a view of the original array with a added dimension
of size w.
Examples
--------
>>> x=np.arange(10).reshape((2,5))
>>> rolling_window(x, 3)
array([[[0, 1, 2], [1, 2, 3], [2, 3, 4]],
[[5, 6, 7], [6, 7, 8], [7, 8, 9]]])
Calculate rolling mean of last dimension:
>>> np.mean(rolling_window(x, 3), -1)
array([[ 1., 2., 3.],
[ 6., 7., 8.]])
"""
if window < 1:
raise ValueError("`window` must be at least 1.")
if window > a.shape[-1]:
raise ValueError("`window` is too long.")
shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
strides = a.strides + (a.strides[-1],)
return np.ascontiguousarray(np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides))
x=np.arange(10).reshape((2,5))
temp = rolling_window(x, 3)
print(temp) | true |
c4acc908848a00d733add4aca3f199abfcb01f90 | AmeerCh/programs | /python/product.py | 361 | 4.40625 | 4 | print('To find the product of three numbers, ',end = '')
Number1 = int(input('enter the first number:'))
Number2 = int(input('Enter the second number:'))
Number3 = int(input('Enter the third number:'))
Product = Number1 * Number2 * Number3
print('The product of ' + str(Number1) + ', ' + str(Number2) + ' and ' + str(Number3) + ' is ' + str(Product) + '.') | true |
a380c16b83a1955e6177f5d9c58219a28e0c37fe | CardinisCode/CS50_aTasteOfPython | /loops.py | 444 | 4.34375 | 4 |
statement = "Hello world!"
# Lets print a statement 10x
# Using a While loop:
# i = 0
# while i < 10:
# print(statement)
# i += 1
# # Using a for loop
# for i in range(0, 10):
# print(i + 1, ":", statement)
# Lets take user input to know how many times we should repeat our statement:
# repeat = int(input("How many times should we repeat our statement: "))
# for i in range(0, repeat):
# print(i + 1, ":", statement)
| true |
10de18333ff1f9ae2d56a1a4fa32190dd3e61b73 | Th3Av1at0r/CIS106-Avi-Schmookler | /Assignment 7/Activity 2.py | 2,604 | 4.1875 | 4 | # this program takes your age
# in years and gives it back
# in months, days, hours, or seconds
def get_years():
variable = 0
while variable == 0:
print("how many years old are you?")
years = input()
if years.isdigit():
return float(years)
else:
print("that is not a valid input")
continue
def get_months_days_hours_seconds():
variable = 0
while variable == 0:
print("do you want to know how old you are in (M)onths, " +
"(D)ays, (H)ours, or (S)econds?")
months_days_hours_seconds = input().upper()
if months_days_hours_seconds in ("M", "D", "H", "S"):
return months_days_hours_seconds
else:
print("that is not a valid input")
continue
def get_months(years):
months = years * 12
return months
def get_days(years):
days = years * 365
return days
def get_hours(years):
hours = years * 8760
return hours
def get_seconds(years):
seconds = years * 31536000
return seconds
def get_months_days_hours_seconds_result(months_days_hours_seconds):
if months_days_hours_seconds == "M":
return "months"
elif months_days_hours_seconds == "D":
return "days"
elif months_days_hours_seconds == "H":
return "hours"
elif months_days_hours_seconds == "S":
return "seconds"
else:
print("unknown variable")
def display_result(months_days_hours_seconds,
months_days_hours_seconds_result):
print("your age in " + str(months_days_hours_seconds_result) + " is " +
str(months_days_hours_seconds))
# main
def main():
years = get_years()
months_days_hours_seconds = get_months_days_hours_seconds()
months_days_hours_seconds_result = \
get_months_days_hours_seconds_result(months_days_hours_seconds)
if months_days_hours_seconds == "M":
months = get_months(years)
display_result(months, months_days_hours_seconds_result)
elif months_days_hours_seconds == "D":
days = get_days(years)
display_result(days, months_days_hours_seconds_result)
elif months_days_hours_seconds == "H":
hours = get_hours(years)
display_result(hours, months_days_hours_seconds_result)
elif months_days_hours_seconds == "S":
seconds = get_seconds(years)
display_result(seconds, months_days_hours_seconds_result)
else:
print("that is not a valid input")
main()
| true |
fbd01ecb2d1feced945e6b8571262954aa9522c2 | Th3Av1at0r/CIS106-Avi-Schmookler | /Assignment 5/Activity 7.py | 735 | 4.125 | 4 | def get_dog_name():
print("What's your dog's name?")
dog_name = (input())
return dog_name
def display_result(dog_name, dog_age):
print(str(dog_name) + " is " + str(dog_age) + " years old in dog years")
def get_human_dog_age():
print("How many years old is your dog?")
human_dog_age = float(input())
return human_dog_age
def get_dog_age(human_dog_age):
dog_age = human_dog_age * 7
return dog_age
# Main
# This program takes your dogs name and age
# and gives you the age in dog years
def main():
dog_name = get_dog_name()
human_dog_age = get_human_dog_age()
dog_age = get_dog_age(human_dog_age)
display_result(dog_name, dog_age)
main()
| true |
65747b4d5abe06171304fa704489c60e1b3b74b6 | hernu123/-2020-2021-Spring-Term---Assignment-iv | /main.py | 392 | 4.21875 | 4 | number = int(input("Enter a natural number : "))
if number < 1:
print("Number needs to be greater than 1")
elif number == 1:
print(number, " is neigher prime nor composite")
else:
for divisor in range(2, (number//2)+1):
if (number % divisor) == 0:
print(number,"is a Composite Number")
break
else:
print(number,"is a Prime Number")
| true |
2b759b41c93f550b08eaece0cd0cb90665d88a1c | AthishayKesan/Python-is-Easy-Pirple.com- | /main.py | 2,902 | 4.21875 | 4 |
"""
Pirple.com : Python is Easy
Chapter 1 : Variables
Homework#1
"""
Song = "Dance Monkey" #String
Genere = "Electropop" #String
LyricistFirstName = "Toni"#String
LyricistLastName = "Watson" #String
LyricistFullName = LyricistFirstName + " " + LyricistLastName #String combine
Producer = "Konstantin Kerstring" #String
DurationInSeconds = 209 #Integer
ReleaseDate = "10 May, 2019" #String
NumberOFViewsOnYoutubeinMillion = 87.16#Float
ApproxNumberOfWords = 434#Interger
print("Song Name : ",Song)
print("Song Genere : ",Genere)
print("Lyricist Name : ",LyricistFullName)
print("Song Producer : ",Producer)
print("Song Durtion(in seconds) : ",DurationInSeconds)
print("Song Release Date : ",ReleaseDate)
print("Number of views on Youtube : ",NumberOFViewsOnYoutubeinMillion)
print("Number of words in the song : ",ApproxNumberOfWords)
"""
Lyrics
They say oh my god I see the way you shine
Take your hand, my dear, and place them both in mine
You know you stopped me dead while I was passing by
And now I beg to see you dance just one more time
Ooh I see you, see you, see you every time
And oh my I, I, I like your style
You, you make me, make me, make me wanna cry
And now I beg to see you dance just one more time
So they say
Dance for me, dance for me, dance for me, oh, oh, oh
I've never seen anybody do the things you do before
They say move for me, move for me, move for me, ay, ay, ay
And when you're done I'll make you do it all again
I said oh my god I see you walking by
Take my hands, my dear, and look me in my eyes
Just like a monkey I've been dancing my whole life
But you just beg to see me dance just one more time
Ooh I see you, see you, see you every time
And oh my I, I like your style
You, you make me, make me, make me wanna cry
And now I beg to see you dance just one more time
So they say
Dance for me, dance for me, dance for me, oh, oh, oh
I've never seen anybody do the things you do before
They say move for me, move for me, move for me, ay, ay, ay
And when you're done I'll make you do it all again
They say
Dance for me, dance for me, dance for me, oh, oh, oh, oh, oh, oh, oh
I've never seen anybody do the things you do before
They say move for me, move for me, move for me, ay, ay, ay
And when you're done I'll make you do it all again
Ooh
Woah-oh, woah-oh, oh
Ooh
Ah ah, ah
They say
Dance for me, dance for me, dance for me, oh, oh, oh
I've never seen anybody do the things you do before
They say move for me, move for me, move for me, ay, ay, ay
And when you're done I'll make you do it all again
They say
Dance for me, dance for me, dance for me, oh, oh, oh, oh, oh, oh, oh
I've never seen anybody do the things you do before
They say move for me, move for me, move for me, ay, ay, ay
And when you're done I'll make you do it all again
All again
"""
| false |
66325e151b3f2faa5330e7c81b540fbeba460a05 | natelee3/python2 | /largest_number.py | 239 | 4.34375 | 4 | #Largest Number
#Create a list of numbers and print the largest number.
simple_list = [3, 4, 5, 455, 7, .5]
largest = 0
for num in simple_list:
if num > largest:
largest = num
print("The largest number is " + str(largest))
| true |
70b64bb3ed106042aaeef9725e63c45b6c6597ab | aliciamorillo/Python-Programming-MOOC-2021 | /Part 2/13. Alphabetically in the middle.py | 277 | 4.25 | 4 | letter1 = input("1st letter:")
letter2 = input("2nd letter:")
letter3 = input("3rd letter:")
word = letter1 + letter2 + letter3
def sortString(str):
return ''.join(sorted(str))
sortedWord = sortString(word)
print("The letter in the middle is", sortedWord[1]) | true |
166c104c7ebe8887d9024c1f9c38c48cf097c351 | aliciamorillo/Python-Programming-MOOC-2021 | /Part 1/10. Story.py | 438 | 4.28125 | 4 | #Please write a program which prints out the following story.
# The user gives a name and a year, which should be inserted into the printout.
name = input("Please type in a name: ")
year = input("Please type in a year: ")
print(name +" is valiant knight, born in the year " + year + ". One morning " + name + " woke up to an awful racket: a dragon was approaching the village. Only " + name + " could save the village's residents.") | true |
b104fd468a1d78cc3fd81dff7447034a121aa80c | aliciamorillo/Python-Programming-MOOC-2021 | /Part 1/14. Times five.py | 239 | 4.28125 | 4 | #Please write a program which asks the user for a number.
# The program then prints out the number multiplied by five.
number = int(input("Please type in a number:"))
plusNumber = number * 5
print(f"{number} times 5 is {plusNumber}") | true |
4381ba344238c7ef2e13b41bc46a376ea263283d | lvamaral/RubyAlgorithms | /Dynamic Programming/ways_to_make_change.py | 918 | 4.1875 | 4 | # Print a single integer denoting the number of ways we can make change for n dollars using an infinite supply of "coins" types of coins.
def make_change(coins, n, index = 0, memo = {}):
if n == 0:
return 1
if index >= len(coins):
return 0
#Save the current amount being considered and the coin to keep track of the "stage" of the process
key = str(n)+"-"+str(index)
if key in memo:
return memo[key]
amtWithCoin = 0
ways = 0
while amtWithCoin <= n:
remainder = n - amtWithCoin
ways += make_change(coins, remainder, index+1, memo)
amtWithCoin += coins[index]
memo[key] = ways
return ways
coins = [2,5,3,6]
n = 10
print(make_change(coins,n))
#5
#Solution is basically creating a tree of possibilities. For each coin, considering all the possibilities if 1 coin was used, or 2, or 3... untill there's no more possible (amt>n)
| true |
c62b31e26706cd226cae4272f1cf605aa4be4449 | limahseng/cpy5python | /compute_bmi.py | 420 | 4.375 | 4 | # Filename: compute_bmi.py
# Author: Lim Ah Seng
# Created: 20130221
# Modified: 20130221
# Description: Program to get user weight and height and
# calculate body mass index
# main
# prompt and get weight
weight = int(input("Enter weight in kg: "))
# prompt and get height
height = float(input("Enter height in m: "))
# calculate bmi
bmi = weight / (height * height)
# display result
print("BMI = {0:.2f}".format(bmi))
| true |
21f60b7d94eba832b6ebcc239e36ccf3e9659420 | sivamu77/upGrade_assignment3 | /assignment_3.py | 1,020 | 4.40625 | 4 | import numpy as np
#1 Create a numpy array starting from 2 till 50 with a stepsize of 3.
arr=np.arange(2,50,3)
print(arr)
#2 Accept two lists of 5 elements each from the user. Convert them to numpy arrays. Concatenate these arrays and print it. Also sort these arrays and print it.
ip1=np.array([int(input()) for i in range(5)])
ip2=np.array([int(input()) for i in range(5)])
print(np.sort(np.concatenate((ip1,ip2))))
#3 Write a code snippet to find the dimensions of a ndarray and its size.
arr=np.array([1,2,3,4,5,6])
print(arr.ndim)
print(arr.size)
#4 How to convert a 1D array into a 2D array? Demonstrate with the help of a code snippet
a = np.array([1, 2, 3, 4])
print(a)
b= np.reshape(a,(-1,2))
print(b)
#5 Consider two square numpy arrays. Stack them vertically and horizontally.
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(np.vstack(a))
print(np.hstack(a))
#6 How to get unique items and counts of unique items?
a=np.arange(1,10)
print(np.unique(a,return_counts=True))
| true |
b4db2715ae8bcc60054ac33698703d5549e71410 | shadydealer/Python-101 | /Solutions/week02/simplify_fraction.py | 854 | 4.15625 | 4 | def gcd(a,b):
if b == 0:
raise ZeroDivisionError("Cannot mod with zero.")
t = 0
while b != 0:
t = b
b = a% b
a = t
return a
def simplify_fraction(fraction):
if fraction[1] == 0:
raise ZeroDivisionError("Denominator cannot be zero.")
greatest_common_divider = gcd(fraction[0], fraction[1])
result_nom = fraction[0] // greatest_common_divider
result_denom = fraction[1] // greatest_common_divider
return (result_nom, result_denom)
def read_input():
is_number = False
fraction = ""
while not is_number:
fraction = input()
try:
fraction = tuple(map(int, fraction.split()))
is_number = True
except ValueError:
print("Please enter two numbers.")
return fraction
#fraction = read_input() | true |
58d9fa137a59df449b58aaedc1e97d1365efdd36 | Jainesh-roy/guess-the-number | /guess the number.py | 644 | 4.15625 | 4 | # exercise 3
# guess the number
import random
rand_num = random.randint(0,20)
guesses = 0
print("welcome to the game - Guess the number")
print("you have only 9 chances to guess the number\n")
while guesses < 9:
inp = int(input("Enter a number: "))
if inp > rand_num:
print("\nenter a smaller number")
elif 8-guesses == 0:
print("\nYou didn't got the rand_numwer")
# break
elif inp < rand_num:
print("\nEnter a Greater Number")
else:
print(f"\ncongratulation! you guessed the number it was {rand_num}")
break
print(8-guesses, "Guesses Left\n")
guesses = guesses + 1 | true |
7befe78ab3db0f80d82bdd423d442075f46dd168 | Spiritual-Programmer/Python-Course | /working_strings.py | 720 | 4.40625 | 4 | #working with strings and functions
phrase = "Giraffe Academy"
#can use \ to add " or other texts
#\n starts text on next line
#concatenation(adding or appending on) with strings
print(phrase + " is cool, plus me concatening strings")
#functions
print("converting string into uppercase letter")
print(phrase.upper)
print("Now converting string to lowercase ")
print(phrase.lower)
print(phrase.isupper())#Checking if value is true or false of uppercase letters
print(phrase.upper().isupper()) #combining
print(len(phrase)) #length in phrase
print(phrase[0]) #getting index of character
print(phrase.index("r")) #index: tells us where the character is, passing parameters
print(phrase.replace("Giraffe","Singh"))
| true |
356efc42abb2c8fd6e16f5d9ceb478ea15c0c63f | akuppala21/Fundamentals-of-CS | /lab4/loops/cubesTable.py | 1,454 | 4.28125 | 4 |
def main():
table_size = get_table_size()
while table_size != 0:
first = get_first()
inc = get_increment()
show_table(table_size, first, inc)
table_size = get_table_size()
# Obtain a valid table size from the user
def get_table_size():
size = int(input("Enter number of rows in table (0 to end): "))
while size < 0:
print("Size must be non-negative.")
size = int(input("Enter number of rows in table (0 to end): "))
return size;
# Obtain the first table entry from the user
def get_first():
first = int(input("Enter the value of the first number in the table: "))
while first < 0:
print("First number must be non-negative.")
first = int(input("Enter the value of the first number in the table: "))
return first;
def get_increment():
inc = int(input("Enter the increment between rows: "))
while inc < 0:
print("Increment must be non-negative.")
inc = int(input("Enter the increment between rows: "))
return inc;
# Display the table of cubes
def show_table(size, first,inc):
print("A cube table of size %d will appear here starting with %d." % (size, first))
print("Number Cube")
s = 0
# Insert Loop Here
for i in range(size):
cube = first**3
print("%-6d %d" % (first, first**3))
first = (first + inc)
s = s + cube
print("The sum of cubes is:",s)
if __name__ == "__main__":
main()
| true |
3281bd5d113b45083483cd808da405bf3d6882e0 | dTenebrae/Python | /lesson2/lesson2_2.py | 1,092 | 4.1875 | 4 | # Для списка реализовать обмен значений соседних элементов, т.е.
# Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
# При нечетном количестве элементов последний сохранить на своем месте.
# Для заполнения списка элементов необходимо использовать функцию input().
listA = []
while True:
list_value = input(
'Введите элемент списка. Если хотите выйти из режима '
'ввода - введите ":q" --->')
if list_value == ':q':
break
listA.append(list_value)
print(f'Список: {listA} Длина списка: {len(listA)}')
num = 0
if len(listA) % 2 == 0:
max_len = len(listA)
else:
max_len = len(listA) - 1
while num < max_len:
listA[num], listA[num + 1] = listA[num + 1], listA[num]
num += 2
print(f'Список: {listA} Длина списка: {len(listA)}')
| false |
f8f61ab1a1037adb9cfa8d5fe038ef4c884a8370 | Liam-Hearty/ICS3U-Assignment-6B-Python | /triangle_perimeter_calculator.py | 1,222 | 4.25 | 4 | #!/usr/bin/env python3
# Created by: Liam Hearty
# Created on: October 2019
# This program calculates perimeter of a triangle.
def calculate_perimeter(L1, L2, L3):
# calculate perimeter and return perimeter
import math
# process
perimeter = L1 + L2 + L3
return perimeter
def main():
# this function gets radius and height from user.
try:
# input
length1_from_user = int(input("Enter the radius of a triangle (cm): "))
length2_from_user = int(input("Enter the height of a triangle (cm): "))
length3_from_user = int(input("Enter the height of a triangle (cm): "))
print("")
if (length1_from_user <= 0 or length2_from_user <= 0
or length3_from_user <= 0):
print("One of your values were less than 0, try again.")
exit()
# call functions
perimeter = calculate_perimeter(length1_from_user,
length2_from_user,
length3_from_user)
# output
print("The perimeter is {} cm".format(perimeter))
except ValueError:
print("Please input a proper value.")
if __name__ == "__main__":
main()
| true |
1a957a9416beb42eda2655006589afc595ed5086 | honeywang991/test01 | /python9/class_0721_list_tuple_dict/class_list.py | 931 | 4.21875 | 4 | __author__ = 'zz'
#列表 list 标识符[]
#特性: 1:他可以包含任何类型的数据,数据之间用逗号隔开
#2:元组取值的方式: 列表名[索引的值]
#3: 他的索引是从0开始的
#4:列表可以进行增删改
list_1 = [1,'hello',8.6,(1,2,3,4),[5,6,9,10]]
#出一个小题目:把(1,2,3,4)里面的3 替换成‘Python9’
# list_1[3][2]='python9' #不能改
# print(list_1)
# print(list_1[3][2])
list_1[3]='python9'
print(list_1)
#取[5,6,9,10]中的5
# print(list_1[4][0])
#函数 列表的函数
#新增一个值 列表名.append() 在最后名加一个元素
# list_1.append('野人')
# print(list_1)
#新增一个值 列表名.insert(i,value) 在指定位置加一个元素
# list_1.insert(0,'大人')
#删除一个元素 列表名.pop() 删除最后面一个元素
#删除指定位置的元素 列表名.pop(index)
# list_1.pop()
# list_1.pop(0)
# print(list_1)
# print(list_1.pop(0)) | false |
28b5ede7a2a33bffdc8457344eeb32ee53cb01d7 | shoredata/dojo-python | /dojo-python-misc/fn_basic_2.py | 2,074 | 4.34375 | 4 | # Functions Basic II
# ====================
# Objectives
# --------------------
# Learn how to create basic functions in Python
# Get comfortable using lists
# Get comfortable having the function return an expression/value
# Countdown - Create a function that accepts a number as an input.
# Return a new array that counts down by one, from the number (as arrays 'zero'th element) down to 0 (as the last element).
# For example countDown(5) should return [5,4,3,2,1,0].
def countdown(num):
newarr = []
for i in range(num,-1,-1):
newarr.append(i)
return newarr
count1 = 5
print(countdown(count1))
# Print and Return - Your function will receive an array with two numbers.
# Print the first value, and return the second.
def printandreturn(num1, num2):
print(num1)
return num2
val1 = 101
val2 = 2012
print(printandreturn(val1,val2))
# First Plus Length - Given an array, return the sum of the first value in
# the array, plus the array's length.
def firstpluslength(arr):
return len(arr) + arr[0]
arr1=[12,0,-18,-9,3,-4,5,-909,1212]
print(firstpluslength(arr1))
# Values Greater than Second - Write a function that accepts any array, and
# returns a new array with the array values that are greater than its 2nd value.
# Print how many values this is.
# If the array is only element long, have the function return False
def vgts(arr):
newarr = []
if (len(arr)<2):
return False
else:
for i in range(len(arr)):
if arr[i]>arr[1]:
newarr.append(arr[i])
print(len(newarr))
return newarr
arr1a = vgts(arr1)
print(f"{arr1} --> {arr1a}")
# This Length, That Value - Given two numbers, return array of length num1
# with each value num2.
# Print "Jinx!" if they are same.
def tltv(num1,num2):
retn = []
if (num1==num2):
print("Jinx!")
else:
retn = [num2 for i in range(num1)]
return retn
print(f"(6,6) = {tltv(6,6)} (should have printed Jinx! above here ^^")
print(f"(2,4) = {tltv(2,4)}")
print(f"(5,-18) = {tltv(5,-18)}")
| true |
3689b5598cb5d4e686f99c9eb2f9423b19203ef6 | RAHULMJP/impact_assignment | /attendence_assignment.py | 1,484 | 4.15625 | 4 | ## Question
# In a university, your attendance determines whether you will be allowed to attend your graduation ceremony.
# You are not allowed to miss classes for four or more consecutive days.
# Your graduation ceremony is on the last day of the academic year, which is the Nth day.
# Your task is to determine the following:
# 1. The number of ways to attend classes over N days.
# 2. The probability that you will miss your graduation ceremony.
def func(n,count,maxC):
# checking the max value of count using max inbuilt funtion because we are making it zero.
maxC = max(count, maxC)
# if n is zero then exit from the function
if(n == 0):
# checking maxC if its greater then three(means missing class for four or more consecutive days)
if(maxC > 3):
return 1
return 0
inc = func(n-1, count + 1, maxC)
exc = func(n-1, 0, maxC)
return inc + exc
# takeing input from user
n = input()
missed_classes =func(int(n), 0, 0)
max_possibility = pow(2, int(n))
# To find the number of ways to attend classes we have to substract missed class possibility from max possibility
print("The number of ways to attend classes " + str(max_possibility-missed_classes))
# The probability of missing ceremony will be missed_classed divided by max_possibility
print("The probability for miss graduation ceremony will be " + str(missed_classes / max_possibility))
| true |
d558701ef05d2344550e741e04efb3970153c9ca | neerajkumar0/firstPython | /TrialPythonProgram/test.py | 1,647 | 4.28125 | 4 | #!/usr/bin/python
print ("Hello, Python!");
class familyMember:
'Details of family member'
def __init__(self,name,age,sex,memberType):
self.name = name
self.age = age
self.sex = sex
self.memberType = memberType
def DisplayMember(self):
print ("\nName : ", self.name, " Age : ", self.age, " Sex : ", self.sex , "\n\n");
class family:
'details of a family'
familyCount =0
def __init__(self, familyName, noOfMember):
self.familyName = familyName
self.noOfMember = noOfMember
self.familyMembers = []
count =0
while(count < self.noOfMember):
count += 1
name = input("\nEnter Name:")
age = input("\n age:")
sex = input("\n sex:")
memberType = input("\n member Type:")
member = familyMember(name,age,sex,memberType)
self.familyMembers.append(member)
family.familyCount += 1
def DisplayFamily(self):
print ("\n This is the ", self.familyName, " family");
print ("\n the family members are:");
count =0
father = False
mother = False
while(count < self.noOfMember):
if(father ==False and self.familyMembers[count].memberType == 'F'):
print ("\nFather :")
self.familyMembers[count].DisplayMember()
father = True
count =0
if(father == True and mother == False and self.familyMembers[count].memberType == 'M'):
print ("\nMother :")
self.familyMembers[count].DisplayMember()
mother = True
count =0
if(mother == True and self.familyMembers[count].memberType == 'C'):
print ("\nChild :")
self.familyMembers[count].DisplayMember()
count += 1
family1 = family("Kumar ", 4)
family1.DisplayFamily()
input("\n\nPress the enter key to exit.");
| false |
07bb532beaf548f1e074fcb8c4fa601c3433b6f4 | rpryzant/code-doodles | /interview_problems/2019/pramp/drone.py | 997 | 4.125 | 4 | """
drone flight planner
minimum amount of energy for drone to complete flight
burns 1 per ascend
gains 1 per descend
sideways is 0
given
route: array( triples )
e.g. route = [ [0, 2, 10],
[3, 5, 0],
[9, 20, 6],
[10, 12, 15],
[10, 10, 8] ]
calc:
min energy drone needs to start the route
can you move up/down multiple times?
what if route is just descent? just ascent?
route is empty?
route is 1 point?
x, y doesn’t matter
IDEA 1:
loop through route, calc running total as if you started with a
tank of 0
remember the min value.
if min less than 0 return abs(min) else return 0
correct? yes, guarentees that you’ll get though the route, and if there was a smaller number you would ahve picked up on it
"""
def min_fuel(route):
temp_min = 0
cur_fuel = 0
for i, [_, _, z] in enumerate(route[1:]):
cur_fuel += (z - route[i][-1])
temp_min = min(temp_min, cur_fuel)
return abs(temp_min)
| true |
30e568bd8619ad5385f961ad0529b9c6ba3f7f9a | rashonmitchell/projeto-algoritmos | /1_introducao/19_this_self.py | 304 | 4.1875 | 4 | """
Nesta implementação em Java, o objetivo é ilustrar o uso do objeto 'this'. Em
Python, o objeto equivalente é 'self'.
"""
class Conta:
def __init__(self, saldo):
self.saldo = saldo
if __name__ == "__main__":
conta_teste = Conta(123.45)
assert conta_teste.saldo == 123.45
| false |
6201b019816bde69b2c679f0715585154c7443a8 | Jardon12/dictionary | /dictionaryoperator.py | 586 | 4.75 | 5 | # empty dictionary
d={}
print(f"my dictionary is {d}")
students = {1: "John", 2: "Valentina", 3: "Beatriz"}
students_list = {"John", "Valentina", "Beatriz"}
# add a new student
students[7] = "Carlos"
print(f"my students are: {students}")
# In a dictionary the order is not important, because you have keys to access the order.
print(f"Carlos is: {students[7]}")
students["nine"] = "Ignacio"
print(f"my students are: {students}")
del students[2]
print(f"my students are: {students}")
# we can iterate over a dictionary
for key in students:
print(f"{key} -> {students[key]}" )
| true |
e442ff2b09bedaf9ce8a69d3bee8bd565f849375 | omkar6644/Python-Training | /Assignment/2.py | 514 | 4.1875 | 4 | #the below program takes 3 inputs from the user and finds a quadratic equation.
#import square root function from math module
from math import sqrt
a = float(input("a=: "))
b = float(input("b=: "))
c = float(input("c=: "))
#Quadratic function
def quadEqu(a, b ,c):
d = b**2-4*a*c
if d > 0:
x = (((-b)+sqrt(d))/(2*a))
y = (((-b)-sqrt(d))/(2*a))
return x,y
if x or y == 0:
return
else:
return 1
print(quadEqu(a,b,c))
| true |
d246141eb7b825492dd658c0de99fed57fe9d12d | omkar6644/Python-Training | /encapsulation.py | 1,616 | 4.375 | 4 | #encapsulation of private methods
#encapsulation is a process of binding the data and code together or it is the process of providing controlled access to the private members of the class.
class Car:
def __init__(self):
self.__updateSoftware()
def drive(self):
print('driving')
def __updateSoftware(self):
print('updating software')
redcar = Car()
redcar.drive()
#redcar.__updateSoftware()
print()
print()
#encapsulation of private variables
class Book:
def __init__(self,name):
self.__name=name
def setName(self,values):
self.__name=values
def getName(self):
return self.__name
b=Book("think rich")
#print(b.name) cannot acess private variables of class
b.setName("grow rich") #by using setname method we can access private variables
x=b.getName()
print(x)
print()
print()
#using Property() function to provide a common name to setter and getter method
class Student:
def __init__(self):
self.__name=""
def getter(self):
return self.__name
def setter(self,value):
self.__name=value
getSet=property(getter,setter)
s=Student()
s.getSet="Python"
msg=s.getSet
print(msg)
print()
print()
#using @Property Decorator
#@property decorator is used to common name to the setter and getter method
class Student:
def __init__(self):
self.__name=""
@property
def name(self):
return self.__name
@name.setter
def name(self,value):
self.__name=value
s=Student()
s.name="Java"
msg=s.name
print(msg)
| true |
eb207182c7235e1b63aa899e387e833a429dbe8f | kinalee/holbertonschool-higher_level_programming | /0x06-python-test_driven_development/3-say_my_name.py | 541 | 4.4375 | 4 | #!/usr/bin/python3
"""
3-say_my_name
that prints "My name is " and two given arguments
Contains one module: say_my_name
"""
def say_my_name(first_name, last_name=""):
"""
first_name and last_name should be strings
"""
try:
print("My name is {:s} {:s}".format(first_name, last_name))
except:
if isinstance(first_name, str) is not True:
raise TypeError("first_name must be a string")
if isinstance(last_name, str) is not True:
raise TypeError("last_name must be a string")
| true |
d6057b286992e14e2fdd09d65fcc64c4fd09a7b8 | StephenPrivette/Project-Euler | /Euler Problem 14.py | 1,050 | 4.15625 | 4 | ##The following iterative sequence is defined
##for the set of positive integers:
##
##n → n/2 (n is even)
##n → 3n + 1 (n is odd)
##
##Using the rule above and starting with 13,
##we generate the following sequence:
##
##13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
##It can be seen that this sequence
##(starting at 13 and finishing at 1) contains 10 terms.
##Although it has not been proved yet (Collatz Problem),
##it is thought that all starting numbers finish at 1.
##
##Which starting number, under one million, produces the longest chain?
longest_chain = 0
for i in range (2, 1000000):
current_number = i
current_chain = 1
while i > 1:
if i % 2 == 0:
i = i // 2
else:
i = i * 3 +1
current_chain += 1
if current_chain > longest_chain:
longest_chain = current_chain
longest_number = current_number
print (longest_number, "is the starting number with the longest chain of"\
, longest_chain)
| true |
938adaab2d7f01cf3a5f38f96baa3310ac409ef1 | vivekbishwokarma99/Lab_Project | /LabFour/Qn_Three.py | 282 | 4.125 | 4 | '''
3.Write a Python program to guess a number between 1 to 9.Note :User is prompted to enter a guess.
If the user guesses wrong then the prompt appears again until the guess is correct, on successful guess,
user will get a "Well guessed!" message, and the program will exit.
''' | true |
2974b099406508d4dfe83937b9d532a94e89f3d7 | kroze05/Tarea_2 | /T2Funciones/1_ejercicio.py | 356 | 4.125 | 4 | #1) Realiza una función llamada area_rectangulo() que devuelva el área del rectangulo a partir de una base y una altura. Calcula el área de un rectángulo de 15 de base y 10 de altura.}
def area_rectangulo(base,altura):
res=base*altura
print(f"El area del rectangulo de base {base} y de altura {altura} es igual a: {res}")
area_rectangulo(15,10) | false |
cca9b7e9503372777d4e6ac612e433c2f2c2dcfc | cesarm9/PythonExercises | /function_sum_2_numbers.py | 302 | 4.125 | 4 | def sum(a, b): #names the function as sum and takes parameters a and b
total = a + b #saves the sum of a and b in the total variable
return total #returns total as the result of the function
print(sum(2, 3)) #prints the value of return according to the parameters given to the sum function | true |
ff2a4d85240db1fabf1ca8e938f115b900fb6770 | veryamini/Competitive-Programming | /GeeksForGeeks/DynamicProgramming/tiling.py | 440 | 4.125 | 4 |
# Q: https://www.geeksforgeeks.org/tiling-problem/
# count(n) = count(n-1) + count(n-2)
# count(n) = n if n = 1, n = 2
# converts in fibbonacci series with different starting numbers
def fib(n):
a = 1
b = 2
if n == 0:
print("WRONG INPUT!")
elif n == 1 or n == 2:
return n
else:
for i in range(2, n):
c = a + b
a = b
b = c
return c
def main():
n = int(input())
print(fib(n))
if __name__ == "__main__":
main() | false |
7a6d13483d43d23e51ae6ea11d9521afaedf4720 | NguyenDuyCuong/Learning | /Python/whileloop.py | 558 | 4.28125 | 4 | i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
else:
print("i is no longer less than 6")
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
for x in "banana":
print(x)
for x in range(6):
print(x)
# The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3):
for x in range(2, 30, 3):
print(x)
for x in range(6):
print(x)
else:
print("Finally finished!")
for x in [0, 1, 2]:
pass
| true |
af17172772fd42b3a09b0686f8f254de6b2e3398 | NguyenDuyCuong/Learning | /Python/myscope.py | 852 | 4.21875 | 4 | # A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
# The local variable can be accessed from a function within the function:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
# A variable created in the main body of the Python code is a global variable and belongs to the global scope.
# Global variables are available from within any scope, global and local.
# If you operate with the same variable name inside and outside of a function, Python will treat them as two separate variables, one available in the global scope (outside the function) and one available in the local scope (inside the function):
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)
# Global Keyword
def myfunc():
global x
x = 300
myfunc()
print(x) | true |
222aed1628d593bb583a5999a76eca65c24cd499 | iamdanielchino/wejapa20wave1 | /Lab1of2.py | 855 | 4.34375 | 4 | #Quiz: Calculate
#In this quiz you're going to do some calculations for a tiler.
#Two parts of a floor need tiling. One part is 9 tiles wide by 7 tiles long, the other is 5 tiles wide by 7 tiles long. Tiles come in packages of 6.
#1. How many tiles are needed?
#2. You buy 17 packages of tiles containing 6 tiles each. How many tiles will be left over?
#Fill this in with an expression that calculates how many tiles are needed.
length_one= 7
width_one= 9
part_one = length_one * width_one
length_two= 7
width_two= 5
part_two= length_two * width_two
total_tiles_needed = part_one + part_two
print(total_tiles_needed)
# Fill this in with an expression that calculates how many tiles will be left over.
package_tiles= 6
no_packages= 17
total_tiles = package_tiles * no_packages
leftover_tiles = total_tiles - total_tiles_needed
print(leftover_tiles)
| true |
2fb38524c9050f84d9edc3e9285cfcb08cb8af21 | peguin40/cpy5p1 | /q3_miles_to_kilometre.py | 376 | 4.21875 | 4 | #q3_miles_to_kilometre.py
#miles to kilometre calculator
#Welcome Message
print("Welcome to Miles to Kilometre calculator, \n Please input the following value(s)")
#get input variable(s)
miles = float(input("Miles:"))
#compute kilometre value
kilometres = float(1.60934 * miles)
#display results
print("{0} miles in kilometres is {1:.3f}km(3dp)".format(miles,kilometres))
| false |
df3b46c7a5582d882d4abb8c4178de62a4f68a2a | hunthunt2010/CompilersGroup2 | /ToTheAST/namespace.py | 884 | 4.15625 | 4 | #!/usr/bin/env python
#Taylor Schmidt
#ToTheAST group assignment
#namespace implementation
class Namespace:
def __init__ (self):
self.nameString = ''
def addName(self, newName):
"takes a new name string as an arg and returns a tuple with its index and length in the global string"
nameLength = len(newName)
#check if name already exists in namespace, if not add it
if self.nameString.find(newName) != -1:
nameIndex = self.nameString.find(newName)
return (nameIndex, nameLength)
else:
nameIndex = len(self.nameString)
self.nameString = self.nameString + newName
return (nameIndex, nameLength)
def getName(self, nameTuple):
"takes a name tuple as an arg (nameIndex, nameLength) and returns the string representation from the namespace"
nameIndex = nameTuple[0]
endIndex = nameIndex + (nameTuple[1])
return self.nameString[nameIndex:endIndex]
| true |
401917d8f5f1028ca7163f1c29fc8bf252cf3655 | cmulliss/gui_python | /challenges/oop_syntax.py | 1,405 | 4.3125 | 4 | class Student:
def __init__(self, name, grades):
self.name = name
self.grades = grades
def average(self):
return sum(self.grades) / len(self.grades)
student = Student("Bob", (90, 90, 93, 78, 90))
student2 = Student("Rolf", (100, 89, 93, 78, 100))
print(student.name)
print(student.grades)
print(student2.name)
print(student2.grades)
# uses the object that was created, calling the Student class, then the average fn, and put the student object in.
# class fn object
print(Student.average(student))
# or better, get it to do the conversion for you, call the average method on the object itself:
print("Student average", student.average())
print("Student2 average", student2.average())
# calling the class, Student, creates a new empty object, runs the 'init' method and will create empty 'self' and you will be able to modify the name property inside self and give it the value Rolf.
# once the self object contains a name property, Python will give back that self, and 'student' will become a name for the self thing we created.
# so we are using this class, Student, through the init method to create an object and assign the name property to inside the object to the string Rolf. Then that object is what becomes the value for our 'student' variable.
# you call a class, the init method runs, and what you get back is the object you created.
# (90, 90, 93, 78, 90)
| true |
383e729b72c0c31f1d137206bba33d2d8ce5b763 | cmulliss/gui_python | /challenges/lambda.py | 515 | 4.34375 | 4 | # lambda fns dont have a name and only used to return values.
print((lambda x, y: x + y)(5, 7))
# def double(x):
# return x * 2
# list comprehensions
sequence = [1, 2, 3, 4, 5]
# doubled = [double(x) for x in sequence]
doubled = [(lambda x: x * 2)(x) for x in sequence]
print(doubled)
# if you want to use lambda fns, use map
# doubled = map(double, sequence)
# need to convert to list as map doesn't return a list, but returns a map object
doubled = list(map(lambda x: x * 2, sequence))
print(doubled)
| true |
27bd9ff92a28e481101e751b7abb5646a4c89fb9 | HorseBackAI/PythonBlockchain | /6_标准库/6-standard-library-assignment/assignment.py | 413 | 4.125 | 4 | import random
import datetime
# 1) Import the random function and generate both a random number
# between 0 and 1 as well as a random number between 1 and 10.
rn1 = random.random()
rn2 = random.randint(1, 10)
print(rn1, rn2)
print()
# 2) Use the datetime library together with the random number
# to generate a random, unique value.
now = datetime.datetime.now()
print(now)
rv = str(rn1) + str(now)
print(rv)
| true |
e5790aa876fa2089b5c3fb568031e407447d036b | andrezzadede/Curso_Guanabara_Python_Mundo_3 | /Mundo 3 - Exercícios/83Exercicio.py | 529 | 4.125 | 4 | #Crie um programa onde o usuario digite uma expressao qualquer que use paratenses. Seu aplicativo deverá analisar se a expressao passada está com os paratenses abertos e fechados na ordem correta.
expressao = str(input('Digite a expressao: '))
pilha = []
for simb in expressao:
if simb == '(':
pilha.append('(')
elif simb == ')':
if len(pilha)>0:
pilha.pop() # remove o ultimo elemento da lista
else:
pilha.append(')')
break
if len(pilha) == 0:
print('Sua expressao é valida')
else:
print('Errado')
| false |
d872e611e08f88b8ecc0eccfb20ced6534406140 | Azevor/My_URI_Reply | /beginner/1006.py | 433 | 4.15625 | 4 | '''
Read three values (variables A, B and C), which are the three student's grades.
Then, calculate the average, considering that grade A has weight 2, grade B has
weight 3 and the grade C has weight 5. Consider that each grade can go from 0
to 10.0, always with one decimal place.
'''
m_N1 = float(input())*2
m_N2 = float(input())*3
m_N3 = float(input())*5
m_Pound = 2+3+5
print('MEDIA = {:.1f}'.format((m_N1+m_N2+m_N3)/m_Pound))
| true |
176e5fddfb93a10aa9a3775878d24bf69ebf1416 | khanaw/My-Python-practice | /Fibonacci+Sequence+Generator.py | 1,647 | 4.59375 | 5 |
# coding: utf-8
# # Fibonacci Sequence Generator
#
# ### Enter a number and generate its Fibonacci Number to that number
# The limit is set to 250. You can increase the limit but may get errors. Use recursion to obtain better results at higher numbers. If you wanted to find 1500, it would be better to run the number in increments of 250 to 1500
#
# A quick note: if you want to see the 22nd term in the fibonacci it will be the fibonacci number for 21. Thus if you wanted to see the fibonaci number for 22, which is term 23, you would have to enter 23
# #### Info on Fibonacci can be found here https://en.wikipedia.org/wiki/Fibonacci_number
# In[8]:
def fibonacci(num):
"""
Return the next and current terms in a fibonnacie sequence
"""
#if the number is 1 return terms 1,0
if num == 1:
return[1,0]
#case for above 1
else:
term=fibonacci(num -1)
term=[term[0] +term[1],term[0]]
return term
# In[9]:
def valid_integer():
"""
Obtain a positive integer less than 200
"""
while True:
num=int(input('Enter the term in the Fibonacci Sequence you want to see: '))
try:
if num>=250:
print('Enter a number smaller than 250')
elif num>0:
return num
break
else:
print('Enter a positive number')
except:
print('Enter an integer')
# In[10]:
def get_fibonacci():
num=valid_integer()
print(fibonacci(num)[1])
# In[ ]:
## call the get_fibonacci() function to obtain the term you want to see
get_fibonacci()
| true |
2d95b0d05e10b25907ad90e44da69b3eb854dd4e | pythonerForEver/EZ-Project | /guess_number.py | 2,096 | 4.15625 | 4 | #! /usr/bin/python3.6
import random
def game_help(minimum=0, maximum=100):
print("""
you have 5 chance to guess number in our mind that
is between {min_}<number<{max_}.
""".format(min_=minimum, max_=maximum))
def guess_number():
maximum = 100
minimum = 0
game_help(minimum, maximum)
random_number = random.randint(minimum, maximum)
player_chance = 5
while True:
guessed = False
your_guess = input("Remained Chance({chance})>".format(chance=player_chance)).lower().split()
if not len(your_guess):
continue
if len(your_guess) > 1:
print("Wrong input, please enter just one number in each round.")
continue
if not your_guess[0].isnumeric():
print("Wrong input, what are you doing? please enter a number.")
continue
if not minimum < int(your_guess[0]) < maximum:
guessed = False
print("Wrong ,enter number between %d and %d." % (minimum, maximum))
else:
guessed_number = int(your_guess[0])
if guessed_number == random_number:
guessed = True
break
if guessed_number < random_number:
print("Wrong ,please enter a bigger number.")
else:
print("Wrong ,please enter a smaller number.")
if not guessed:
player_chance -= 1
if player_chance == 0:
guessed = False
break
if guessed:
print("congratulation you guess our number {random_num} successfully."
"".format(random_num=random_number))
else:
print("oh oh oh! you lose. our number is {random_num}.".format(random_num=random_number))
def main():
answer = input("Are you ready to guess number in our mind?(press y to continue)\n>")
if answer.lower() != "y":
print("Come back as soon as possible.")
exit(0)
print("Let's Go.")
guess_number()
if __name__ == "__main__":
main()
| true |
3629b979e2f3bef3ddd7554ce77b88f43ffebfc8 | inventsekar/LinuxTools-Thru-Perl-and-Python | /linux-wc-command-implementation-Thru-Python.py | 779 | 4.1875 | 4 | #!/usr/bin/python
# inventsekar 5th march 2018
# python implementation of Linux tool "wc"
line1 = raw_input("Please enter line1:");
line2 = "A quite bubble floating on a sea of noise. - The God of Small Things - Arundhati Roy";
line3 = "Hello, How are you";
#-------------------------------------#
# Finding number of words: wc -w
#-------------------------------------#
print "Finding numer of words: wc -w\n";
print "---------------------------------\n";
#$nWords=0;
#while ($line1 =~ /\b\w+\b/g){ $nWords++; }
print "line1 is:", line1;
#print "\$line1 contains $nWords words\n";
wordCount=0
for lineOfText in range(1-3):
print(str(linei),str(lineOfText))
f1=lineOfText.split()
wordCount=wordCount+len(f1)
print ("number of words: wc -w:" +str(wordCount))
| true |
f696510ab7ff2a945d649c4ca397c637f5d1c3e9 | CurroValero05/TIC-2-BACH | /Contrasena_2.py | 268 | 4.15625 | 4 | #Escribe un programa que genere una contrasena
#con 3 letras de tu nombre y 3 del aellido
def contrasena_2():
nombre=raw_input("Introduce el nombre: ")
apellido=raw_input("Introduce el apellido: ")
print nombre[-3:]+apellido[-3:]
contrasena_2()
| false |
5c342d84049215a42fb64986ecbdff53baf62da8 | vanessa617/Dev_2017 | /tuples.py | 531 | 4.46875 | 4 | #creating a tuple
t1 = ('a','b','c')
print type(t1)
#create an empty tuple
t2 = ()
print t2
print type(t2)
#you have to use a comma even if the tuple has one element
t2 = (1,)
print t2
#getting the first element
print t1[0] #output = a
#getting the last element
print t1[-1] #output = c
#getting elements using slicing
print t1[1:3] #output = ('b', 'c') - returns the second and third elements
a = (1,2,3,4,5)
print type(a)
#replace the first element with (10, ), and reassign result to a new tuple
b = (10,) + a[1:]
print b | true |
f03a785fce0b9814e652bd587bb824d64588adaa | cpe202spring2019/lab1-JackBeauche | /lab1.py | 2,132 | 4.1875 | 4 |
def max_list_iter(int_list): # must use iteration not recursion
# finds the max of a list of numbers and returns the value (not the index)
# If int_list is empty, returns None. If list is None, raises ValueError
# Check if list is None:
if (type(int_list) == type(None)):
raise ValueError
# Check if int_list is empty
elif (len(int_list) == 0):
return(None)
# Process list iteratively if both checks fail
else:
MaxVal = int_list[0] # Assume MaxVal is first value
for i in int_list:
if i > MaxVal: # Update MaxVal if an item is larger
MaxVal = i
return(MaxVal)
pass
def reverse_rec(int_list): # must use recursion
# """recursively reverses a list of numbers and returns the reversed list
# If list is None, raises ValueError"""
if(type(int_list) == type(None)):
raise ValueError
elif(len(int_list) == 0):
return(int_list)
else:
return(reverse_rec(int_list[1:]) + int_list[0:1])
pass
def bin_search(target, low, high, int_list): # must use recursion
# """searches for target in int_list[low..high] and returns index if found
# If target is not found returns None. If list is None, raises ValueError """
if(type(int_list) == type(None)):
raise ValueError
elif(int_list == []):
return None # test for empty list
elif( low <= high):
mid = (low + high)//2 # mid point is defined
if(target == int_list[mid]): # return mid if target is found
return(mid)
elif(target < int_list[mid]): # can search only the lower half of the list, since target is not found, we decrease 1 from mid and that is new high
return(bin_search(target, low, mid - 1, int_list))
else:
return(bin_search(target, mid + 1, high, int_list)) # can search only the upper half of the list, since target is not found, we increase 1 from mid and that is new low
else:
return(None) # target is not found in list
pass
if __name__ == '__main__':
max_list_iter(None) | true |
554a6913036341f20d00e1d6341c98a411331869 | abhiunix/python-programming-basics. | /forloop.py | 1,152 | 4.875 | 5 | #forLoop
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
for city in cities:
print(city)
print("Done!")
#Using the range() Function with for Loops
for i in range(3):
print("Hello!")
#range(start=0, stop, step=1)
#Creating and Modifying Lists
#In addition to extracting information from lists, as we did in the first example above,
#you can also create and modify lists with for loops.
#You can create a list by appending to a new list at each iteration of the for loop like this:
# Creating a new list
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
capitalized_cities = []
for city in cities:
capitalized_cities.append(city.title())
#Modifying a list is a bit more involved, and requires the use of the range() function.
#We can use the range() function to generate the indices for each value in the cities list.
#This lets us access the elements of the list with cities[index] so that we can modify the values in the cities list in place.
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
for index in range(len(cities)):
cities[index] = cities[index].title() | true |
506f053a5695a697513ed9599f28d76c70069869 | abhiunix/python-programming-basics. | /enumerate.py | 745 | 4.5 | 4 | #Enumerate
#enumerate is a built in function that returns an iterator of tuples containing indices and values of
#a list. You'll often use this when you want the index along with each element of an iterable in a loop.
letters = ['a', 'b', 'c', 'd', 'e']
for i, letter in enumerate(letters):
print(i, letter)
#Quiz: Enumerate
#Use enumerate to modify the cast list so that each element contains the name followed by the
#character's corresponding height. For example, the first element of cast should change from
#"Barney Stinson" to "Barney Stinson 72".
cast = ["Barney Stinson", "Robin Scherbatsky", "Ted Mosby", "Lily Aldrin", "Marshall Eriksen"]
heights = [72, 68, 72, 66, 76]
#forLoop
for i, character in enumerate(cast):
cast[i] = character + " " + str(heights[i])
print(cast) | true |
85ad6a8a91801ca457548e5ec62eacd5090c9c14 | RileyWaugh/ProjectEuler | /Problem5.py | 1,103 | 4.125 | 4 | #Problem: 2520 is the smallest number divisible by 1,2,3,...10.
# What is the smallest number divisible by 1-20 (more generally, 1-n)?
import math
def greatestLesserPower(x,y):
#findsthe greatest power of x less than or equal to y
if x > y:
return 0
product = 1
while product <= y:
product *= x
return product/x
def isPrime(x):
if (x == 2 or x == 3 or x ==5 or x == 7):
return 1
test = 1
for i in range(2, int(math.ceil(math.sqrt(x))+1)):
if not(x%i):
test = 0
break
return test
def lowerPrimes(x):
#generates the list of all primes less than or equal to x
plist = []
for i in range(2,x+1):
if isPrime(i):
plist.append(i)
return plist
def main():
#strategy: find the product of the greatest powers less than num of each prime number less than num
'''print(isPrime(27), isPrime(31), isPrime(3), isPrime(4), isPrime(11))
print(lowerPrimes(25), lowerPrimes(31))
print(greatestLesserPower(5,7), greatestLesserPower(2,40))'''
num = 20
plist = lowerPrimes(num)
product = 1
for i in plist:
product *= greatestLesserPower(i, num)
print(product)
main() | true |
b2b71150f3d13bfd8de9d35a6fd26f500dcb409c | josenavarro-leadps/class-sample | /teamManager.py | 1,426 | 4.28125 | 4 | #made a class that contains the goals, age, and name.
#"self" is always being needed
class player(object):
def __init__(self, goals, age, name):
self.goals = goals
self.age = age
self.name = name
#now I made a function in my class
def playerstats(self):
print("name" + self.name)
print("goals" + self.goals)
print("age" + self.age)
#empty list to add on to
myPlayers = []
#made print statements to let the user know that there is three options
print ("If you want to add a plyer press 1")
print ("If you want to copy a player press 2")
print ("Press 0 to exit")
choice = int(input())
while choice != 0:
# asks the user for data if they chose number 1
#data: name, age, goals
if choice == "1":
print ("whats the new members name")
name = input()
#name of memeber
print ("How old is the new player")
age = input()
#asks for age
print ("How many goals did the new player make")
goals = input()
#goals in life time
#adds the new player to the list
myPlayers.append(player(name, age, goals))
print ("Do you want to keep adding players, or do you want to copy all players")
choice = input()
#will copy the the goals, age, and ,name
elif choice == "2":
for status in myPlayers:
status.playerStats()
# asks what you want to do
print ("choose again, 1:add a new player to the squad, 2:copy status from players")
choice = input()
| true |
f00047a3067e5bf47b9cc47d2b93e63d83a8451a | AlexVillagran/curso-basico-python | /Ej3-Variables.py | 1,322 | 4.15625 | 4 | # coding=utf-8
name = "Fazt"
print(10+10)
print (name)
#En una variable podemos guardar un numero, un decimal,
#un entero, booleano , una dubla,lista , diccionario un None
x = 100
# Case Sensitive : sensible a distinguir entre letras mayusculas y minusculas
libro = "Mi libro de Historia"
Libro = "Mi otro libro de Historia"
#Reglano podemos tener variables que comienzan con numero
#2Libro="Mi libro de Historia"
print (libro)
#Definir he inicializar con un valor las variables en una sola linea
y, robot = 100, "Mi Robot"
print (x, robot)
#Convencion- separar nombre de variables formadas por 2 o mas palabras se debe separar con guion bajo
#Esto hace mas legibles nuestros codigos
nombre_libro = "Vendele a la mente" #Snake Case (esta es muy tipica en python)
nombreLibro = "Quién se robo mi queso" #Camel Case
NombreLibro = "El Efecto compuesto" #Pascal Case
#Se llaman convenciones por que los programadores eligen una forma definir sus variables
#Cuando escribimos un valor que no cambia, se le conoce como constante. Se escriben
#todo en mayusculas
PI = 3.1426
MI_NOMBRE = "Manuel"
#Python es un lenguaje dinamico, es decir es de tipado dinamico
nombre_libro = "Mi libro"
print (nombre_libro)
nombre_libro = 10 #Podemos asignar un valor de distinto tipo a una misma variable
print (nombre_libro)
| false |
3cfeda8a19cc9e5e490fa862e0744ab1122fb419 | 14masterblaster14/PythonTutorial | /P11_tryexception.py | 1,142 | 4.125 | 4 | #############################
#
# 21# Try Except :
# - The try block lets you test a block of code for errors.
# - The except block lets you handle the error.
# - The finally block lets you execute code, regardless of the result
# of the try- and except blocks.
#############################
try:
print(7 / 2)
except:
print("An exception occurred")
# O/P : 3.5
try:
print(7 / 0)
except:
print("An exception occurred")
# O/P : An exception occurred
try:
print(x / y)
except ArgError:
print("Invalid Devider value")
except:
print("An exception occurred")
"""
Till now O/P :
Traceback (most recent call last):
File "D:/DESKTOP/python/Tryexception.py", line 25, in <module>
print(x / y)
NameError: name 'x' is not defined
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:/DESKTOP/python/Tryexception.py", line 26, in <module>
except ArgError:
NameError: name 'ArgError' is not defined
3.5
An exception occurred
Process finished with exit code 1
"""
| true |
c54ad499a961fab6567a02703e0d48f6a67afe82 | Katherinaxxx/leetcode | /557. Reverse Words in a String III.py | 574 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2020/8/18 下午9:47
@Author : Catherinexxx
@Site :
@File : 557. Reverse Words in a String III.py
@Software: PyCharm
"""
class Solution:
def reverseWords(self, s: str) -> str:
res = ''
sl = s.split()
def helper(s):
res = ''
for i in range(len(s)-1,-1,-1):
res += s[i]
return res
new_sl = list(map(helper, sl))
return ' '.join(new_sl)
def reverseWords(self, s):
return ' '.join(x[::-1] for x in s.split()) | false |
74c8e37b1aee8458ec2a85dd3cc3f8912b0796bd | 95ktsmith/holbertonschool-machine_learning | /math/0x06-multivariate_prob/0-mean_cov.py | 863 | 4.34375 | 4 | #!/usr/bin/env python3
""" Mean and Covariance """
import numpy as np
def mean_cov(X):
"""
Calculates the mean and covariance of a data set
X is a numpy.ndarray of shape(n, d) containing the data set
n is the number of data points
d is the number of dimensions in each data point
Returns mean, cov:
mean is a numpy.ndarray of shape (1, d) containing the data set mean
cov is a numpy.ndarray of shape (d, d) containing the data set
covariance matrix
"""
if type(X) is not np.ndarray or len(X.shape) != 2:
raise TypeError("X must be a 2D numpy.ndarray")
if X.shape[0] < 2:
raise ValueError("X must contain multiple data points")
mean = np.average(X, axis=0).reshape((1, X.shape[1]))
x = X[:, :] - mean[0, :]
cov = x.T @ x / (x.shape[0] - 1)
return mean, cov
| true |
17ed305f38dc835d83d6661db0de6a9ba8cca688 | njcssa/summer2019_wombatgame | /student_assessment/student_assessment1.py | 2,990 | 4.1875 | 4 | # To do with instructors:
# create 5 variables which all hold different types of data
# at least 1 should hold an int
# at least 1 should hold a double
# at least 1 should hold a boolean
# at least 1 should hold a string
# 1 variable can hold whatever you want
# then print out what one variable holds
# make a program which comments on peoples' age
# if they are younger than 5 print "you are young"
# if they are between 6 and 12 print "you are a kid"
# if they are between 13 and 19 print "you are a teenager"
# if they are 18 or 19 print "you are a teenager and an adult"
# if they are between 20 and 64 print "you are an adult"
# if they are 65 or older, print "you are a senior citizen"
def age_commenter(age):
pass
# make 4 if statements
# 1 should have a not
# 1 should have an and
# 1 should have an or
# 1 should combine at least 2 of an and, or, not
def if_statements():
pass
# make a while loop that prints the numbers 1-10
def print_ten():
pass
# make a while loop that counts by twos
def count_by_two():
pass
# make a while loop that loops through the number 1-10
# only print out numbers if they are greater than 5
def print_greater_than_five():
pass
# make a function that takes two parameters that are ints
# inside the function have it print out the sum
# remember to call the function
def add(a, b):
pass
add(1, 2)
# make a function that takes two parameters that are ints
# inside the function have it return the sum
# remember to call the function
# now call the function within the add2 function
def add2(a, b):
pass
add2(add2(1, 1), add2(4, 2))
# make a function that returns a list of even numbers in a certain range
# print the returned list
def get_evens(start, end):
pass
print(get_evens(2, 19))
# make a function which takes a list of ints as an input
# have the function return a list with every value in the original list doubled
def double_list(sl):
pass
new_list = double_list([1, 2, 3, 4, 5, 6])
# alternate version that deals with lists and references
def double_list2(sl):
pass
some_list = [1, 2, 3, 4, 5, 6]
double_list2(some_list)
print(some_list)
# lists are special though because this doesn't work with other types of variables
def reference_example(i):
pass
i = 5
reference_example(i)
print(i)
# make a function which bubble sorts a list
def bubble_sort(li):
pass
li = [2, 6, 5, 1, 3, 10, 9, 11]
bubble_sort(li)
print(li)
# To do by yourself:
# make a function which takes a list as a parameter
# return the smallest number
def get_smallest(li):
pass
li = [2, 5, 1, 76, 89, 0, 3]
print(get_smallest(li))
# make a function which calculates a number to a power
# return the answer
def power(a, b):
pass
print(power(5, 5))
# Make a function which takes in a list of integers as a parameter.
# return the number of even integers in the list.
list1 = [22, 32, 55, 90, 24, 67]
def count_evens(l):
pass
print(count_evens(list1))
| true |
85ba0c5919184a9376bb29b59c5e60123c53d60c | mat105/enviame-backend-test | /Ejercicio-3/main.py | 1,532 | 4.15625 | 4 | SAMPLE_STRING = 'afoolishconsistencyisthehobgoblinoflittlemindsadoredbylittlestatesmenandphilosophersanddivineswithconsistencyagreatsoulhassimplynothingtodohemayaswellconcernhimselfwithhisshadowonthewallspeakwhatyouthinknowinhardwordsandtomorrowspeakwhattomorrowthinksinhardwordsagainthoughitcontradicteverythingyousaidtodayahsoyoushallbesuretobemisunderstoodisitsobadthentobemisunderstoodpythagoraswasmisunderstoodandsocratesandjesusandlutherandcopernicusandgalileoandnewtonandeverypureandwisespiritthatevertookfleshtobegreatistobemisunderstood'
# Separo todas las posibles combinaciones de cadenas y luego las comparo con ellas mismas dadas vuelta.
# Agrego las que son iguales a una coleccion.
def is_palindrome(word):
return len(word) > 1 and word == word[::-1]
# Devuelve un listado de cadenas (sin repetir) que son palindromos dentro del string.
# Si se quieren repetidos puede usarse una lista.
def process(text):
text_len = len(text)
palindromes = set()
for i in range(text_len):
for j in range(i, text_len):
word = text[i:j+1]
if is_palindrome(word):
palindromes.add(word)
return palindromes
if __name__ == '__main__':
pals = process(SAMPLE_STRING)
string_replaced = SAMPLE_STRING
for k in pals:
string_replaced = string_replaced.replace(k, k.upper())
print('\n### Palindromos encontrados:', f'({len(pals)})')
print(pals)
print('\n### Palindromos convertidos a mayusculas en la cadena:')
print(string_replaced)
| false |
e214dfe2f5ee9b8bbf23bbe42daf9a62bbb4c316 | varunkudva/Programming | /dynamic_programming/balanceParenthesis.py | 722 | 4.21875 | 4 | """
Given n pairs of parentheses, find all possible balanced combinations
Solution:
1. Start with clean slate and add left parenthesis.
2. Add right parenthesis only if there are more left parenthesis than right.
3. Stop if left count == n or right count > left count.
"""
def add_parenthesis(n, left, right, idx, res):
# base and error cases
if left > n or right > left:
return
if left == n and right == n:
print("".join(res))
else:
res[idx] = '('
add_parenthesis(n, left+1, right, idx+1, res)
res[idx]= ')'
add_parenthesis(n, left, right+1, idx+1, res)
if __name__ == '__main__':
n = 3
res = [""] * n * 2
add_parenthesis(n, 0, 0, 0, res)
| true |
e76a4f77828e4af880bfc6de8bc99e6a86f58bd7 | RocqJones/python3x_mega | /1.0Basics_Recap/1.8whileLoopRecap.py | 924 | 4.1875 | 4 | # The program will allow a user to create username n password & store in a list then verify the password.
# create user
user_name = input("Enter User Name: ")
user_password = input("Enter new password:")
user_db = []
user_db.append(user_name)
user_db.append(user_password)
# test db
# print(user_db)
# Break
for symbol in "***************************************************************************":
print(symbol*2)
# Verify password by checking from database
print("Verify password to proceed please!!!")
verify_password=''
while verify_password != user_db[1]:
verify_password = input("Verify password: ")
if verify_password == user_db[1]:
print("SUCCESS!!\n Your bank a/c 122 556 661 649")
else:
print("Sorry, Try again! If you forgot password type 'hint'")
# give hint
if verify_password == "hint":
h = user_db[1]
print(h[:3] + "..." + h[-3:])
| true |
88e9d79d5194b389f295f37e2a4b7d6264bbd817 | stdout-se/tenant | /random_utils.py | 1,042 | 4.125 | 4 | import random
def from_dungeon_level(table, dungeon_level: int):
for (value, level) in reversed(table):
if dungeon_level >= level:
return value
return 0
def random_choice_from_dict(choice_dict: dict):
"""
Provided a dictionary, will return a randomly selected key string. The key is randomly selected based on relative
weights, provided for each key as a value.
Example:
dict = {'orc': 80, 'troll': 30, 'demon': 5}
random_choice_from_dict(dict)
This will return a choice of either 'orc', 'troll' or 'demon' according to the relative weights provided.
:param choice_dict: Dictionary, where keys are options and values are their relative weights
:return: Random choice, selected according to provided weights
"""
population = list(choice_dict.keys()) # Ex: ['orc', 'troll', 'demon']
relative_weights = list(choice_dict.values()) # Ex: [80, 30, 5]
return random.choices(population, weights=relative_weights)[0] # Take item from list with a single item
| true |
8b13f5f6647438ba94bba082bcbdeb8d87e2f8ae | SzymonSauer/Python-basics | /BMI_Calculator.py | 412 | 4.21875 | 4 | print("Enter your height: ")
height = float(input())
if height >=3.00:
print("Wow! You are the world's highest man! ;)")
print("Enter your weight: ")
weight = float(input())
bmi = weight/(height**2)
print("BMI:"+str(bmi))
if bmi<18.5:
print("You are too thin!")
elif bmi>=18.5 and bmi <25:
print("Congratulatons! You have great BMI!")
elif bmi>=25:
print("You are overweight!") | true |
4b74595fb181c56249a3674c9810745b01b26057 | arrancapr/Clases | /Python1ArrancaPr/Samples/dict.py | 469 | 4.21875 | 4 | #define a dictionary
fruitsByColor = {"red": "apple", "blue": "berry"}
#retrieve the values
name =""
print(fruitsByColor["blue"])
while( name != "-done"):
print("Enter student name to get their hobbies")
name= input()
HobbiesByPerson = {"Aaron":["Photography","Spelunking"],
"Sarah":["Climbing","Spelunking"]}
if(name != "-done"):
hobbies = HobbiesByPerson[name]
for h in hobbies:
print(h)
print("We are done")
| false |
00c8d588b17af0b3faa11ab875504abffbda571d | sillyer/learn-python-the-hard-way | /ex33.py | 402 | 4.15625 | 4 | numbers = []
#while i<6 :
# print "at the top i is %d" % i
# numbers.append(i)
# i = i+1
# print "Number now: ", numbers
# print "At the bottom i is %d" % i
def add_list(elem_range, num_list):
i=0
while(i<elem_range):
print "add %d to %r" % (i,numbers)
num_list.append(i)
print "then the list is:", numbers
i = i+1
add_list(6,numbers)
print "the numbers: "
for num in numbers:
print num,
| false |
ba80abfcae511a6681c294525ebc1caea40f5681 | birsandiana99/UBB-Work | /FP/Laboratory Assignments/Sapt 1/Assignment 1/pb8.py | 1,389 | 4.125 | 4 | def prim(x):
'''
Input: x-integer number
Output: sem (0 if the number is not prime, 1 if the number is prime)
Determines if the number given is prime or not by verifying if it has any divisors other than itself
'''
sem=1
'special case if the value given is 1 or is a multiple of 2'
if x==1 or x%2==0:
sem=0
else:
'special case if the number is 2'
if x==2:
sem=1
else:
for i in range(3,x//2):
if x%i==0:
sem=0
return sem
def twin_Numbers(x):
'''
Input: x- interger number
The subprogram prints the closest prime numbers to x, which satisfy the condition q-p=2
First we give p the immediate next value to x and q the value p+2 and verify if they are both prime
'''
p=x+1
q=p+2
'if they are not in the first case, we continue increasing p with 1 and q with 2 until we find the closest 2 twin prime numbers to x and print them'
if prim(p)==1 and prim(q)==1:
print(p," ",q)
else:
p=p+1
q=p+2
ok=0
while ok==0:
if prim(p)==1 and prim(q)==1:
print(p," ",q)
ok=1
else:
p=p+1
q=p+2
x=int(input("Give me the number: "))
twin_Numbers(x)
| true |
a2bfd8ddd0c0c484fcfa54807d770d2527a57d6e | birsandiana99/UBB-Work | /FP/Laboratory Assignments/Sapt 1/first 1.py | 260 | 4.125 | 4 | def sum(a,b):
'''
Adds two numbers.
Input: a, b -integer numbers
Output: the sum of a and b (integer)
'''
return a+b
x=int(input("Give me the first number: "))
y=int(input("Give me the first number: "))
print("The sum is: ", sum(x,y))
| true |
8823f2aa3f984cb92582136b0560acc089c7803b | y281473724/Py-base | /元类type().py | 760 | 4.40625 | 4 | #动态语言和静态语言最大的不同,就是函数和类的定义
#不是编译时定义的,而是运行时动态创建的
#type()函数既可以返回一个对象类型,又可以创建出新的类型
#比如我们可通过type()函数创建一个Hello类而无需通过class Hello(object):...的方法
def fn(self,name = 'world'):#先定义函数
print('Hello,%s.' %name)
#创建一个class对象,type()函数依次传入3个参数:
#1.class的名称;
#2.继承的父类集合,如果只有一个父类,要注意tuple单元素的写法;
#3.class的方法名称与函数绑定,这里把函数fn绑定到方法名hello上。
Hello = type('Hello', (object,), dict(hello = fn))#创建Hello class
h = Hello()
h.hello() | false |
5d31c9047b9c34c18a894b1fcceba1cb3d531a5a | DhirendraBhatta/Jupyter | /rpsgame.py | 977 | 4.34375 | 4 | #Assignment of Rock Paper Scissor Game by Dhirendra Bhatta
import random
comp = random.randint(1,3)
print("Computer's generated input is: ",comp)
user = int(input('Enter 1 for rock,2 for paper and 3 for scissor '))
while user not in [1,2,3]:
user = int(input('Enter 1 for rock,2 for paper and 3 for scissor '))
if user == comp:
print("Computer and User both entered the same value.Hence it's draw.")
elif user == 1 and comp == 2:
print(' Paper covers the rock.So Computer wins.')
elif user == 2 and comp == 3:
print(' Scissor cuts paper.So Computer wins.')
elif user == 3 and comp == 1:
print(' Rock broke scissor.So Computer wins.')
elif comp == 1 and user == 2:
print('Paper covers the rock.So User wins.')
elif comp == 2 and user == 3:
print('Scissor cuts the paper.So User wins.')
elif comp == 3 and user == 1:
print('Rock broke the scissor.So User wins.')
else:
print('Thank you for playing the game rock paper scissor')
| true |
fd63741c194d59c392125be8f8553e610c616b0d | Xenocide007/Python-Projects | /3.py | 1,009 | 4.1875 | 4 | #3 in a row
import random
names = []
gameBoard = [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]]
def inputNames():
name1 = raw_input("Enter first player's name here: \t")
name2 = raw_input("Enter second player's name here: \t")
return name1, name2
def first(name1, name2):
num1 = int(raw_input("%s, guess a number between 1 and 10, closest person wins and get to go first!\t" % name1))
num2 = int(raw_input("%s, pick a number\t" % name2))
if num2 == num1:
num2 = int(raw_input("%s, choose a different number" % name2))
RNG = random.randint(0, 10)
print ("%d is the number" % RNG)
if abs(num1 - RNG) > abs (num2 - RNG):
print "%s goes first" % name2
else:
print "%s goes first" % name1
def move(board):
mov = raw_input("Pick a number between 1 and 9 (that hasn't been picked already)")
for listt in board:
for subvalue in range(len(listt)):
if mov == subvalue:
listt[subvalue]= "X"
print board
#names = inputNames()
#first(names[0], names[1])
move(gameBoard)
| true |
4dfb1a39f65da88252968ef388cb29817dcc14ee | gabrielSSimoura/ReverseWordOrder | /main.py | 556 | 4.40625 | 4 | # Write a program (using functions!) that asks the user for a long string containing multiple words.
# Print back to the user the same string, except with the words in backwards order.
# For example, say I type the string:
# My name is Gabriel
# Then I would see the string:
# Gabriel is name My
# shown back to me.
def main():
userInput = str(input("Type a sentence: "))
userInput = userInput.split()
userInput = userInput[::-1]
userInput = " ".join(userInput)
print("Your reverse sentence should be: " + userInput)
main()
| true |
e9bc436baa593405e732b1cb59db5d72945be174 | chanyoonzhu/leetcode-python | /708-Insert_into_a_Sorted_Circular_Linked_List.py | 1,215 | 4.125 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
"""
"""
- two pointers
- O(n), O(1)
"""
class Solution:
def insert(self, head: 'Optional[Node]', insertVal: int) -> 'Node':
if not head:
node = Node(insertVal)
node.next = node
return node
def should_insert_in_between(prev, nextt):
if not prev or not nextt:
return False
if prev.val <= insertVal <= nextt.val: # right in between
return True
if prev.val > nextt.val and (insertVal <= nextt.val or insertVal >= prev.val): # at circular point
return True
return False
prev, nextt = None, head
while not prev or nextt != head: # break when traversed the entire circle
if should_insert_in_between(prev, nextt):
prev.next = Node(insertVal, nextt)
return head
else:
prev, nextt = nextt, nextt.next
# need to be inserted as prev of head
# tail -> prev
prev.next = Node(insertVal, nextt)
return head
| true |
f9e731280039de962fbd886d3603f04ee5a2bff1 | chanyoonzhu/leetcode-python | /319-Bulb_Switcher.py | 418 | 4.21875 | 4 | """
- Math logic
- intuition: light bulbs that are left on are switched odd number of times. Divisors come in pairs 12 = 2 * 6 = 3 * 4, only exception is when n is a square number like 16 = 4 * 4 (one single divisor).
So only square numbers will be on at the end. Find all square numbers equal to or less than n.
- O(1), O(1)
"""
class Solution:
def bulbSwitch(self, n: int) -> int:
return int(sqrt(n)) | true |
96fcc3eecfd5be51af858e83e8dd064ff390a2d5 | AidanH6/PythonBeginnerProjects | /higherlower.py | 990 | 4.46875 | 4 | """
Create a simple game where the computer randomly selects a number between 1 and 100 and the user has to guess what the number is.
After every guess, the computer should tell the user if the guess is higher or lower than the answer.
When the user guesses the correct number, print out a congratulatory message.
"""
import random
playing = True
tries = { "try": 0 }
compNum = random.randint(0,100)
while playing:
guess = int(input("The computer has selected a number between 0 and 100. Try guess it!: "))
if guess > 100:
print("Invalid number. please enter it again.")
if guess > compNum:
print("That guess was higher than the computer's number!")
tries['try'] += 1
elif guess < compNum:
print("That guess was lower than the computer's number!")
tries['try'] += 1
else:
tries['try'] += 1
print("You guessed right! It took you {tries} tries.".format(tries=tries['try']))
exit() | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.