blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f48ad084c38a7023a5850dc1452b2534e620e776 | Anku-0101/Python_Complete | /DataTypes/03_TypeCasting.py | 229 | 4.1875 | 4 | a = "3433"
# Typecasting string to int
b = int(a)
print(b + 1)
'''
str(31) --> "31" => Integer to string conversion
int("32") --> 32 => string to integer conversion
float(32) --> 32.0 => Integer to float conversion
''' | false |
1d8479254cbe4a936f1b7c21715fc58638f61f84 | Anku-0101/Python_Complete | /DataTypes/02_Operators.py | 591 | 4.15625 | 4 | a = 3
b = 4
print("The value of a + b is", a + b)
print("The value of a*b is", a * b)
print("The value of a - b is", a - b)
print("The value of a / b is", a / b)
print("The value of a % b is", a % b)
print("The value of a > b is", a > b)
print("The value of a == b is", a == b)
print("The value of a != b is", a != b)
p... | true |
05f486e4dac5d903bd5ec01c15c0835caa59a8b2 | Weenz/software-QA-hw2 | /bmiCalc.py | 1,631 | 4.3125 | 4 | import math
#BMI Calculator function
def bmiCalc():
print ("")
print ("BMI Calculator")
print ("------------------")
#Loop to verify integer as input for feet
while True:
try:
feet = int(input("Enter your feet part of your height: "))
except ValueError:
... | true |
12491cc31c5021a38cb40799492171c2d5b6b978 | muneel/url_redirector | /redirector.py | 2,194 | 4.25 | 4 | """
URL Redirection
Summary:
Sends the HTTP header response based on the code received.
Converts the URL received into Location in the response.
Example:
$ curl -i http://127.0.0.1:5000/301/http://www.google.com
HTTP/1.0 301 Moved Permanently
Server: BaseHTTP/0.3 Python/2.7.5
Date: Wed, 19 Apr 2017 20:06:11 GMT
Locat... | true |
94c39abb57532962ca90b9df933800cfa6d1b3b3 | AswinT22/Code | /Daily/Vowel Recognition.py | 522 | 4.1875 | 4 |
# https://www.hackerearth.com/practice/basic-programming/complexity-analysis/time-and-space-complexity/practice-problems/algorithm/vowel-game-f1a1047c/
def count_vowel(string,):
vowel = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
count = 0
length=len(string)
for i in range(0, length):
i... | true |
8299f3f9b8ae5f7f1781d56037247da67de61ddd | Cpano98/Ejercicios-Clase | /PruebaWhile.py | 329 | 4.125 | 4 | #encoding: UTF-8
#Autor: Carlos Pano Hernández
#Prueba ciclo while
import turtle
def main():
radio=int(input("Radio:"))
while radio>0:
x=int(input("x:"))
y = int(input("y:"))
turtle.goto(x,y)
turtle.circle(radio)
radio=int(input("Radio:"))
turtle... | false |
d9816ac73df50f5676313824859a15b10485a7c4 | affreen/Python | /pyt-14.py | 511 | 4.28125 | 4 | """demo - script that converts a number into an alphabet and then
determines whether it is an uppercase or lowercase vowel or consonant"""
print("Enter a digit:")
var=input()
var=int(var)
new_var=chr(var)
#if(new_var>=97 and new_var<=122):
if (new_var in ['a','e','i','o','u']):
print("You have entered a... | true |
f33786d90ed22092a69a7114e274fd8610c4d278 | admcghee23/RoboticsFall2019GSU | /multiCpuTest.py | 2,198 | 4.3125 | 4 | #!/usr/bin/env python
'''
multiCpuTest.py - Application to demonstrate the use of a processor's multiple CPUs.
This capability is very handy when a robot needs more processor power, and has processing elements
that can be cleaved off to another CPU, and work in parallel with the main application.
... | true |
18646e411b6caf292796e43014e8093d9c818655 | Mahe7461/Python | /Python IDEL/comparison operator.py | 257 | 4.25 | 4 | #comparison operator
a=10
b=20
if a==b:
print('equal')
elif a!=b:
print('not equal')
elif a>b:
print('greater than')
elif a<b:
print('less than')
elif a>=b:
print('greater than or equal to')
elif a<=b:
print('less than or equal to')
| false |
c7d0404c184ff42bd90467f8aebe5c6d1ac185a9 | csuzll/PyDesignPattern | /创建型/SimpleFactory.py | 1,093 | 4.4375 | 4 | """
简单工厂模式: 集中式生产
"""
# 斧头: 产品抽象类
class Axe(object):
def __init__(self, name):
self.name = name
def cutTree(self):
print("%s斧头砍树" % self.name)
# 花岗岩石斧头: 子产品类
class StoneAxe(Axe):
def cutTree(self):
print("使用%s砍树" % self.name)
# 铁斧头: 子产品类
class SteelAxe(Axe):
def cutTree(self)... | false |
7fb846cef384bf05421502c4602add3a30f2c889 | mahespunshi/Juniper-Fundamentals | /Comprehensions.py | 1,006 | 4.53125 | 5 | # List comprehension example below. notes [] parenthesis. Comprehensions can't be used for tuple.
x =[x for x in range(10)]
print(x)
# create comprehension and it can creates for us, but in dict we need to create it first and then modify it.
# so, we can't create auto-dict, we can just modify dict, unlike list.
# Dict... | true |
19e0975c0f0f0df045b2c1a1e6ff13ad97a3aee6 | BaDMaN90/COM404 | /Assessment_1/Q7functions.py | 1,429 | 4.3125 | 4 | #file function have 4 functions that will do a cool print play
#this function will print piramids on the left of the face
def left(emoji):
print("/\/\/\\",emoji)
#this function will print piramids on the right of the face
def right(emoji):
print(emoji,"/\/\/\\")
#this function will print face between piramid... | true |
3f7d577aacbb73da5406b3676fb12d9947c98e51 | BaDMaN90/COM404 | /Basic/4-repetition/1-while-loop/2-count/bot.py | 684 | 4.125 | 4 | #-- importing the time will allow the time delay in the code
#-- progtram will print out the message and ask for input
#-- 2 variables are created to run in the while loop to count down the avoided live cables and count up how many have avoided
import time
print("Oh no, you are tangle up in these cables :(, how many li... | true |
5996714a292cf5902cefb2830c497c7d81959b54 | RPadilla3/python-practice | /python-practice/py-practice/greeter.py | 407 | 4.1875 | 4 | prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name?"
name = input(prompt)
print("\n Hello, " + name + "!")
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
print("\nThe number " + ... | true |
5d10bf344a26b484e373e93cd734b9c405d3076c | rexrony/Python-Assignment | /Assignment 4.py | 2,548 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
#Question 1
firstname = input("Your First Name Please ");
lastname = input("Your Last Name Please ");
age = int(input("Your Age Please "));
city = input("Your City Please ");
userdata = {
'first_name': firstname,
'last_name': lastname,
'age': age,
'... | true |
8536c9d42de73a7e2b426c38df271740c51f79e2 | HarshHC/DataStructures | /Stack.py | 1,819 | 4.28125 | 4 | # Implementing stack using a linked list
# Node Class
class Node(object):
# Initialize node with value
def __init__(self, value):
self.value = value
self.next = None
# Stack Class
class Stack(object):
# Initializing stack with head value and setting default size to 1
def __init__(self, ... | true |
82bc520ff6d2ea345f94e190032a06296eb89b77 | SugeilyCruz/edd_1310_2021 | /adts/Funcion Recursiva/tarea.py | 1,547 | 4.1875 | 4 | print("Crear una lista de enteros en Python y realizar la suma con recursividad, el caso base es cuando la lista este vacia.")
def suma_lista_rec(lista):
if len(lista) == 1:
return lista[0]
else:
return lista.pop() + suma_lista_rec(lista)
def main():
datos= [4,2,3,5]#14
dt= [4,2,3,5]
... | false |
dec63d4f99825d1934be4b81836d5a3728b8038e | DKanyana/Code-Practice | /ZerosAndOnes.py | 372 | 4.25 | 4 | """
Given an array of one's and zero's convert the equivalent binary value to an integer.
Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.
"""
def binary_array_to_number(arr):
binNum = 0
for cnt,num in enumerate(arr):
binNum += num * (2 ** (len(arr)-1-cnt))
return bin... | true |
67588905fa64b3e7efa93541b569769688d1600f | krrish12/pythonCourse | /Day-4/DecisionMaking.py | 1,578 | 4.125 | 4 | var,var1 = 100,110
if ( var == 100 ) : print("Value of expression is 100 by Comparison operator")
#output: Value of expression is 100
if ( var == 10 ): print("Value of expression is 10 by Comparison operator")
elif(var1 == 50): print("Value of expression is 50 by Comparison operator")
else:print("Value of expression i... | true |
982cdcd7b9d77313def824ed2540e1d4f609f0ab | krrish12/pythonCourse | /Day-3/operators.py | 1,463 | 4.21875 | 4 | obj=10+4
print(obj)#int type
#output: 14
obj=10+3.0
print(obj)#float type
#output:13.0
obj=10-4
print(obj)#int type
#output: 6
obj=10-3.0
print(obj)#float type
#output:7.0
obj=2*2
print(obj)#int type
#output: 4
obj=4.0*2
print(obj)#float type
#output: 8.0
obj=2/2
print(obj)#float type
#output: 1.0
obj=2%2
print(... | false |
56af4680b7f68a43096c0c8d8a9d81a318b3ceea | Tom0497/BCS_fuzzy | /src/FuzzyFact.py | 2,097 | 4.46875 | 4 | class FuzzyFact:
"""
A class to represent a fuzzy fact, i.e. a fact or statement with a value of certainty in the range [-1, 1],
where -1 means that the fact is a 100% not true, whereas a value of 1 means that the fact is a 100% true,
finally, a value of 0 means ignorance or lack of knowledge in terms o... | true |
6048b803d984e8837f31aaa7c31667e396f4b0b0 | yogesh1234567890/insight_python_assignment | /completed/Data3.py | 384 | 4.21875 | 4 | '''3. Write a Python program to get a string from a given string where all
occurrences of its first char have been changed to '$', except the first char itself.
Sample String : 'restart'
Expected Result : 'resta$t' '''
user=input("Enter a word: ")
def replace_fun(val):
char=val[0]
val=val.replace(char,'$')
... | true |
12d6c22a4cdacef7609f965d1f682213f06d25d1 | yogesh1234567890/insight_python_assignment | /completed/Data22.py | 267 | 4.1875 | 4 | #22. Write a Python program to remove duplicates from a list.
mylist=[1,2,3,4,5,4,3,2]
mylist = list(dict.fromkeys(mylist))
print(mylist)
##here the list is converted into dictionaries by which all duplicates are removed and its well again converted back to list | true |
c0874441b6ae538e3be713d71015ec626f04272f | yogesh1234567890/insight_python_assignment | /functions/Func14.py | 498 | 4.4375 | 4 | #14. Write a Python program to sort a list of dictionaries using Lambda.
models = [{'name':'yogesh', 'age':19, 'sex':'male'},{'name':'Rahsit', 'age':70, 'sex':'male'}, {'name':'Kim', 'age':29, 'sex':'female'},]
print("Original list:")
print(models)
sorted_models = sorted(models, key = lambda x: x['name'])
print("\nSo... | true |
93705ba1b2d202737fa5f9f9852ed9814f768eb4 | yogesh1234567890/insight_python_assignment | /functions/Func5.py | 313 | 4.40625 | 4 | """ 5. Write a Python function to calculate the factorial of a number (a non-negative
integer). The function accepts the number as an argument. """
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
n=int(input("Insert a number to calculate the factiorial : "))
print(fact(n)) | true |
7d701dbeb4a04cda556c0bc2da03de589a1d26e9 | yogesh1234567890/insight_python_assignment | /completed/Data39.py | 206 | 4.1875 | 4 | #39. Write a Python program to unpack a tuple in several variables.
a = ("hello", 5000, "insight")
#here unpacking is done
(greet, number, academy) = a
print(greet)
print(number)
print(academy)
| true |
93d2d0026b5d737c60049229091c9c01faedf0f0 | yogesh1234567890/insight_python_assignment | /functions/Func7.py | 666 | 4.25 | 4 | """ 7. Write a Python function that accepts a string and calculate the number of
upper case letters and lower case letters.Sample String : 'The quick Brow Fox'
Expected Output :
No. of Upper case characters : 3
No. of Lower case Characters : 12 """
string="The quick Brow Fox"
def check(string):
upper=0
l... | true |
45c4e66f0dba9851ea5539d2c98e6076ed1ad8fd | sk-ip/coding_challenges | /December_2018/stopwatch.py | 734 | 4.125 | 4 | # program for stopwatch in python
from datetime import date, datetime
def stopwatch():
ch=0
while True:
print('stopwatch')
print('1. start')
print('2. stop')
print('3. show time')
print('4. exit')
ch=input('enter your choice:')
if ch=='1':
sta... | true |
888537ae81ac1f0a4b2b1452d32bd86b004c610c | B001bu1at0r81/Home-Work | /Home_Work4/Home_Work4_Task_3.py | 664 | 4.125 | 4 | ###################################
#!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~!!!#
#!!!_______Orest Danysh________!!!#
#!!!________Home-work_4________!!!#
#!!!___________Task_3__________!!!#
#!!!_____Fibonacci_number______!!!#
#!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~!!!#
###################################
quantity_of_numbers = int(input(... | false |
9f34a088a4d0a61f2af65fa911222eb2d3372dd8 | mbramson/Euler | /python/problem016/problem016.py | 488 | 4.125 | 4 | # -*- coding: utf-8 -*-
## Power Sums
## 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
## What is the sum of the digits of the number 2**1000?
## This is actually a very simple problem in python, because Python automatically deals with large numbers.
## Returns the Power Sum of n. As in it sum... | true |
a4382447caa1d2c2e4bfd9ddedef88a7063bf943 | valerienierenberg/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 1,421 | 4.1875 | 4 | #!/usr/bin/python3
"""This module contains a function island_perimeter that returns
the perimeter of the island described in grid
"""
def island_perimeter(grid):
"""island_perimeter function
Args:
grid ([list of a list of ints]):
0 represents a water zone
1 represents a la... | true |
74a62d228dbd2ce456d09211bea6f15d822ca3f7 | James-E-Sullivan/BU-MET-CS300 | /sullivan_james_lab3.py | 2,052 | 4.25 | 4 | # Eliza300
# Intent: A list of helpful actions that a troubled person could take. Build 1
possible_actions = ['taking up yoga.', 'sleeping eight hours a night.',
'relaxing.', 'not working on weekends.',
'spending two hours a day with friends.']
'''
Precondition: possibl... | true |
91e5fa35bc4ea64c7cc65e096d10ed0d91d8d88b | bperard/PDX-Code-Guild | /python/lab04-grading.py | 320 | 4.125 | 4 | score = int(input('On a scale of 0-100, how well did you?'))
grade = ''
if score > 100:
grade = 'Overachiever'
elif score > 89:
grade = 'A'
elif score > 79:
grade = 'B'
elif score > 69:
grade = 'C'
elif score > 59:
grade = 'D'
elif score >= 0:
grade = 'F'
else:
grade = 'Leave'
print(grade)
| true |
21ab8c793589afe2c8f984db02ca2b5650be962b | bperard/PDX-Code-Guild | /python/lab08-roshambo.py | 1,309 | 4.25 | 4 | '''
Rock, paper, scissors against the computer
'''
import random
throws = ['rock', 'paper', 'scissors'] #comp choices
comp = random.choice(throws)
player = input('Think you can beat me in a game of Roshambo? I doubt it, but let\'s give it a shot.\n Choose your weapon: paper, rock, scissor.').lower() #player prompt
... | true |
75566c13a5e09874a1ea4ff64c7f198b7f4218fc | bperard/PDX-Code-Guild | /python/lab31-atm.py | 2,865 | 4.21875 | 4 | '''
lab 31 - automatic teller machine machine
'''
transactions = [] # list of deposit/withdraw transactions
class ATM: # atm class with rate and balance attribute defaults set
def __init__(self, balance = 0, rate = 0.1):
self.bal = balance
self.rat = rate
def __str__(self): # format w... | true |
e5a8eae58dc45a0259309b867eeac974b3dc7d62 | bperard/PDX-Code-Guild | /python/lab09-change.py | 838 | 4.25 | 4 | '''
Making change
'''
# declaring coin values
quarters = 25
dimes = 10
nickles = 5
pennies = 1
# user input, converted to float
change = float(input('Giving proper change is key to getting ahead in this crazy world.\n'
'How much money do you have? (for accurate results, use #.## format)'))
# conv... | true |
07de036683eeaf643caaa7e140c8959af82703e7 | RobertCochran/connect4 | /user_input.py | 1,148 | 4.25 | 4 | import random
def user_input():
""" This function allows the user to choose where their red piece goes. """
print "We're going to play Connect Four."
print " I'll be black and you'll be red. "
print "You go first and choose where you want to put your piece. There are seven columns in total."
... | true |
eb7cb4ffdec2e4c5790db0c1d1b407ed5b8a2930 | galgodon/astr-119-hw-1 | /operators.py | 1,641 | 4.5 | 4 | #!/usr/bin/env python3 # makes the terminal know this is in python
x = 9 #Set variables
y = 3
#Arithmetic Operators
print(x+y) # Addition
print(x-y) # Subtraction
print(x*y) # Multiplication
print(x/y) # Division
print(x%y) # Modulus (remainder)
print(x**y) # Exponentiation ... | true |
9bdfa82561a8638beb7caa171e52f717cc3bb89e | galgodon/astr-119-hw-1 | /functions.py | 1,209 | 4.1875 | 4 | #!/usr/bin/env python3
import numpy as np # import numpy and sys
import sys
def expo(x): # define a function named expo that needs one input x
return np.exp(x) # the function will return e^x
def show_expo(n): # define a subroutine (does not return ... | true |
3ad1a7fcb0a7b6d2c7ba0e1f639d396c6adf6fe7 | Peter-Moldenhauer/Python-For-Fun | /If Statements/main.py | 502 | 4.3125 | 4 | # Name: Peter Moldenhauer
# Date: 1/12/17
# Description: This program demonstrates if statements in Python - if, elif, else
# Example 1:
age = 12
if age < 21:
print("Too young to buy beer!")
# Example 2:
name = "Rachel"
if name is "Peter": # you can use the keword is to compare strings (and also numbers), it... | true |
b26499e29901a2733e78fc344d500378924488e6 | python-programming-1/homework-3-kmc89 | /HW3.py | 310 | 4.1875 | 4 | num = 0
try:
num_input = input('Enter a number: ')
except:
print('Invalid input!')
num = int(num_input)
def collatz(num):
if (num)%2 == 0:
col_num = int(num /2)
print(col_num)
return (col_num)
else:
col_num = num * 3 + 1
print(col_num)
return (col_num)
while num > 1:
num = collatz(num)
| false |
971e882b734c6217358ea3c384e58b0554206a3b | FA0AE/Mision-04 | /Triangulos.py | 1,519 | 4.3125 | 4 | #Francisco Ariel Arenas Enciso
#Determinación de un triángulo de acuerdo a la medida de sus lados
'''
Mediante el uso de operadores lógicos y relacionales, y de los datos enviados por "main()",
la función decide que tipo de triángulo es.
'''
def decidirTriangulo(lado1, lado2, lado3):
if lado1 == lado2 an... | false |
86148c0044b69aea97ee2609548116160898a6bb | Douglas1688/Practices | /operaciones_matematicas/calculos_generales.py | 549 | 4.1875 | 4 | """Este módulo permite realizar operaciones matemáticas"""
def sumar(x,y):
print("El resultado de la suma es: ",x+y)
def restar(x,y):
print("El resultado de la suma es: ",x-y)
def multiplicar(x,y):
print("El resultado de la suma es: ",x*y)
def dividir(x,y):
print("El resultado de la suma es: ",x//y)
def... | false |
bda62fab31e84c7569144db7354b0072603f52b4 | seashore001x/PythonDataStructure | /BinarySearchTree.py | 1,514 | 4.21875 | 4 | class BinaryTree:
def __init__(self):
self.tree = EmptyNode()
def __repr__(self):
return repr(self.tree)
def lookup(self, value):
return self.tree.lookup(value)
def insert(self, value):
self.tree = self.tree.insert(value)
class EmptyNode:
def __repr__(self):
... | false |
df41b52417f3f769d2e6bfe452a76c7e9a67d886 | su6i/masterIpsSemester1 | /HMIN113M - Système/tp's/factoriel.py | 316 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf8 -*-
import sys, os
os.system("clear")
r=1
if len(sys.argv) == 2:
n = int(sys.argv[1])
if n<0:
print("Please enter a number superior than 2")
elif n<2 and n>0:
print(n,"!= 1")
else:
while n >= 2:
r *=n
n -=1
print(sys.argv[1]+"! = ",r)
| false |
26cdf3876507195bf2db3deb50b2bee7eb316483 | JatinBumbra/neural-networks | /2_neuron_layer.py | 1,059 | 4.15625 | 4 | '''
SIMPLE NEURON LAYER:
This example is a demonstration of a single neuron layer composed of 3 neurons. Each neuron has it's own weights that it
assigns to its inputs, and the neuron itself has a bias. Based on these values, each neuron operates on the input vector
and produces the output.
The be... | true |
8eb8573aacab9bc276179414ebd75e4cf664cf47 | sankalp-sheth/FSDP2019 | /day3/weeks.py | 252 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 13 13:22:14 2019
@author: KIIT
"""
week_days=('Monday', 'Wednesday', 'Thursday', 'Saturday')
new_days=(week_days[0],)+("Tuesday",)+week_days[1:3]+("Friday",)+(week_days[-1],)+("Sunday",)
print(new_days)
| false |
12284512b8af388e4ed161a00fea411dfead3100 | sakura-fly/learnpyqt | /src/布局/绝对定位.py | 1,054 | 4.21875 | 4 | """
程序指定了组件的位置并且每个组件的大小用像素作为单位来丈量。当你使用了绝对定位,我们需要知道下面的几点限制:
如果我们改变了窗口大小,组件的位置和大小并不会发生改变。
在不同平台上,应用的外观可能不同
改变我们应用中的字体的话可能会把应用弄得一团糟。
如果我们决定改变我们的布局,我们必须完全重写我们的布局,这样非常乏味和浪费时间。
"""
import sys
from PyQt5.QtWidgets import QWidget, QLabel, QApplication
class Example(QWidget):
def __init__(self):
super().__init_... | false |
144e54ba2157096c8d6e9076129d00022ad1bd93 | Dgustavino/Taller_01-Python | /python_1.py | 1,103 | 4.59375 | 5 | """ EJERCIO 1:
EJERCIO 2:
"""
lista_nombres = [
'nombre1', # this is list
'nombre2' ]
lista_apellidos = ('apell1',
'apell2') # this is tuplet
# imprimo los ejemplos de la parte superior
print(lista_nombres)
print(lista_apellidos)
# ejemplos de la estructurada de datos set()
set1 = {12345... | false |
0823b6486c60bccbed17ff96778b88ec46a3d113 | ScoltBr/PythonProjetos | /escopo_de_variaveis.py | 990 | 4.40625 | 4 | """
Escopo de variavel
Dois casos de escopo:
1 - Variáveis globais:
- Variáveis globais são reconhecidas, ou seja, seu escopos compreendem, todo a o programa.
2 - Variáveis locais:
- Variáveis locais ~soa reconhecidas apenas no bloco onde foram declarades, ou seja, seu escopo
esta limitado ao seu bloco on... | false |
8034b3dcc454c0570bbf301ed92a7d9ee3100260 | ScoltBr/PythonProjetos | /tipo_float.py | 726 | 4.125 | 4 | """"
Tipo float
Tipo real, dicimal
Casas decimais
OBS: o separados de casas de cimais na programação é o ponto e não a virgula. [1.5F,0.9F,1.123F]
"""
# Errado do ponto de vista do Float, mas gera uma tupla
from builtins import int
valor = 1, 44 ... | false |
d8fb565e7a39ebb7a200514407b2ffb49e07b19d | adharmad/project-euler | /python/commonutils.py | 2,794 | 4.34375 | 4 | import functools
from math import sqrt
@functools.lru_cache(maxsize=128, typed=False)
def isPrime(n):
"""
Checks if the number is prime
"""
# Return false if numbers are less than 2
if n < 2:
return False
# 2 is smallest prime
if n == 2:
return True
# All even numbers ... | true |
97fee167a426b404694914d45e69b493b6f07a72 | patrebert/pynet_cert | /class9/ex8/mytest/world.py | 885 | 4.15625 | 4 | #!/bin/env python
def func3():
print "world.py func3"
class MyClass:
def __init__(self,arg1, arg2, arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
def hello(self):
print "hello"
print " %s %s %s" %(self.arg1, self.arg2, self.arg3)
def not_hello(self... | false |
96de7caab2ee2c486df92f38a6b207376173bc01 | jackyxugz/myshop | /coupons/tests.py | 814 | 4.28125 | 4 | class Cat:
"""定义一个猫类"""
def __init__(self, new_name, new_age):
"""在创建完对象之后 会自动调用, 它完成对象的初始化的功能"""
self.name = new_name
self.age = new_age # 它是一个对象中的属性,在对象中存储,即只要这个对象还存在,那么这个变量就可以使用
def __str__(self):
"""返回一个对象的描述信息"""
return "名字是:%s , 年龄是:%d" % (self.name, self.age... | false |
779d06833f0b30281c71242196a77f9ff08ce094 | abhay-rana/python-tutorials. | /DATA STRUCTURE AND ALGORITHMS/INSERRTION_ SORT.py | 397 | 4.15625 | 4 | #INSERTION SORT IS SIMILAR TO E WE PLAYING CARDS
# THE WAY WE SORT THE CARDS
def insertion_sort(arr):
for e in range(1,len(arr)):
temp=arr[e]
j=e-1
while j>=0 and temp<arr[j]:
arr[j+1]=arr[j] # we are forwarding the elements
j=j-1
else:
arr[j... | true |
6cc03c6e49891cacfa4ff2824caf9718994e1811 | Avinint/Python_musicfiles | /timeitchallenge.py | 1,006 | 4.375 | 4 | # In the section on Functions, we looked at 2 different ways to calculate the factorial
# of a number. We used an iterative approach, and also used a recursive function.
#
# This challenge is to use the timeit module to see which performs better.
#
# The two functions appear below.
#
# Hint: change the number of itera... | true |
f348334cc86f5d86e66be05fa2aaaab5da2460c6 | cyrus-raitava/SOFTENG_364 | /ASSIGNMENT_2/SOLUTIONS/checksum.py | 1,406 | 4.125 | 4 | # -*- coding: utf-8 -*-
def hextet_complement(num):
'''
Internet Checksum of a bytes array.
Further reading:
1. https://tools.ietf.org/html/rfc1071
2. http://www.netfor2.com/checksum.html
'''
# Create bitmask to help calculate one's complement
mask = 0xffff
# Use th... | true |
cfd0d212f68d0be4b2caca1cf3df6c5a7ce645c5 | toasterbob/review | /Object_Oriented/polymorphism.py | 1,195 | 4.1875 | 4 | # Polymorphism
class Animal:
name = ""
location = ""
def __init__(self, name, location):
self.name = name
self.location = location
def talk(self):
pass
def move(self):
pass
def breathe(self):
pass
class Bird(Animal):
def talk(self):
print... | false |
82b50126fd52145f1d863a61ca57c592bf13b297 | carlosflrslpfi/CS2-A | /class-08/scope.py | 1,521 | 4.21875 | 4 | # Global and local scope
# The place where the binding of a variable is valid.
# Global variable that can be seen and used everywhere in your program
# Local variable that is only seen/used locally.
# Local analogous to within a function.
# we define a global variable x
x = 5
def some_function():
x = 10 # local v... | true |
1f561cbd24991690d041d444eae5cc96a110e06d | bronyamcgrory1998/Variables | /Class Excercises 5.py | 724 | 4.21875 | 4 | #Bronya McGrory
#22/09/2014
#Both a fridge and a lift have heights, widths and depths. Work out how much space is left in the lift once the fridge
fridgeheight= int (input("fridge height"))
fridgewidth= int (input("fridge width"))
fridgedepth= int (input("fridge depth"))
volume_of_fridge_answer= fridgeheigh... | true |
2d8881cef624299204688eee1fbe091c8f32fab0 | mariia-iureva/code_in_place | /group_coding_sections/Section2/8ball.py | 991 | 4.375 | 4 | """
Simulates a magic eight ball.
Prompts the user to type a yes or no question and gives
a random answer from a set of prefabricated responses.
"""
import random
# make a bunch of random answers
ANSWER_1 = "Ask again later."
ANSWER_2 = "No way."
ANSWER_3 = "Without a doubt."
ANSWER_4 = "Yes."
ANSWER_5 = "Possibly."
d... | true |
009c1adc7155346cdebdf136237a9f00d6a4b4a5 | Ace139/PythonAlgorithms | /pysort.py | 1,942 | 4.125 | 4 | __author__ = 'ace139'
__email__ = 'soumyodey@live.com'
"""
This program is implementation of different sorting algorithms,
also could be imported as a module in other programs.
"""
def insertion_sort(arr):
for p in range(1, len(arr)):
key = arr[p]
c = p - 1
while c >= 0 and arr[c] > key:
... | false |
410cd4eae846e5f36fdf76230a5e64afd7cfaa81 | qcymkxyc/JZoffer | /main/question51/book1.py | 1,438 | 4.40625 | 4 | #!/usr/bin/env python
# _*_coding:utf-8_*_
"""
@Time : 19-1-30 上午10:49
@Author: qcymkxyc
@File: book1.py
@Software: PyCharm
"""
def _merge(nums1, nums2):
"""合并两个数组
:param nums1: List[int]
数组一
:param nums2: List[int]
数组二
:return: List[int], int
合并数组, ... | false |
a57612a005864e361ebf18274fc62a76f97618d1 | duonglong/practice | /magicalRoom.py | 2,880 | 4.15625 | 4 | # --*-- coding: utf-8 --*--
"""
You're an adventurer, and today you're exploring a big castle.
When you came in, you found a note on the wall of the room.
The note said that the castle contains n rooms, all of which are magical.
The ith room contains exactly one door which leads to another room roomsi.
Because the room... | true |
1cd204b6f3b4a171e9625b8d2a3db9c04e472b84 | duonglong/practice | /acode.py | 2,098 | 4.25 | 4 | """
Alice and Bob need to send secret messages to each other and are discussing ways to encode their messages:
Alice: 'Let's just use a very simple code: We'll assign 'A' the code word 1, 'B' will be 2, and so on down to 'Z' being assigned 26.'
Bob: 'That's a stupid code, Alice. Suppose I send you the word 'BEAN' enco... | true |
b3fbacf8e7c5a5fd61a833c04a2b4e87899dc127 | KRiteshchowdary/myfiles | /Calculator.py | 394 | 4.15625 | 4 | a = float(input('number 1 is '))
function = input('desired function is ')
b = float(input('number 2 is '))
if (function == '+'):
print(a + b)
elif (function == '-'):
print(a - b)
elif (function == '*'):
print(a*b)
elif (function == '/' and b != 0):
print(a/b)
elif (function == '/' and b==0):
print... | true |
0ee672d520f8a915f269215ac12d78738e46ed33 | bilun167/FunProjects | /CreditCardValidator/credit_card_validator.py | 1,036 | 4.1875 | 4 | """
This program uses Luhn Algorithm (http://en.wikipedia.org/wiki/Luhn_algorithm) and works with most credit card numbers.
1. From the rightmost digit, which is the check digit, moving left, double the value of every second digit.
2. If the result is greater than 9 (e.g., 7 * 2 = 14), then sum the digits of it (e.g... | true |
de4352cd7d651055e3204be3f1c06dfb4ba75d83 | DarlanNoetzold/P-versus-NP | /P versus NP.py | 2,233 | 4.15625 | 4 | # Simulação de tempo que o computador que está executando o programa
# levaria para calcular algumas rotas para o caixeiro viajante sem
# utilizar Otimização Combinatória
import time
# Calcula o tempo que o processador da máquina leva para fazer 10 milhões
# de adições, cada edição é o calculo de um caminho (li... | false |
8153b4cfc2169b781bc16d1ad06e2ca4233b3ea9 | osagieomigie/foodWebs | /formatList.py | 1,572 | 4.21875 | 4 | ## Format a list of items so that they are comma separated and "and" appears
# before the last item.
# Parameters:
# data: the list of items to format
# Returns: A string containing the items from data with nice formatting
def formatList(data):
# Handle the case where the list is empty
if len(data) == ... | true |
d87ae28da2b3a113e2891241fddd47595525417f | margueriteblair/Intro-To-Python | /more-loops.py | 1,001 | 4.125 | 4 | #counting in a loop,
zork = 0
print('Before', zork)
for thing in [9, 42,12, 3, 74, 15]:
zork = zork+1
print(zork, thing)
print('After', zork)
count = 0
sum = 0
print('Before', count, sum)
for value in [9, 42,12, 3, 74, 15]:
count = count + 1
sum = sum + value
print(count, sum, value)
print('After... | true |
c3bce9a9f83075deeb2e20c609676b26e669840e | murffious/pythonclass-cornell | /coursework/working-with-data-file/samples/unit4/convert.py | 956 | 4.15625 | 4 | """
Module showing the (primitive) way to convert types in a CSV files.
When reading a CSV file, all entries of the 2d list will be strings, even if you
originally entered them as numbers in Excel. That is because CSV files (unlike
JSON) do not contain type information.
Author: Walker M. White
Date: June 7, 2019
"... | true |
30be17d0390482768e1351980180136f55087a9e | murffious/pythonclass-cornell | /coursework/programming-with-objects/exercise2/funcs.py | 1,793 | 4.15625 | 4 | """
Module demonstrating how to write functions with objects.
This module contains two versions of the same function. One version returns a new
value, while other modifies one of the arguments to contain the new value.
Author: Paul Murff
Date: Feb 6 2020
"""
import clock
def add_time1(time1, time2):
"""
Re... | true |
5aa45d78764eb9ca62abc1f4d6bfd82b7056d90d | ellafrimer/shecodes | /lists/helper.py | 549 | 4.46875 | 4 | print("Accessing just the elements")
for letter in ['a', 'b', 'c']:
print(letter)
print("Accessing the elements and their position in the collection")
for (index, letter) in enumerate(['a', 'b', 'c']):
print("[%d] %s" % (index, letter))
print("A string is also a collection...")
for (index, letter) in enumerat... | true |
2883dec0109abec67805f361b8bc7c8748b70a7f | ellafrimer/shecodes | /loops/geometric_shape.py | 282 | 4.1875 | 4 | """
making a triangle
"""
def print_asterisks(num):
print("*" * num)
# for number in range(1, 6):
# print_asterisks(number)
"""
making a trapeze
"""
a_number = 8
for number in range(int(a_number/2), a_number+1):
print_asterisks(number)
"""
making a diamond
"""
| false |
6276c03f5933147d623376818f96cfa35f07f8e8 | shahamran/intro2cs-2015 | /ex3/findLargest.py | 410 | 4.46875 | 4 | #a range for the loop
riders=range(int(input("Enter the number of riders:")))
high_hat=0
gandalf_pos=0
#This is the loop that goes through every hat size and
#checks which is the largest.
for rider in riders:
height=float(input("How tall is the hat?"))
if height>high_hat:
high_hat=height
ganda... | true |
8552969c9e3f4e2764951ac3914572d1b9744a36 | Lumexralph/python-algorithm-datastructures | /trees/binary_tree.py | 1,471 | 4.28125 | 4 | from tree import Tree
class BinaryTree(Tree):
"""Abstract base class representing a binary tree structure."""
# additional abstract methods
def left_child(self, p):
"""Return a Position representing p's left child.
Return None if p does not have a left child
"""
raise Not... | true |
caf308fc4385c102d25e0dd35bd132017822a166 | Kevinvanegas19/lps_compsci | /misc/calculateDonuts.py | 360 | 4.15625 | 4 | print("How many people are coming to the party?")
people = int(raw_input())
print("How many donuts will you have at your party?")
donuts = int(raw_input())
donuts_per_person = donuts / people
print("Our party has " + str(people) + " people and " + str(donuts) + " donuts.")
print("Each person at the party gets "... | false |
bf12f927c2d684699f41b48c1191ea956205a41c | km-aero/eng-54-python-basics | /exercise_103.py | 433 | 4.3125 | 4 | # Define the following variables
# name, last_name, species, eye_color, hair_color
# name = 'Lana'
name = 'Kevin'
last_name = 'Monteiro'
species = 'Alien'
eye_colour = 'blue'
hair_colour = 'brown'
# Prompt user for input and Re-assign these
name = input('What new name would you like?')
# Print them back to the user ... | true |
f693e45eab8cfcc4ab449149fcba829e8e4f0b02 | khadtareb/class_assignments1 | /pythonProject6/Assignment_62.py | 351 | 4.1875 | 4 | #62. Python | Ways to remove a key from dictionary Ways to sort list of dictionaries by values in
d=[{ "name" : "Nandini", "age" : 22},
{ "name" : "Manjeet", "age" : 20 },
{ "name" : "Nikhil" , "age" : 19 }]
print(sorted(d,key=lambda i:i['age']))
print(sorted(d,key=lambda i:i['age'],reverse=True))
print(sorted(d,key=... | false |
1736fa54bb0aa30ff931ced7e8fc61c104a3aa5d | CheshireCat12/hackerrank | /eulerproject/problem006.py | 544 | 4.21875 | 4 | #!/bin/python3
def square_of_sum(n):
"""Compute the square of the sum of the n first natural numbers."""
return (n*(n+1)//2)**2
def sum_of_squares(n):
"""Compute the sum of squares of the n first natural numbers."""
return n*(n+1)*(2*n+1)//6
def absolute_diff(n):
"""
Compute the absolute d... | true |
dd5140fad8067d9c49215aa6a3600281770c22ff | marsdev26/python_exercises | /hello_turtle.py | 1,085 | 4.28125 | 4 | import turtle
#Function to draw 1 petal of a flower
def draw_petal():
turtle.down()
turtle.forward(30)
turtle.right(45)
turtle.forward(30)
turtle.right(135)
turtle.forward(30)
turtle.right(45)
turtle.forward(30)
turtle.right(135)
#Function to draw a flower
def draw_flower():
... | false |
99e02fa63b997cb3156d5427da3833584a99d3c3 | stogaja/python-by-mosh | /12logicalOperators.py | 534 | 4.15625 | 4 | # logical and operator
has_high_income = True
has_good_credit = True
if has_high_income and has_good_credit:
print('Eligible for loan.')
# logical or operator
high_income = False
good_credit = True
if high_income or good_credit:
print('Eligible for a loan.')
# logical NOT operator
is_good_credit = True
c... | true |
fa537f900f5a5f23c8573e1965895df2dd3b3706 | jhreinholdt/caesar-cipher | /ceasar_cipher.py | 1,693 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 21 15:33:33 2017
@author: jhreinholdt
Caesar cipher - Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25. This cipher rotates the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th nex... | true |
fd5d0602a635cc7f492c76ed2df9548da2ec29dc | madhuriagrawal/python_assignment | /swapTwoNumbers.py | 231 | 4.25 | 4 | def swapingUsingThirdVariable():
x=2
y=6
z=x
x=y
y=z
print(x,y)
def swapingWithoutThirdVariable():
x = 2
y = 6
x,y=y,x
print(x,y)
swapingUsingThirdVariable()
swapingWithoutThirdVariable()
| false |
58185c8ed1fbceae5dbb44fc547712f101f17e21 | Meenal-goel/assignment_7 | /fun.py | 2,238 | 4.28125 | 4 | #FUNCTIONS AND RECURSION IN PYTHON
#1.Create a function to calculate the area of a circle by taking radius from user.
rad = float(input("enter the radius:"))
def area_circle (r):
res = (3.14*pow(r,2))
print("the area of the circle is %0.2f"%(res) )
area_circle(rad)
print("\n")
#Write a function “perfect()” t... | true |
833994a2e77655b22525d4cf4e8d3d3a6ab93cc4 | JustineRobert/TITech-Africa | /Program to Calculate the Average of Numbers in a Given List.py | 284 | 4.15625 | 4 | n = int(input("Enter the number of elements to be inserted: "))
a =[]
for i in range(0,n):
elem = int(input("Enter the element: "))
a.append(elem)
avg = sum(a)/n
print("The average of the elements in the list", round(avg, 2))
input("Press Enter to Exit!")
| true |
6f6baad65328395fc7a61d1dbf7f0e981ff9ec9a | caoxiang104/DataStructuresOfPython | /Chapter3_Searching_Sorting_and_Complexity_Analysis/example4.py | 745 | 4.21875 | 4 | # coding=utf-8
"""
expo函数的一个可替代的策略是,使用如下的递归定义:
expo(number, exponent)
=1, 当exponent=0
=number*expo(number, exponent-1) 当exponent是基数的时候
=(expo(number,exponent/2))^2, 当exponent是偶数的时候
使用这一策略定义一个递归的expo函数,并且使用大O表示法表示其复杂度。
"""
# O(nlogn)
def expo(number, exponent):
if exponent == 0:
return 1
elif exponent ... | false |
787f852dd458b854945dd7e5fc9da154c0f3351d | caoxiang104/DataStructuresOfPython | /Chapter11_Sets_and_Dicts/item.py | 614 | 4.125 | 4 | class Item(object):
"""Represents a dictionary item."""
def __init__(self, key, value):
self.key = key
self.value = value
def __str__(self):
return str(self.key) + ":" + str(self.value)
def __eq__(self, other):
if type(self) != type(other):
return False
... | false |
c9edd541c68a693e72eb35e48e24701e862a23a4 | IfWell/MSG-Algorithm | /p1-3.py | 464 | 4.1875 | 4 | #문제(1) ppt의 문제 3번
# """로 둘러싸인 코드들은 없는 걸로 처리됨. 지우고 사용할 것
#for을 이용한 풀이
"""
for i in range(1, 10):
for j in range(1, 10):
print("{0} x {1} = {2}".format(i, j, i*j))
"""
#while을 이용한 풀이
"""
i,j = 1,1
while(i <= 9):
j = 1 #j를 다시 1로 초기화
while(j <= 9):
print("{0} x {1} = {2}"... | false |
4dbd156acd668c70d2c6b1426c9a80a2843dbfdc | Struggling10000/try | /Hw_1.py | 525 | 4.125 | 4 | import string
'''
题目:有这么一串字符串 str = “my Name is alex”想要将每一个单词首字母大写,其他不变str = “My Name Is Alex”
'''
s = 'my Name is alex.'
print('原字符串:s='+s)
print('直接调用函数结果:'+string.capwords(s))
s1=s.split(' ')
print('切分后的字符串列表是:')
print(s1)
def normallize(name):
return name.capitalize()
s2=list(map(normallize,s1))
print('处理后的列表是:')
... | false |
597653d108f0c38033a862126f529a959c0afd2d | OlegMeleshin/Lubanovic-Exercises | /Chapter 3/Chapter_3_part_4.py | 836 | 4.5 | 4 | # 10. Create an English-French dictionary called "e2f" and print it.
# Here are your words: dog/chien, cat/chat and walrus/morse.
e2f = {'dog' : 'chien', 'cat' : 'chat', 'walrus' : 'morse'}
print(f'''English to French Dictionary
{e2f}\n''')
# 11. Print french for walrus using your dictionary.
print(f"Fr... | false |
0f498dc435ba20d7cace60400c5439d12a0546e4 | OlegMeleshin/Lubanovic-Exercises | /Chapter_4/Chapter_4_part_6.py | 270 | 4.28125 | 4 | '''6. Use Set comprehension to create the 'odd' set containing even numbers in range(10).
Так и написано ODD, в котором ЧЕТНЫЕ числа. Опечатка возможно.'''
odd = {even for even in range(10) if even % 2 == 0}
print(odd)
| false |
5f5106c85c99ffa303151c793d5d490844b92977 | rajatsachdeva/Python_Programming | /UpandRunningwithPython/Working with files/OS_path_utilities.py | 1,241 | 4.125 | 4 | #
# Python provides utilities to find if a path is file or directory
# whether a file exists or not
#
# Import OS module
import os
from os import path
from datetime import date, time , datetime
import time
def main():
# print the name of os
print "Os name is " + os.name
# Check for item existence ... | true |
f848e3d507aaad9c30b0042a17542dc6225e5945 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/04 Syntax/object.py | 921 | 4.25 | 4 | #!/bin/python3
# python is fundamentally an object oriented language
# In python 3 everything is an object
# class is a blueprint of an object
# encapsulation of variables and methods
class Egg:
# define a constructor
# with special name __init__
# All methods within classes have first argument as self
... | true |
377c78d18db40dd93bd16b65a9a1a4547c508216 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/16 Databases/databases.py | 896 | 4.3125 | 4 | #!/usr/bin/python3
# Databases in python
# Database used here is SQLite 3
# row factory in sqlite3
import sqlite3
def main():
# Connects to database and creates the actual db file if not exits already
db = sqlite3.connect('test.db')
# Interact with the database
db.execute('drop table if exi... | true |
33d9a7cc53d070f8575fa5b3b044edd4eb5e9fe4 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/12 Classes/generator.py | 1,218 | 4.46875 | 4 | #!/usr/bin/python3
# A generator object is an object that can be used in the context of an iterable
# like in for loop
# Create own range object with inclusive range
class inclusive_range:
def __init__(self, *args):
numargs = len(args)
if numargs < 1 :
raise TypeError('Requries at lea... | true |
b572c312a1314e7048b1f596650a724d215b0a63 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/11 Functions/generator.py | 1,290 | 4.125 | 4 | #!/usr/bin/python3
# Generator functions
def main():
for i in inclusive_range(0, 10):
print(i, end = ' ')
print()
for i in inclusive_range2(18):
print(i, end = ' ')
print()
for i in inclusive_range2(0, 25):
print(i, end = ' ')
print()
for i in inclusive_range2(0, 50... | false |
d2d7d34fa745243c91ab891f0fdd3e28ba8b16d0 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/14 Containers/dictionary.py | 1,397 | 4.28125 | 4 | #!/usr/bin/python3
# Organizing data with dictionaries
def main():
d1 = {'one' : 1, 'two' : 2, 'three' : 3}
print(d1, type(d1))
# dictionary using dict constructor
d2 = dict(one = 1, two = 2, three = 3)
print(d2, type(d2))
d3 = dict(four = 4, five = 5, six = 6)
print(d3, type(d3... | true |
f33362d646b39360d8bdc20d346a369fdf7d6a19 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/05 Variables/Finding_type_identity.py | 1,300 | 4.3125 | 4 | #!/bin/python3
# Finding the type and identity of a variable
# Everything is object and each object has an ID which is unique
def main():
print("Main Starts !")
x = 42
print("x:",x)
print("id of x:",id(x))
print("id of 42:",id(42))
print("type of x:", type(x))
print("type of 42:", type(4... | true |
20a46b2b8f01f34c9cced37bd810309cf4808858 | lucioeduardo/cc-ufal | /APC/Listas/02 - Estruturas de Decisão/q6.py | 783 | 4.125 | 4 | """
Escreva um algoritmo que recebe três valores para os lados de um
triângulo (a,b e c) e decide se a forma geométrica é um triângulo ou não e em
caso positivo, classifique em isósceles, escaleno ou equilátero.
– O valor de cada lado deve ser menor que' a soma dos outros dois
– Isósceles: dois lados iguais e um difere... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.