blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0bbd2ccf66e4e1a33d41ad0e1c96bd1e2bc2044c | rohansharma777/Python_Assignments | /Assignment_1/prog1.py | 220 | 4.1875 | 4 | length=int(input("Enter length of the rectangle.: "))
breadth=int(input("Enter the breadth of rectangle.: "))
print("Area = ",length*breadth)
if length==breadth:
print("Voila ! The rectangle turned out to be a square") | true |
a003c4b9b3af81122a59ca84db3ec0313e96fa82 | trinbar/coding-challenges | /Arrays-Lists-Hashmaps/reverse_words.py | 795 | 4.5625 | 5 | """
Your team is scrambling to decipher a recent message, worried it's a plot to
break into a major European National Cake Vault. The message has been mostly
deciphered, but all the words are backward! Your colleagues have handed off the
last step to you.
Write a function reverse_words() that takes a message as a list of characters
and reverses the order of the words in place. ↴
"""
def reverse_words(lst):
"""Returns a string that reverses the order of words in a list of chars."""
#Create empty string
temp_str = ""
#Iterate through lst, pop off the first item and add to temp_str
while len(lst) != 0:
temp_str += lst.pop(0)
#Split temp_str, reverse it, then join as one string
return " ".join(temp_str.split()[::-1])
#Runtime O(n)
| true |
0ab4f79aa27f74ea5566b6b30803fc0d0ed59314 | Gor-Ren/firecode.io | /src/python/level_1/flip_vertical_axis.py | 547 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 5 17:25:05 2017
@author: Gor-Ren
"""
def flip_vertical_axis(matrix):
"""Flips a matrix across the vertical axis.
A matrix in the form of a list of lists, where each sublist represents a row
is flipped across its vertical centre line.
Args:
matrix: A list of m lists. Each sublist contains n values such that it
represents an m x n matrix.
Returns:
None; the input list is mutated in-place.
"""
for row in matrix:
row = row[::-1]
| true |
3fb5016f0e77f75183d13e44165b51a2b6180061 | Gor-Ren/firecode.io | /src/python/level_3/excel_column_name_to_number.py | 2,202 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 16 17:27:33 2017
@author: Gor-Ren
"""
def excel_column_name_to_number(column_title):
"""Translate an Excel column reference from letter(s) to a number.
Excel column references may be expressed as letters, e.g. 'A', 'D', 'AZ'.
These have a corresponding numerical reference. This function takes an
input alphabetical reference and returns the numerical reference as an int.
For example: 'A' -> 1, 'D' -> 4, 'AZ' -> 51
Args:
column_title: A string containing uppercase latin alphabet characters.
Returns:
An integer, the corresponding numerical column reference.
"""
def char_to_num(letter):
"""Helper. Translates uppercase char into its position in alphabet."""
return ord(letter) - ord('A') + 1
# the input string is essentially a base 26 value to be decoded to decimal
base = 26
power = 0
column_num = 0
for char in reversed(column_title): # reverse to handle little-endian format
column_num += char_to_num(char)*base**power
power += 1
return column_num
## Previous solution (longer due to using own code instead of ord() function)
def excel_column_name_to_number2(column_title):
"""Translate an Excel column reference from letter(s) to a number.
Excel references may be expressed as letters, e.g. 'A', 'D', 'AZ'. These
columns have a corresponding numerical reference. This function takes an
input alphabetical reference and returns the numerical reference as an int.
For example: 'A' -> 1, 'D' -> 4, 'AZ' -> 51
Args:
column_title: A string containing uppercase latin alphabet characters.
Returns:
An integer, the corresponding numerical column reference.
"""
import string
char_map = {}
for num, char in enumerate(string.ascii_uppercase):
char_map[char] = num+1
# the input string is essentially a base 26 value to be decoded to decimal
column_num = 0
base = 26
power = 0
for char in reversed(column_title): # reverse to handle little-endian format
column_num += char_map[char]*base**power
power += 1
return column_num | true |
02f6857e57fb6f179c8d27752c9509a467306825 | ewong8/ewong8.github.io | /Assignments/Assignment 2/cis122-assign02-pythagorean.py | 1,048 | 4.53125 | 5 | '''
CIS 122 Summer 2020 Assignment 2
Author: Ethan Wong
Description: Defining a function to use the Pythagorean Theorem
References: https://www.rapidtables.com/calc/math/pythagorean-calculator.html;
http://mathforum.org/dr.math/faq/faq.pythagorean.html;
https://docs.python.org/3/library/math.html
'''
# Question 1
# Import Math module
import math
# Calculate the missing side "c"
def calc_side_c(a, b):
# Use math.sqrt to solve for C (taking sqrt of the sum of sqaures of a & b)
c = math.sqrt(math.pow(a, 2) + math.pow(b, 2))
# Return the result of c, rounding value to the nearest hundreths
return round(c, 2)
# Test function
c = calc_side_c(5, 10)
print("c =", c)
# Calculate the missing side a or b
def calc_side_ab(ab, c):
# Let x be the missing side (a or b) and solve for x using pythagorean theorem
x = math.sqrt(math.pow(c, 2) - math.pow(ab, 2))
# Return the result and round to the nearest hundreth
return round(x, 2)
# Test function
x = calc_side_ab(4, 8)
print("a/b =", x)
| true |
bf98bb43200c617963007656c9a184eb39052fac | natemccoy/pyintro | /simplemodule.py | 1,714 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This is a simple module example. It has a few functions and some data.
You can import this module if you are in the same directory by doing:
import simplemodule
The functions and data variables declared in this file can then be used by
typing:
simplemodule.FUNCTIONNAME()
simplemodule.VARIABLENAME
where FUNCTIONNAME and VARIABLENAME are replaced by the respective function
and variable names that you are interested in using.
If you want to know what functions or variables are available, look in the
respective FUNCTIONS and DATA sections by caling help(simplemodule)
"""
simplestring = "This is a string. It can be used in your module. Just import it"
def printhello():
'''
prints the string "hello
'''
print("Hello")
def returnhello():
'''
returns the string "hello"
'''
return "Hello"
def printsimplestring():
'''
prints the simplestring variable
'''
print(simplestring)
def returnsimplestring():
'''
returns the simplestring variable
'''
return simplestring
def returnsentences():
'''
returns a list of sentences split() from the simplestring variable
each sentence in the list of sentences is a string.
'''
# split simple string on the period/full stop
sentences = simplestring.split('. ')
return sentences
def generatesentences():
'''
returns a generator. the generator yields a sentence.
the sentence was split() from the simplestring variable
'''
# split simple string on the period/full stop
sentences = simplestring.split('. ')
for sentence in sentences:
yield sentence
| true |
9d1ee27a62cf1d1054016c5fad6a03d633f692f8 | wduncan21/Challenges | /leetcode/algo/647. Palindromic Substrings.py | 960 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 9 22:54:12 2017
@author: Mr.Wang
Given a string, your task is to count how many palindromic substrings in this
string.
The substrings with different start indexes or end indexes are counted as
different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Note:
The input string length won't exceed 1000.
"""
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
result=0
for length in range(1,len(s)+1):
for start in range(len(s)+1-length):
sub_s=s[start:start+length]
#if sub_s not in result:
if sub_s==sub_s[::-1]:
result+=1
return result | true |
2105fba30872c0d1526e936ca9930752978d3438 | Mansi149/Python | /43 Radio.py | 1,631 | 4.25 | 4 | """
PROBLEM 43
Write a program to print the output of the following poblem statement :-
Characteristics | Functionality
---------------------------------------
color |
brand |
ACPower |
headphone |
|
power_led | power_switch ( ON / OFF)
mode_led | mode_switch ( AM / FM )
frequency | band_tuner ( 88 - 108 )
volume | volume_tuner ( 1 - 10 )
---------------------------------------
Go to the market and buy a new Radio
Switch ON the radio
Set the mode to FM
Set the frequency to 102.2
Set the volume to 8
Listen to your song
Switch OFF the radio
Destroy the Radio ?
"""
class radio:
color = "Black"
brand = "Boat"
ACPower = False
headphone = True
def __init__(self):
self.power_led = None
self.mode_led = None
self.frequency = 0.0
self.volume = 0
print("Play Your Radio")
def power_switch(self,power_status):
self.power_led=power_status
print("Radio is : "+power_status)
def mode_switch(self,mode_status):
self.mode_led=mode_status
print("Radio Mode is set : "+mode_status)
def band_tuner(self,freq):
self.frequency=freq
print("Radio frequency is set at : ",freq)
def volume_tuner(self,vol):
self.volume=vol
print("Volume set at : ",vol)
national_radio=radio()
national_radio.power_switch("ON")
national_radio.mode_switch("FM")
national_radio.band_tuner(93.8)
national_radio.volume_tuner(100) | true |
265467a34a8798b1c02127c5f74c07fa2729e3d0 | webclinic017/New-Osama-Python | /Completed code/Education fees.py | 1,837 | 4.125 | 4 | """
A program for calculating the total amount deposited in the bank to cover the school
expenses completely throughout the school years, and the remainder is zero after the end of the
school years
"""
# (ver 1) account money and check it (12-2-2020 by Osama)
n1 = int(input('What is the value of the annual school expenses:'))
n2 = int(input('How many years will you spend in school:'))
n3 = float(input('What is the value of the annual bank interest:'))
def check(test):
for _ in range(0, n2):
test = test - n1
for _ in range(0, 12):
test += (test * (n3 / 1200))
print('Pound differences:', int(test))
total_amount = []
for start in range(1, 1000000): # It tests numbers until it reaches the required verification value
remaining_amount = int(start)
for a in range(0, n2):
remaining_amount = remaining_amount - n1 # Deduction of the value of the first annual premium
for _ in range(0, 12):
remaining_amount += (remaining_amount * (n3 / (12 * 100)))
# Calculating the monthly interest value on the deposited amount, noting that the annual interest has
# been divided by the number of months of the year (12)
if -20 < int(remaining_amount) < 20:
# The remainder in the bank allowed after the end of the school years is from -20 to 20 Egyptian Pound (if
# the value is negative, this value will be yours, even if it is positive, it will be for the school)
total_amount.append(start) # Group values that meet this condition in a list
sss = int(sum(total_amount) / len(total_amount)) # Average values
print('The total amount required to be deposited in the bank:', sss)
check(sss)
print('The total amount paid in the case of paying school fees annually:', n1 * n2)
print('The amount saved:', n1 * n2 - sss)
| true |
6edb8f4a11829c755da100e7e5bb99b5cf964120 | machinelearningdeveloper/aoc_2016 | /01/directions.py | 2,092 | 4.125 | 4 | import re
def load_directions(filename):
"""Load directions from a file."""
with open(filename) as f:
return [direction.strip().strip(',') for direction
in f.readline().strip().split()]
def turn(orientation, direction):
"""Given an orientation on the compass
and a direction ("L" or "R"), return a
a new orientation after turning 90 deg
in the specified direction."""
compass = ['N', 'E', 'S', 'W']
if orientation not in compass:
raise ValueError('orientation must be N, E, S, or W')
if direction not in ['R', 'L']:
raise ValueError('direction must be R or L')
i = (compass.index(orientation) + (1 if direction == 'R' else -1)) % len(compass)
return compass[i]
def follow_directions(starting_point, starting_orientation, *directions):
"""Given a starting point, starting orientation
and a list of directions of the form DN, where D
is R (right) or L (left) and N is an integer,
return the ending point and orientation."""
point = starting_point
orientation = starting_orientation
for step in directions:
m = re.match(r'(?P<direction>R|L)(?P<n>\d+)', step)
if not m:
raise ValueError('each step must be in the form (L|R)[0-9]+')
orientation = turn(orientation, m.group('direction'))
x = y = 0
if orientation == 'E':
x = 1
elif orientation == 'W':
x = -1
if orientation == 'N':
y = 1
elif orientation == 'S':
y = -1
move = int(m.group('n'))
point = (point[0] + x * move, point[1] + y * move)
return (point, orientation)
def expand_path(starting_point, ending_point):
x1, y1 = starting_point
x2, y2 = ending_point
if x1 != x2 and y1 != y2:
raise ValueError('expand straight-line paths only')
if x1 != x2:
step = 1 if x1 <= x2 else -1
return [(x, y1) for x in range(x1, x2 + step, step)]
else:
step = 1 if y1 <= y2 else -1
return [(x1, y) for y in range(y1, y2 + step, step)]
| true |
cd10774a38f1a95e31fee570b7e91c4a50567682 | hackoregon/civicu-pythonii-summer-2017 | /student-work/cassandradelieto/Building Classes/working_with_classes.py | 1,521 | 4.25 | 4 | <<<<<<< HEAD
#Make the class have at least three attributes in its __init__ method and at least one method that
#combines two of these attributes in some way.
class MealPreparation:
people_min = 1
def __init__(self, people, pans, ingredients):
self.people = people
self.pans = pans
self.ingredients = ingredients
def contents(self):
MealPreparation.people_min +=2
return self.people
def __str__ (self):
return "A total of {} people are using {} pans and preparing a meal using the follow ingredient(s) {}.".format(self.people, self.pans, self.ingredients)
#print(MealPreparation.__dict__)
if __name__ == '__main__':
first_meal = MealPreparation(2,3,"meat")
print(first_meal)
=======
#Make the class have at least three attributes in its __init__ method and at least one method that
#combines two of these attributes in some way.
class MealPreparation:
people_min = 1
def __init__(self, people, pans, ingredients):
self.people = people
self.pans = pans
self.ingredients = ingredients
def contents(self):
MealPreparation.people_min +=2
return self.people
def __str__ (self):
return "A total of {} people are using {} pans and preparing a meal using the follow ingredient(s) {}.".format(self.people, self.pans, self.ingredients)
#print(MealPreparation.__dict__)
if __name__ == '__main__':
first_meal = MealPreparation(2,3,"meat")
print(first_meal)
>>>>>>> upstream/master
| true |
fb1ecb5dd3b5fc9d74345dd46aed919cbb00b018 | hackoregon/civicu-pythonii-summer-2017 | /student-work/sambeck/week_1/group_challenge/names_challenge.py | 2,095 | 4.125 | 4 | """
The goal of this challenge is to create a function that will take a list of
names and a bin size and then shuffle those names and return them in a
list of lists where the length of the inner lists matches the bin size.
For example calling the function with a list of names and the size of 2 should return
a list of lists where each inner list has 2 random names. If the the number
of names provided doesn't divide evenly into the bin size and only one name is
remaining add that name to another inner list.
"""
from random import shuffle
class Person:
def __init__(self, first_name, last_name, email):
self.first_name = first_name
self.last_name = last_name
self.email = email
def ask_a_question(self, question):
print('42')
class Student(Person):
def __init__(self, first, last, email, books, teacher):
super().__init__(first, last, email)
self.books = set(books)
self.teacher = teacher
teacher.addStudent(self)
def addBook(self, book):
self.books.add(book)
def removeBook(self, book):
if book in self.books:
self.books.remove(book)
else:
print('cannot remove')
def showBooks(self):
print(self.books)
class Teacher(Person):
def __init__(self, first, last, email):
super().__init__(first, last, email)
self.studentList = []
def addStudent(self, student):
self.studentList.append(student)
def names_func(a_list, size):
shuffle(a_list)
outlist = []
while len(a_list):
if len(a_list) >= size:
team = []
for i in range(size):
team.append(a_list.pop())
outlist.append(team)
elif len(a_list) == 1:
outlist[0] += a_list
break
else:
outlist.append(a_list)
break
return outlist
if __name__ == '__main__':
# Any code here will run when you run the command:
# `python names_challenge.py`
print(names_func(["one", "two", "three", "four", "five"], 2))
| true |
84fb96e92fe3bb4c321a3f7bc6e158229dfa835c | hackoregon/civicu-pythonii-summer-2017 | /student-work/tank/week_2/day_1/working_with_csvs/scrapy.py | 432 | 4.34375 | 4 | bicycle_sent = 'a blue bicycle'
# get a list of all letters with a for loop
bicycle_letters = []
for letter in bicycle_sent:
bicycle_letters.append(letter)
# get all letters with a list comp
bicycle_letters = [letter for letter in bicycle_sent]
print(bicycle_letters)
my_dict = {"a": 1, "b": 2, "c": 3}
# using a for loop
flipped_dict = {}
for key, value in my_dict.items():
flipped_dict[value] = key
print(flipped_dict) | false |
e911f43a2c731b07a59b0b39fa80cb2a8a2c91f8 | sydneykuhn/ICS3U-Unit4-05-Python-Sum-Loop | /loop_sum.py | 864 | 4.3125 | 4 | #!/usr/bin/env python3
# Created by: Sydney Kuhn
# Created on: Oct 2020
# This program calculates the sum of positive numbers
def main():
# this function is a loop
total = 0
# input
number_amount_as_string = input(
"How many numbers would you like to add together : "
)
# process & output
try:
number_amount = int(number_amount_as_string)
for loop_counter in range(number_amount):
user_input_as_string = input("Enter a number to add : ")
user_input = int(user_input_as_string)
if user_input < 0:
continue
total += user_input
print("The sum of just the positive numbers is = {0}".format(total))
except (Exception):
print("Invalid number entered, please try again.")
print("\nDone.")
if __name__ == "__main__":
main()
| true |
ead9dad89cb04fb1ae14fc07902e59979907f069 | akshxrx/Translator-Eng-Ben- | /main.py | 2,142 | 4.21875 | 4 | #!/usr/bin/python3
'''
This program is from p. 81 Figure 5.9 "Translating text (badly)" of
our Gutag textbook.
You can use it as a starter program for assignment 2.
The output from the program is:
--------------------------------------
Input: I drink good red wine, and eat bread.
Output: Je bois "good" rouge vin, et mange pain..
--------------------------------------
Input: Je bois du vin rouge.
Output: I drink of wine red..
--------------------------------------
'''
EtoF = {'bread' : 'pain', 'wine' : 'vin', 'with' : 'avec', 'I' : 'Je',
'eat' : 'mange', 'drink' : 'bois', 'John' : 'Jean', 'friends' : 'amis', 'and' : 'et', 'of' : 'du', 'red' : 'rouge'}
FtoE = {'pain': 'bread', 'vin': 'wine', 'avec': 'with', 'Je': 'I', 'mange': 'eat', 'bois': 'drink', 'Jean': 'John', 'amis': 'friends', 'et': 'and', 'du': 'of', 'rouge': 'red'}
dicts = {'English to French': EtoF, 'French to English': FtoE}
def translateWord(word, dictionary) :
if word in dictionary.keys():
return dictionary[word]
elif word != '':
return f'"{word}"'
return word
def translate(sentence, dicts, direction) :
UCletters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
LCletters = 'abcdefghijklmnopqrstuvwxyz'
letters = UCletters + LCletters
dictionary = dicts[direction]
translation = ''
word = ''
for character in sentence:
if character in letters:
word += character
else:
translation = translation + translateWord(word, dictionary) + character
word = ''
translation = translation + translateWord(word, dictionary)
return translation
sentence = 'I drink good red wine, and eat bread.'
translated = translate(sentence, dicts, 'English to French')
print('--------------------------------------')
print('Input:', sentence)
print('Output:', translated)
print('--------------------------------------')
sentence = 'Je bois du vin rouge.'
translated = translate(sentence, dicts, 'French to English')
print('Input:', sentence)
print('Output:', translated)
print('--------------------------------------')
| true |
9de7998ff8e5726574d7f7ab1dab0f290c46fe9e | gracepfohl/SIPPartnerAssignments | /DrawShapes.py | 978 | 4.84375 | 5 | from turtle import * #imports entire turtle library already created
import math
# Name your Turtle.
### Write your code below:
#this draws a square
#how do i loop this to user input? Helpppppppppp
def Draw_Shape(num_sides): #num_sides=argument and parameter
# Set Up your screen and starting position.
turtle = Turtle() #calls Turtle function
setup(1000,800) #Refers to size of turtle
x_pos = 0 #start location of turtle
y_pos = 0 #start location of turtle
turtle.penup() #makes turtle to move without drawing a line
turtle.setposition(x_pos, y_pos)
turtle.pendown() #allows turtle to draw again
angle = 360 / num_sides #formula for angle of a shape
for side in range(num_sides):
turtle.forward(100)
turtle.right(angle)
user_input = input("How many sides do you wnat in your shape?")
user_input = int(user_input)
Draw_Shape(user_input)
# Closes window on click.
exitonclick()
| true |
149b10ab41f0b765a8f1b08e71237842e39696a2 | MarsBighead/mustang | /Python/hackerrank/primality.py | 363 | 4.125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the primality function below.
def primality(n):
if n < 2: return "Not prime"
for i in range(2,int(math.sqrt(n))+1):
if n % i == 0:
return "Not prime"
return "Prime"
if __name__ == '__main__':
n = 12
result = primality(n)
print(result) | true |
aa69004039e3a325d8499d7819b8d67aa530486a | Sidhus234/Python-Dev-Course | /Codes/Session 8 Decorators/Session 8 Decorators Decorators II.py | 551 | 4.25 | 4 | # Decorators supercharges a function
def my_decorator(func):
def wrap_func():
print('***************')
func()
print('***************')
return wrap_func
@my_decorator
def hello():
print('helloooo')
hello()
def bye():
print('see ya later')
bye()
@my_decorator
def bye():
print('see ya later')
bye()
# Decorator allows us to reuse functionality for different functions
def hello1():
print('helloooo')
# above code does
hello2 = my_decorator(hello1)
hello2()
| false |
7a6e51fe2379f4ed34fb57ef67a56b190c5e8812 | Sidhus234/Python-Dev-Course | /Codes/Session 3/Session 3 - Python Basics - List.py | 2,433 | 4.21875 | 4 | # List is ordered sequence of objects
li = [1,2,3,4,5]
li2 = ['a', 'b',' c', 'd']
li3 = ['a', 1,2,'apple', 'True']
# Data Structure: Way to organise information
amazon_cart = ['notebooks', 'sunglasses']
amazon_cart[0]
amazon_cart[1]
amazon_cart[3]
# List Slicing
amazon_cart = [
'notebooks',
'sunglasses',
'toys',
'grapes']
amazon_cart[0::2]
# Lists are mutable (one element can be changed)
amazon_cart[0] = 'baby powder'
amazon_cart
amazon_cart[0:3]
# To copy a list use [:] otherwise both will refer to same thing
new_list = amazon_cart
new_list[0] = 'apple'
new_list
amazon_cart
new_list = amazon_cart[:]
new_list[0] = 'cat'
new_list
amazon_cart
basket = [1,2,3,4,5]
print(len(basket))
# List methods: https://www.w3schools.com/python/python_ref_list.asp
basket.append(100)
basket
# append changes the list inplace
basket.insert(0, 100)
basket
# insert modifies the list inplace
basket.extend([100, 1001, 101])
basket
# Removing things
basket.pop(0)
basket
basket.pop(-1)
basket
# pop also removes element inplace
# pop removes the element at given index
# remove takes out the given element
basket.remove(4)
basket
basket.clear()
basket
# Clear removes everything in the list
basket = [1,2,3,4,5]
basket.index(2)
# .index returns the index of given element
basket.index(1, 2,5)
basket.index(1, 0,5)
# Key word is a word we use in python which mean something
# https://www.w3schools.com/python/python_ref_keywords.asp
1 in basket
'x' in basket
'i' in 'Gursewak'
basket.count(1)
# 1 only exisits once in list basket
basket = [3,4,5,2,1,2,5,3,9]
basket.sort()
basket
# .sort() edits the same list
# sorted produces a new array
new_basket = sorted(basket)
basket
new_basket
new_basket1 = basket.copy()
basket.reverse()
basket
basket.sort()
basket.reverse()
basket
basket[::-1]
# generate list quickly
li = list(range(1,100))
li
sentence = ' '
sentence.join(['hi', 'my', 'name', 'is', 'JOJO'])
sentence
new_sentence = ' '.join(['hi', 'my', 'name', 'is', 'JOJO'])
new_sentence
# List unpacking
a,b,c = [1,2,3]
a
b
c
a,b,c = 1,2,3
a,b,c, *other, d = [1,2,3,4,5,6,7,8,9]
a
b
c
other
d
friends = ['Simon', 'Patty', 'Joy', 'Carrie', 'Amira', 'Chu']
new_friend = ['Stanley']
friends.extend(new_friend)
friends.sort()
friends
| true |
173734ee04b23eef886e0eeba9a376871dea1e34 | Gtech-inc/Projet-Tortue | /rectangle.py | 713 | 4.15625 | 4 | import turtle
def rectangle(x: int, y: int, w: int, h: int):
"""
Paramètres
x, y : coordonnées du centre de la base de rectangle
w : largeur du rectangle
h : hauteur du rectangle
Cette fonction dessine un rectangle Le point de coordonnées (x,y) est
sur le côté en bas au milieu
"""
if turtle.isdown():
turtle.penup()
turtle.setpos(x, y)
turtle.pendown()
turtle.goto(x + w, y)
turtle.goto(x + w, y - h)
turtle.goto(x, y - h)
turtle.goto(x, y)
turtle.penup()
if __name__ == '__main__':
rectangle(0, 0, 150, 100)
# On ferme la fenêtre si il y a un clique gauche
turtle.exitonclick()
| false |
7ee988759fd04ce71352b98ce412fb0c1ef0b89b | superSeanLin/Algorithms-and-Structures | /206_Reverse_Linked_List/206_Reverse_Linked_List.py | 1,063 | 4.125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: 'ListNode') -> 'ListNode':
# iteration
# get the head and insert tail
# if not head:
# return head
# p = head
# while p.next:
# p = p.next
# q = head
# while q != p:
# temp = q.next
# q.next = p.next
# p.next = q
# q = temp
# return q
# recursion I
# if not head or not head.next:
# return head
# p, q = head, head
# while p.next:
# q = p
# p = p.next
# q.next = None
# p.next = self.reverseList(head)
# return p
# recursion II
# use self loop
if not head or not head.next:
return head
p = self.reverseList(head.next)
head.next.next = head
head.next = None
return p
| false |
bfa9b44b9b9a7956c589f77ebc3a8b92b5320dce | s-torn/labb1 | /labb1.py | 607 | 4.375 | 4 | import math
print('Welcome to volume calculator!')
while True:
choice=input('Would you like to calculate the volume of a cube or a tetrahedon? \nType C or T, or leave empty to exit program.\n')
if choice=='':
break
elif choice=='c' or choice=='C':
cube=float(input('Enter cube side length in cm:\n'))
volume=cube**3
print(f'Cube volume is {volume} cm3.')
elif choice=='t' or choice=='T':
tetra=float(input('Enter tetrahedon side length in cm:\n'))
volume=tetra**3/(6*math.sqrt(2))
print(f'Tetrahedon volume is {round(volume,2)} cm3.')
| true |
866b45ac9072baa578d0e761262ca2ccb4f5f616 | LucasHCarvalho/LearningPy | /Lista 2/ordenacao.py | 417 | 4.15625 | 4 | '''
Exercício 5 - Verificando ordenação
Receba 3 números inteiros na entrada e imprima
crescente
se eles forem dados em ordem crescente. Caso contrário, imprima
não está em ordem crescente
'''
x = int(input("Digite um número:"))
y = int(input("Digite um número:"))
z = int(input("Digite um número:"))
if(x < y < z):
print("crescente")
else:
print("não está em ordem crescente") | false |
341a65b2b92441adeacbcbb3f4400c3ab77fe6e0 | andrewrowland1/RowlandAS-Yr12ComputerScience | /ACS Programming Task/06InputValidation.py | 638 | 4.15625 | 4 | #program that asks the user for a number between 1 and 10 and then outputs the times table for that number
i_Number = int(input("Please input a number between 1 and 10"))
#Check if number is between 1 and 10
if i_Number != 99:
while i_Number < 1 or i_Number > 10:
i_Number = int(input("Please input a number between 1 and 10"))
#program will times the number by the counter. after each loop the counter increases by 1 until the counter is above 12. then it will terminate
for counter in range (1,13):
print(i_Number * counter)
counter = counter + 1
#counter increases by 1 each loop
| true |
ff76cd187b2c26456106f5ba2a8970013af9eb74 | andrewrowland1/RowlandAS-Yr12ComputerScience | /ACS Programming Task/09SecondsAnyone.py | 411 | 4.21875 | 4 | #program that takes in the hours, minutes and seconds then outputs the total number of seconds
hours = int(input("Please input the number of hours"))
minutes = int(input("Please input the number of minutes"))
seconds = int(input("Please input the number of seconds"))
HoursToSeconds = hours * 3600
MinutesToSeconds = minutes * 60
TotalSeconds = HoursToSeconds + MinutesToSeconds + seconds
print(TotalSeconds)
| true |
c33b64669a2b47a412f2e03170c9c97cabd0e1bc | larissagabriela/Metodos_computacionais_em_Fisica | /Aula4_cor/mysum.py | 769 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
"""
- Sem erros.
"""
# In[20]:
"""
Esse programa calcula a soma dos elementos de uma lista
"""
lista1 = [1,2,3] #Definir as listas
lista2 = ['Hello, ', 'World!']
lista3 = [[1, 2],[4,3]]
def mysum(x): #Essa função calcula a soma dos elementos de uma função
"""
Calcula a soma dos elementos de uma lista
return: a soma dos elementos da lista
"""
soma = x[0] #A variável assume o valor do primeiro item da lista
for i in x[1:]: #Percorrer cada elemento da lista a partir do segundo
soma += i #Somar cada valor da lista na variável soma
return soma
print(mysum(lista1))
print(mysum(lista2))
print(mysum(lista3))
| false |
554e9317cfd3620297958628dce7ef56caac344a | wufei74/lpthw | /ex6.py | 1,381 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 9 13:54:00 2020
@author: WufeiNewPC
"""
types_of_people = 10 #Variable
x = f"There are {types_of_people} types of people." #x is a string that includes our previous variable, also a string
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}." #y is another formatted{hence the f in front} string which has two strings included in it, from two variables
print(x) #This prints the x string, which includes our variable "types_of_people"
print(y) #This prints the y string, which includes the variables "binary" and "do_not"
print(f"I said: {x}") #Another formatted string which includes the x variable, which calls the types_of_people variable
print(f"I also said: '{y}'") #Another formatted string that calls on and prints the variable string "y" in quotes.
hilarious = False #True/false variable
joke_evaluation = "Isn't that joke so funny?! {}" #This leaves an empty call for a variable at the end
print(joke_evaluation.format(hilarious)) #This prints the "joke_evaluation" variable string, and also calls to format it and input variable "hilarious" where the {} is.
w = "This is the left side of..."
e = "a string with a right side."
print(w + e) #This + is actually concatenating the string. Notice there are no spaces inbetween w and e when printed.
| true |
b88b313638cf463e78e950263daaa4c23bba3b2d | shilab/Courses | /multiplication.py | 505 | 4.15625 | 4 | #!/usr/bin/python
# An algorithm for multiplication
def multiplication (x, y):
# Input: Two integers x and y with y >= 0
# Output: The product of x and y
if y == 0:
return 0
z = multiplication (x, y // 2)
# z = multiplication (x, y >> 1) # right shift by 1 : divide by 2
if y % 2 == 0: # if x is even
# if x & 1 == 0:
return 2*z
else:
return x + 2*z
x = 201
y = 111
result = multiplication(x, y)
print x, y, result
# the cost is O(n^2)
| true |
9e6728a6064f89921a5c26423f8f2051fb2593fe | tbindi/hackerrank | /utopian_tree.py | 1,018 | 4.5 | 4 | '''
The Utopian tree goes through 2 cycles of growth every year. The first growth cycle occurs during the spring, when it doubles in height. The second growth cycle occurs during the summer, when its height increases by 1 meter.
Now, a new Utopian tree sapling is planted at the onset of the spring. Its height is 1 meter. Can you find the height of the tree after N growth cycles?
I/P:
2
3
4
O/P:
6
7
Explanation: #01:
There are 2 testcases.
N = 3:
the height of the tree at the end of the 1st cycle = 2
the height of the tree at the end of the 2nd cycle = 3
the height of the tree at the end of the 3rd cycle = 6
N = 4:
the height of the tree at the end of the 4th cycle = 7
'''
def ret_value(level):
if level == 0:
return 1
elif level % 2 == 1:
return 2 * ret_value(level-1)
elif level % 2 == 0:
return 1 + ret_value(level-1)
if __name__ == "__main__":
n = input()
inp = []
while n != 0:
inp.append(input())
n -= 1
for i in iter(inp):
print ret_value(i) | true |
0e7189bbd5e6781322ae078966ef9c64c6851204 | tbindi/hackerrank | /quick_sort.py | 844 | 4.25 | 4 | '''
The previous challenges covered Insertion Sort, which is a simple and intuitive sorting algorithm. Insertion Sort has a running time of O(N2) which isn't fast enough for most purposes. Instead, sorting in the real-world is done with faster algorithms like Quicksort, which will be covered in the challenges that follow.
The first step of Quicksort is to partition an array into two smaller arrays.
I/P:
5
4 5 3 7 2
O/P:
3 2 4 5 7
'''
# Head ends here
def partition(ar):
pivot = ar[0]
left = []
right = []
for i,c in enumerate(ar[1:]):
if c > pivot:
right.append(c)
else:
left.append(c)
print " ".join([str(x) for x in left + [pivot] + right])
# Tail starts here
m = input()
ar = [int(i) for i in raw_input().strip().split()]
partition(ar) | true |
99e33b7f6f0adb4d5fad4f9a449c22d28aa39ed5 | nutcha20/project_psit | /src/physics/resistor.py | 2,725 | 4.15625 | 4 | """ Resistor """
print("Resistor")
def electrical_resistivity_r():
""" Electrical Resistivity """
print("Electrical Resistivity")
print("Formula is R = p(I/A)")
print("R = Object resistance (Ω)")
print("p = Electrical resistivity of the object (Ω*m)")
print("I = Object length (m)")
print("A = Cross-sectional area of the object (m^2)")
print("Find R")
p = float(input("p : "))
i = float(input("I : "))
a = float(input("A : "))
print("R = %.2f Ω\n" %(p*(i/a)))
def electrical_resistivity_p():
""" Find p """
print("Electrical Resistivity")
print("Formula is R = p(I/A)")
print("R = Object resistance (Ω)")
print("p = Electrical resistivity of the object (Ω*m)")
print("I = Object length (m)")
print("A = Cross-sectional area of the object (m^2)")
print("Find p")
r = float(input("R : "))
i = float(input("I : "))
a = float(input("A : "))
print("p = %.2f Ω*m\n" %((r*a)/i))
def electrical_resistivity_i():
""" Find p """
print("Electrical Resistivity")
print("Formula is R = p(I/A)")
print("R = Object resistance (Ω)")
print("p = Electrical resistivity of the object (Ω*m)")
print("I = Object length (m)")
print("A = Cross-sectional area of the object (m^2)")
print("Find I")
p = float(input("p : "))
r = float(input("R : "))
a = float(input("A : "))
print("I = %.2f m\n" %((r*a)/p))
def electrical_resistivity_a():
""" Find A """
print("Electrical Resistivity")
print("Formula is R = p(I/A)")
print("R = Object resistance (Ω)")
print("p = Electrical resistivity of the object (Ω*m)")
print("I = Object length (m)")
print("A = Cross-sectional area of the object (m^2)")
print("Find A")
p = float(input("p : "))
r = float(input("R : "))
i = float(input("I : "))
print("A = %.2f m^2\n" %((p*i)/r))
def electrical_conductivity_p():
""" Electrical_Conductivity """
print("Electrical Conductivity")
print("Formula is p = 1/σ")
print("p = Electrical Resistivity of the object (Ω*m)")
print("σ = Electrical Conductivity of the object (Ω*m)^-1\n")
print("Find p")
q = float(input("σ : "))
print("p = %.2f Ω*m\n" %(1/q))
def electrical_conductivity_q():
""" Find q """
print("Electrical Conductivity")
print("Formula is p = 1/σ")
print("p = Electrical Resistivity of the object (Ω*m)")
print("σ = Electrical Conductivity of the object (Ω*m)^-1\n")
print("Find q")
p = float(input("p : "))
print("σ = %.2f (Ω*m)^-1\n" %(1/p))
| false |
5441eaec30a4f9966171b2b26e7f7e870c0f0e74 | akash20aeccse123/Python | /divisible_by_five_or_eleven.py | 230 | 4.1875 | 4 | n=int(input("Enter any Number:"))
if(n%5==0):
print("Number is Divisible by 5, SuccessFully.")
elif(n%11==0):
print("Number is Divisible by 11,SuccessFully.")
else:
print("Number is Not Divisible by 5 and 11.")
| true |
6cb577bb9f1277a3e98080727afcff35db97b025 | akash20aeccse123/Python | /area_rectangle.py | 226 | 4.4375 | 4 | '''3.program to obtain length and breadth of a rectangle and
calculate its area.'''
length=float(input("Enter lenght:"))
breadth=float(input("Enter breadth:"))
area=(length*breadth)
print("Area of rectangle=",area)
| true |
eeba1b63d2decaf4fd7f51ee47dd28b3e362e48b | t-silva/Academico | /Python/Exercícios/Listas/19.py | 1,833 | 4.15625 | 4 | #Defindo função para checar se número é FLOAT
def is_number(num):
try:
float(num)
#If successful, returns true.
return True
except:
#Silently ignores any exception.
pass
return False
###############################################
lista = []
print(" _________________________________")
print("| |")
print("|___Ordenando valores positivos___|")
print("|_Digite 0 ou negativo para sair._|")
print("|_________________________________|")
N = 1
while N > 0:
N = input("\n| Digite um valor positivo: ")
print("|_____________________________")
while not is_number(N):
print(" ______________________________________")
print("| |")
print(f"| ✘ Valor digitado não é um número ✘ |")
print("|______________________________________|")
N = input("\n| Digite um valor positivo: ")
print("|_____________________________")
N = float(N)
if N > 0:
if len(lista) == 0:
lista.append(N)
else:
tamanho = len(lista)
val = 1
count = 0
while count < tamanho and val == 1:
if N < lista[count]:
print(f'{N} < {lista[count]}')
lista.insert(count,N)
val = 0
count +=1
if val ==1:
print(f'{N} é o maior')
lista.append(N)
print("\nOrdenando Lista...",)
print("-----------------", end="")
for a in range(len(lista)):
print(f'{"-"* len(str(lista[a]))}--',end="")
print(f"\nLista ordenada = {lista}")
print("-----------------", end="")
for a in range(len(lista)):
print(f'{"-"* len(str(lista[a]))}--',end="")
| false |
634880b82438eb2db736c68502fccad65e6c82b3 | Michaelnstrauss/Byte | /inclass2_6/inclass26.py | 538 | 4.15625 | 4 | #!/usr/bin/env python3
# these two way of generating unsorted_list accomplish
# the exact same thing
from random import randint
unsorted_list = [randint(0,99) for _ in range(30)]
unsorted_list = []
for i in range(30):
unsorted_list.append(randint(0,99))
def bubble_sort(a_list):
for i in range(len(a_list)):
for j in range(len(a_list) - i):
if a_list[j] > a_list[j+1]:
a_list[j], a_list[j+1] = a_list[j+1], a_list[j]
print(unsorted_list)
bubble_sort(unsorted_list)
print(unsorted_list)
| false |
52f3269cac3ef4832f981628020b565ecdb05172 | Michaelnstrauss/Byte | /inclass2_6/n_class26.py | 305 | 4.28125 | 4 | #!/usr/bin/env python3
value = int(input('Give me a number: '))
if value > 100:
print("That's a big number")
if value % 2 == 0:
print('Also it is even')
else:
print('Also it is odd')
elif value > 10:
print("That's not too small")
else:
print("That's a small number")
| true |
ac152507216a5c02f28cfc0be604077652a782d4 | Michaelnstrauss/Byte | /udemy/capitalize.py | 286 | 4.25 | 4 |
string1 = 'michael'
def capitalize(string1):
up = string1.replace(string1[0], string1[0].upper())
return up
'''string2 = ''
for letter in string1:
string2 = string1.append(string1[0].upper())
print(string2)'''
print(capitalize(string1))
| false |
2c9d56b6d1850d516137f3bf35923967321db372 | Michaelnstrauss/Byte | /udemy/multiply_even_numbers.py | 208 | 4.125 | 4 |
a_list = [2,3,4,5,6]
def multiply_even_numbers(a_list):
total = 1
for num in a_list:
if num % 2 == 0:
total = total * num
return total
print(multiply_even_numbers(a_list)) | false |
5efda9d85ecbfef3e4e521181b23ddf1046a6d76 | Karlasalome/python-challenge | /HW2_python/PyPoll/python hw.py | 1,827 | 4.25 | 4 | #import csv file and The total number of months included in the dataset
import csv
input_File ="C:\\Users\\KarlaSalome\\Desktop\\COLNYC201904DATA3\\homework\\03-Python\\Instructions\\PyBank\\Resources\\budget_data.csv"
totalMonths = 0
totalRev = 0
pastRev = 0
highestIncRev = 0
lowestDecRev = 0
#create lists to store revenue change. [] saves it as a list.
revChange=[]
with open(input_File, newline='') as csvfile:
#read file
#split the data on commas
budget_csvreader = csv.reader(csvfile, delimiter=',')
#skip header row one time
next(budget_csvreader)
for row in budget_csvreader:
#count total months in csv file
totalMonths = totalMonths + 1
#count total revenue in csv file using float in case there are decimal points
totalRev = totalRev + (float(row[1]))
#create a variable that will count the revenue change also with float
monthlyRevChange = float(row[1]) - pastRev
pastRev = float(row[1])
#calculate the average change in revenue
avgRevChange = totalRev/totalMonths
#print everything, add '$' to currency
#find the greatest increase in revenue
if monthlyRevChange > highestIncRev:
highestIncMonth = row[0]
highestIncRev = monthlyRevChange
#find the greatest decrease in revenue
if monthlyRevChange < lowestDecRev:
lowestDecMonth = row[0]
lowestDecRev = monthlyRevChange
print("Karla Salome Pratts -FINANCIAL ANALYSIS-")
print("_____________________________________")
print(f"Total Months: {totalMonths}")
print(f"Total Revenue: ${totalRev}")
print(f"Average Revenue Change: ${avgRevChange}")
print(f"Greatest Increase in Revenue: {highestIncMonth} ${highestIncRev}")
print(f"Greatest Decrease in Revenue: {lowestDecMonth} ${lowestDecRev}") | true |
c6c0641c14295c9b795233455a1f79250d03d9e4 | Robert-Rutherford/learning-Python | /practiceProblems/oopCalculator.py | 664 | 4.15625 | 4 | # Simple OOP Calculator
# site: https://edabit.com/challenge/ta8GBizBNbRGo5iC6
# Create methods for the Calculator class that can do the following:
#
# Add two numbers.
# Subtract two numbers.
# Multiply two numbers.
# Divide two numbers.
class Calculator:
def add(self, num1, num2):
return num1 + num2
def subtract(self, num1, num2):
return num1 - num2
def multiply(self, num1, num2):
return num1 * num2
def divide(self, num1, num2):
return num1 / num2
calculator = Calculator()
print(calculator.add(10, 5))
print(calculator.subtract(10, 5))
print(calculator.multiply(10, 5))
print(calculator.divide(10, 5))
| true |
a7904035e3f200c5f393d63c968de180ae99d2d3 | Robert-Rutherford/learning-Python | /practiceProblems/fullnameAndEmail.py | 1,105 | 4.40625 | 4 | # Fullname and Email
# site: https://edabit.com/challenge/gB7nt6WzZy8TymCah
# Create the instance attributes fullname and email in the Employee class. Given a person's first and last names:
#
# Form the fullname by simply joining the first and last name together, separated by a space.
# Form the email by joining the first and last name together with a "." in between, and follow it with '@company.com'
# at the end. Make sure everything is in lowercase.
class Employee:
def __init__(self, firstname, lastname):
self.firstname = firstname.lower()
self.lastname = lastname.lower()
self.fullname = self.firstname + " " + self.lastname
self.email = self.firstname + "." + self.lastname + "@company.com"
# full name
def fullname(self):
print(self.firstname + " " + self.lastname)
# email
def email(self):
print(self.firstname + "." + self.lastname + "@company.com")
emp_1 = Employee("John", "Smith")
emp_2 = Employee("Mary", "Sue")
emp_3 = Employee("Antony", "Walker")
print(emp_1.fullname)
print(emp_2.email)
print(emp_3.firstname)
| true |
7f09d7d596c934a8956121ddfff2bffe38da293a | stewartstout/dsp | /python/q8_parsing.py | 1,240 | 4.40625 | 4 | #The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
# The below skeleton is optional. You can use it or you can write the script with an approach of your choice.
import csv
def read_data(data):
# COMPLETE THIS FUNCTION
def get_min_score_difference(self, parsed_data):
# COMPLETE THIS FUNCTION
def get_team(self, index_value, parsed_data):
# COMPLETE THIS FUNCTION
Answer:
import csv
with open('/Users/stewartstout/desktop/football.csv', 'r') as f:
reader = csv.reader(f)
your_list = list(reader)
i = 1
for row in your_list[1:]:
diff = int(row[5]) - int(row[6])
your_list[i].append(diff)
i += 1
r = 2
smallest_difference = ''
min = your_list[r - 1][8]
while r < len(your_list):
if your_list[r][8] < min:
smallest_difference = your_list[r][0]
min = your_list[r][8]
r += 1
print smallest_difference
| true |
09909b7ab1b60f5c575816e734fb6e78276d8051 | 4OKEEB90/COM404 | /1-basics/03-decision/01-if/bot.py | 357 | 4.28125 | 4 | #Ask what kind of book this is.
print("What type of book is this?")
#define the variable "book" as a string variable to be input by the user.
book = str(input())
#If statement to give a specific response to "adventure" books
if book == "adventure":
print("I like adventure books!")
#A print statement to end the process
print("Finished reading book.")
| true |
c7583dca55e506efd68867b022ccc79b0d98fc45 | chaoswork/leetcode | /036.ValidSudoku.py | 1,972 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author: Chao Huang (huangchao.cpp@gmail.com)
Date: Wed Feb 21 12:11:45 2018
Brief: https://leetcode.com/problems/valid-sudoku/description/
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled
with the character '.'.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable.
Only the filled cells need to be validated.
"""
class Solution(object):
def check_list(self, lst):
nums_set = set()
for num in lst:
if num == '.':
continue
if num in nums_set:
return False
nums_set.add(num)
return True
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
n = len(board)
for i in range(n):
if not self.check_list(board[i]):
return False
nums = []
for j in range(n):
nums.append(board[j][i])
if not self.check_list(nums):
return False
for i in range(3):
for j in range(3):
nums = []
for p in range(3):
for q in range(3):
nums.append(board[i * 3 + p][j * 3 + q])
if not self.check_list(nums):
return False
return True
sol = Solution()
a = [[".",".","4",".",".",".","6","3","."],[".",".",".",".",".",".",".",".","."],["5",".",".",".",".",".",".","9","."],[".",".",".","5","6",".",".",".","."],["4",".","3",".",".",".",".",".","1"],[".",".",".","7",".",".",".",".","."],[".",".",".","5",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."]]
print sol.isValidSudoku(a)
print sol.check_list(['.', '.', '.', '5', '.', '.', '5', '.', '.'])
| true |
57874f2e9b4ff5b3208e3132732176e693a56603 | djovercash/python_practice1 | /python_lists.py | 1,596 | 4.15625 | 4 | cities = ['Solta', 'Greenville', 'Buenos Aires', 'Los Cabos', 'Walla Walla Valley', 'Marakesh', 'Albuquerque', 'Archipelago Sea', 'Iguazu Falls', 'Salina Island', 'Toronto', 'Pyeongchang']
print cities
countries = ['Croatia', 'USA', 'Argentina', 'Mexico', 'USA', 'Morocco', 'New Mexico', 'Finland', 'Argentina', 'Italy', 'Canada', 'South Korea']
print countries
print cities[0] #Solta
print cities[2] #Buenos Aires
print cities[-1] #Pyeongchang
print cities[-2] #Toronto
top_canadian_city = cities[-2] #Toronto
print top_canadian_city #Toronto
print type(top_canadian_city) #str
print type(cities) #list
#SLICING an element
print cities[0:2] #Solta, Greenville. First number is what index to start at and second is what index to end at
print cities[4:6] #Walla Walla Valley, Marakesh
top_two = cities[0:2]
print top_two
#Changing elements with destructive methods
cities.append('San Antonio')
print cities #Added San Antonio to the end of cities
cities.pop()
print cities #Removes last element (San Antonio) from cities
cities[4] = "WHAT?"
print cities #Changes the element at index 4
cities[4] = "Walla Walla Valley"
print cities #Changes it back
#Use SET to find unique value (undestructively)
cities.append("Solta") #Added Solta to cities
print cities
unique_cities = set(cities)
print unique_cities
print type(set()) #set
# A set is just like a list, except elements do not have order and each element appears just once.
# i.e. unique_cities[4] returns an error
unique_cities_list = list(unique_cities)
print unique_cities_list
print len(unique_cities_list)
print len(cities)
| false |
658d7e8001639d68252a1ef16041370254e8c9f4 | bapbuild/Hacker | /Reverse_a_string.py | 559 | 4.15625 | 4 | #############Sample1#######################
# str1 = input().strip()
# def reverser(s):
# y =''.join(reversed(s))
# return y
#
# print(reverser(str1))
#############Sample 2################
# str1 = input().strip()
#
# def reverser(word):
# reword = word[::-1]
# return reword
#
#
# print(reverser(str1))
######################Sample 3#################
str1 = input().strip()
def reverse(str1):
reversed =''
index= len(str1)
while index>0:
reversed += str1[index-1]
index-=1
print(reversed)
reverse(str1) | false |
7baeb5e08cdf3b2ad91af050c37defa4d78fa4cc | BibhushaSapkota/pyhtonlabwork | /programming/dragon.py | 273 | 4.34375 | 4 | # write a program to print sum of three numbers
firstnumber=float(input("enter first number"))
secondnumber=float(input("enter second number"))
thirdnumber=float(input("enter third number"))
sum=firstnumber+secondnumber+thirdnumber
print("the sum of three number is" ,sum)
| true |
973060782b7d91537a738d24c838d25a7281e749 | DarrenWen/PythonHelloWord | /test2/currency_convert_v2.py | 471 | 4.21875 | 4 | # 汇率
usd_vs_rmb = 6.97
# 带单位的货币输入
currence_str_value = input("请输入带单位的货币金额:")
str_value=currence_str_value[:-3];
unit = currence_str_value[-3:].upper()
print(unit)
if unit=="USD":
rmb_value=eval(str_value)
print("美元转人民币金额:",rmb_value*usd_vs_rmb)
elif unit=="RMB":
usd_value = eval(str_value)
print("人民币转美元金额:", usd_value / usd_vs_rmb)
else:
print("不支持该汇率转换")
| false |
f1debe1432dc1a0ed6408cf41eeff23251b2de8a | DarrenWen/PythonHelloWord | /test2/currency_convert_v3.py | 847 | 4.125 | 4 | '''
作者:Wiggins
日期:2018年11月6日
版本:v3
'''
# 汇率
usd_vs_rmb = 6.97
# 带单位的货币输入
currence_str_value = input("请输入带单位的货币金额(退出程序请输入Q):")
while(currence_str_value != "Q"):
str_value=currence_str_value[:-3];
unit = currence_str_value[-3:].upper()
# print(unit)
if unit=="USD":
rmb_value=eval(str_value)
print("美元转人民币金额:",rmb_value*usd_vs_rmb)
elif unit=="RMB":
usd_value = eval(str_value)
print("人民币转美元金额:", usd_value / usd_vs_rmb)
else:
print("不支持该汇率转换")
print("********************************************************************")
currence_str_value = input("请输入带单位的货币金额(退出程序请输入Q):")
print("程序已退出")
| false |
8f5ad9ec17a171908e33b17236e61d20c4d98777 | ThanushaJ/coding-bootcamp | /LoopingProblems/NaturalNumbersWhile.py | 275 | 4.25 | 4 | """Write a program to print all natural numbers from 1 to n. - using while loop
Positive TC:
Input: 6
Output: 1 2 3 4 5 6
Negative TC:
Input: 6
Output: 1 2 3 4 5
"""
startNum = 1
endNum = int(input())
while startNum <= endNum:
print(startNum, end=" ")
startNum += 1
| true |
62147a23b0140e1be5318ef65a78f318d9a8ec46 | bholaa72429/01-Lucky_Unicorn | /05_valid_number.py | 748 | 4.375 | 4 | # Ask the user for a number
# Loop question so that it repeats until valid number is entered
# Make code recyclable!
# function goes here
def intcheck(question, low, high):
valid = False
while not valid:
error = "Whoops! Please enter an integer between {} and {}".format(low, high)
try:
response = int(input("Enter an integer between {} and {}: ".format(low, high)))
if low <= response <= high:
return response
else:
print(error)
print()
except ValueError:
print(error)
# main routine goes here
num_1 = intcheck("Enter a number between 1 and 15", 1, 15 )
num_2 = intcheck("Enter a number between 5 and 10", 5, 10) | true |
a9e4a0d0bef4da447d1ecab64a54cb947431d10f | nathanbaja/Python-Exercises-CursoEmVideo | /ex017.py | 584 | 4.125 | 4 | ## from math import sqrt
## o = float(input('digite o comprimeto de um dos catetos do triangulo '))
## a = float(input('digite o comprimento do outro cateto '))
## h1 = o**2
## h2 = a**2
## h3 = h1 + h2
## print('a o comprimento da hipotenusa deste triangulo é de {:.2f} centimetros'.format(sqrt(h3)))
from math import hypot
o = float(input('digite o comprimeto de um dos catetos do triangulo '))
a = float(input('digite o comprimento do outro cateto '))
h = hypot(o, a)
print('a o comprimento da hipotenusa deste triangulo é de {:.2f} centimetros'.format(h)) | false |
babb8b6de98197b31753c0dd29382197c736cca0 | Radzihowski/python | /realpython.com/ch06-functions-and-loops/run-in-circles.py | 678 | 4.3125 | 4 | # 6.4 - Run in Circles
# Solutions to review exercises
# Exercise 1
# Write a for loop that prints out the integers 2 through 10, each on a new line, using range()
for n in range (2,11):
print(n)
# Exercise 2
# Write a while loop thet print out hte integers 2 through 10
i = 2
while i < 11:
print(i)
i = i + 1
# Exercise 3
# Write a function called double() that takes a number as its input and doubles it.
# Then use doubles() in a loop to double the number 2 three times, displaying each result on a separate line
# Here's some sample output:
# 4
# 8
# 16
def doubles(k):
return k * 2
num = 2
for l in range (0, 3):
num = doubles(num)
print(num)
| true |
eebd6f4fb0cea51b0ba0c9c9c5445073b0811ebe | eric-mena/AutomateTheBoringStuff | /Ch_4_Practice_Q.py | 2,218 | 4.625 | 5 | #Q1. What is []?
#A1. This is an empty list.
#Q2. How would you assign the value 'hello' as the third value in a list stored
# in a variable named spam? (Assume spam contains [2, 4, 6, 8, 10].)
#A2. spam[2] = 'hello'
#Q3. For the following three questions, let’s say spam contains the list ['a',
# 'b', 'c', 'd'].
#Q3. What does spam[int('3' * 2) / 11] evaluate to?
#A3. 'd'
#Q4. What does spam[-1] evaluate to?
#A4. 'd'
#Q5. What does spam[:2] evaluate to?
#A5. ['a','b']
#Q6. For the following three questions, let’s say bacon contains the list
# [3.14, 'cat', 11, 'cat', True].
# What does bacon.index('cat') evaluate to?
#A6. 1
#Q7. What does bacon.append(99) make the list value in bacon look like?
#A7. [3.14, 'cat', 11, 'cat', True, 99]
#Q8. What does bacon.remove('cat') make the list value in bacon look like?
#A8. [3.14, 11, 'cat', True]
#Q9. What are the operators for list concatenation and list replication?
#A9. +,*
#Q10. What is the difference between the append() and insert() list methods?
#A10. append() will add a variable to the end of a list, while insert() will add a variable
# to the index specified within the square brackets.
#Q11. What are two ways to remove values from a list?
#A11. del(), remove()
#Q12. Name a few ways that list values are similar to string values.
#A12. You can call specific locations within a list/string, you can use the length function, you
# you can slice them.
#Q13. What is the difference between lists and tuples?
#A13. Lists are mutable, while tuples are immutable.
#Q14. How do you type the tuple value that has just the integer value 42 in it?
#A14. cheese = (42,)
#Q15. How can you get the tuple form of a list value? How can you get the list
# form of a tuple value?
#A15. tuple(), and list().
#Q16. Variables that “contain” list values don’t actually contain lists directly.
# What do they contain instead?
#A16. They contain references to list values.
#Q17. What is the difference between copy.copy() and copy.deepcopy()?
#A17. the methods differ in that copy() will duplicate a list with conventional variables, and
# deepcopy() will duplicate lists that contain lists within them.
| false |
9dcd285fde6c09ab315cc099fc46cc1e5251bfb4 | Index-Eletronic/Python3 | /exerc_dict_teoria.py | 1,700 | 4.3125 | 4 | '''
Teoria sobre Dicionários em python
'''
pessoa = {'nome': ' Filipe', 'sexo': 'M', 'idade': 25}
print(pessoa['nome'])
print(pessoa['idade'])
print(f'O{pessoa["nome"]} tem {pessoa["idade"]}') # Como esta dentro de ' ' (simples) tem que colocar "" ( duplas )
print(pessoa.keys())
print(pessoa.values())
print(pessoa.items())
print('-=' * 20)
print('Acessando através de laços.')
for k in pessoa.keys():
print(k)
print('-=' * 20)
for k, v in pessoa.items():
print(f'{k} = {v}')
print('-=' * 20)
for k in pessoa.values():
print(k)
print('-=' * 20)
del pessoa['sexo'] # Ira deletar o elemento sexo.
print(pessoa)
print('-=' * 20)
pessoa['nome']= 'Leandro' # Modifida o elemento nome.
pessoa['peso']= 98.5 # Adiciona o elemento 'peso'.. NAO precisa utilizar o append.
print(pessoa)
print(f'-=' * 20, {"DICIONARIO DENTRO DE UMA LISTA"}, '-=' * 20)
brasil = []
estado1 = {'uf': 'Rio de Janeiro', 'Sigla': 'RJ'}
estado2 = {'uf': 'São Paulo', 'Sigla': 'SP'}
brasil.append(estado1)
brasil.append(estado2)
print(estado1) # Uma lista com primeiro elemento.
print(estado2) # Uma lista com segundo elemento.
print(brasil)
print(brasil[0]) # ira mostrar o primeiro elemento
print(brasil[0]['uf']) #Ira mostrar o Rio de Janeiro
print(brasil[1]['Sigla']) # Ira mostra SP
print('-=' * 20)
estado = dict()
brasil = list()
for c in range(0, 3):
estado['uf'] = str(input('Unidade Federativa: '))
estado['Sigla'] = str(input('Sigla do Estado: '))
brasil.append(estado.copy()) # .copy substitui o [:]
for e in brasil:
for k, v in e.items():
print(f'O campo {k} tem valor {v}')
#-- OUUUU
for v in e.values():
print(v, end=' ')
print()# Para pular de linha
| false |
847b3bc95969c989ad55097eaccf01753aa82bbc | jobaamos/gap-year-club-code | /AMOS15.py | 471 | 4.3125 | 4 | #python program to print the heighest digit out of two
while True:
print("enter 'x' for exit.")
print("enter two numbers;")
num1=input()
num2=input()
if num1=='x':
break
else:
number1=int(num1)
number2=int(num2)
if number1>number2:
largest=number1
else:
largest=number2
print("largest of entered two numbers is", largest,"\n")
| true |
8194dc0c4b4a196646923a0fa270182c907162c4 | faithmyself92129/hellow100day | /D8/hack.py | 397 | 4.15625 | 4 | """另一种创建类的方式"""
def bar(self, name):
self._name =name
def foo(self, course_name):
print('%s正在学习%s。' % (self._name, course_name))
def main():
Student = type('Student', (object,),dict(__init__=bar, study = foo) )
stu1 = Student('罗浩')
stu1.study('Python 程序设计')
print(Student)
if __name__ == '__main__':
main()
| false |
5e47ff673a8aa213cac90d9ef74ecaeabf29e636 | faithmyself92129/hellow100day | /D8/rect.py | 758 | 4.21875 | 4 | """定义和使用矩形类"""
class Rect(object):
def __init__(self, width = 0, height = 0):
self._width = width
self._height = height
def perimeter(self):
return (self._width + self._height)*2
def area(self):
return self._width*self._height
def __str__(self):
"""矩形对象的字符串表达式"""
return '矩形[%f, %f]' % (self._width,self._height)
def __del__(self):
"""析构函数"""
print('销毁矩形对象')
if __name__ == '__main__':
rect1 = Rect()
print(rect1)
print(rect1.perimeter())
print(rect1.area())
rect2 = Rect(3.5, 4.5)
print(rect2)
print(rect2.area())
print(rect2.perimeter())
| false |
c232c2fa6b62812cb9c9b4b4b3419f0abea4796a | tamaragmnunes/Exerc-cios-extra---curso-python | /Desafio027.py | 270 | 4.125 | 4 | # Digite o seu nome completo e mostre o seu primeiro nome e o último
nome = str(input('Digite o seu nome completo: ')).split()
print('O seu primeiro nome é {}.'.format(nome[0]))
print('O seu último nome é {}.'.format(nome[-1]))
print('Fim do programa!!! :)')
| false |
881450a9c84b4409be080decf709a19dac68d9e1 | Winvoker/oop | /oop2.py | 816 | 4.46875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 29 22:10:34 2020
@author: batuhan
"""
from abc import ABC,abstractmethod
class Shape(ABC): # my abstract class
@abstractmethod
def area(self): pass # my abstract method
@abstractmethod
def perimeter(self): pass # my abstract method
def toString(self): pass
class Square(Shape):
def __init__(self,a):
self.a=a
def area(self):
return(self.a*self.a)
def perimeter(self):
return(self.a*4)
def toString(self):
print("Square")
class Circle(Shape):
def __init__(self,a):
self.a=a
def area(self,a):
return(3.14*self.a**2)
def perimeter(self):
return(2*3.14*self.a)
def toString(self):
print("circle")
sekil=Square(2) | false |
0b572f3b68ee047f5203534b6a53fc93a8c61be0 | dan2014/Data-Structures | /queue/queue.py | 1,035 | 4.15625 | 4 | class Queue:
def __init__(self):
self.size = 0
# what data structure should we
# use to store queue elements?
self.storage = []
def __repr__(self):
if(self.len() == 0):
return "The queue is empty"
else:
for i in reversed(self.storage):
print(f"{i}")
return ""
def enqueue(self, item):
self.storage.append(item)
self.size += 1
def dequeue(self):
if( self.len() > 0 ):
temp = self.storage[0]
self.storage.pop(0)
self.size -= 1
return temp
else:
pass
def len(self):
return self.size
if __name__ == "__main__":
test_queue = Queue()
test_queue.enqueue(3)
test_queue.enqueue(4)
test_queue.enqueue(5)
print(test_queue)
test_queue.dequeue()
print(test_queue)
test_queue.enqueue(6)
print(test_queue)
test_queue.dequeue()
print(test_queue)
test_queue.dequeue()
print(test_queue)
test_queue.dequeue()
print(test_queue)
test_queue.dequeue() | false |
540fade4cee914439f6ec97fa29c5b3c98b2ea09 | mchvz93/Python_Projects | /flaglab2.py | 573 | 4.4375 | 4 | #Find largest number till users enter a flag
num = int(input("Enter a value: "))
large = int(input("Enter a value: "))
while num != -999:
if num > large:
large = num
num = int(input("Enter a value: "))
print("The largest number is: ", large)
'''>>>
Enter a value: 12
Enter a value: 64
Enter a value: 95
The largest number is: 64
Enter a value: 320
The largest number is: 95
Enter a value: 12
The largest number is: 320
Enter a value: 35
The largest number is: 320
Enter a value: -999
The largest number is: 320
>>>'''
| true |
e5b4b9399732c498b326a6db5718dd3776df0d12 | fatoustyles/GWC2019 | /gtn.py | 782 | 4.1875 | 4 | from random import * #imports the ability to get a random number
aRandomNumber = randint(1,20) #generates a random integer
tries = 3
while tries > 0:
guess = input("Guess a number between 1 and 20 (inclusive): ")
if not guess.isnumeric(): #checks if a string is only digits 0 to 9
print("That's not a positive whole number, try again!")
else:
tries -= 1
guess = int(guess) #converts a string to an integer
if tries == 0:
print("sorry! no more tries left!")
break
if(guess == aRandomNumber):
print("You're right!")
break
elif(guess > aRandomNumber):
print("The number is too high. Try again!")
else:
print("The number is too low. Try again!")
| true |
2b9ec69ec998a02d99eef6213a8e50af235181c7 | DancewithPeng/PythonLearning | /my_string.py | 607 | 4.4375 | 4 | # 1.单引号字符串
str = '单引号'
print(str)
# 转义符
str2 = 'python is good, isn\'t it?'
print(str2)
# 多行字符
str3 = '''
this is a paragraph
second line
'''
print(str3)
# 字符串拼接
# + 号拼接
print(str + str2)
# 直接拼接,直接拼接不支持变量,只支持字面量
print('I am a ''Coder')
# 字符,通过索引直接访问对应的字符
print(str[0])
# [0:3] 表示一个切片
print(str[0:3])
# [:3] [0:] 可以缺省开始和结束的索引
print(str[:3], str[0:])
# 取字符串长度
print(len(str))
# python的字符串都是不可变的
| false |
69d2281a1043d16e50627b26f5ae51bc54ce0a24 | prajaktaray/PreCourse_2 | /Exercise_4.py | 1,456 | 4.53125 | 5 | # Python program for implementation of MergeSort
#The function divides the array in the middle and calls itself recursively for each half separately
#when it reaches one element in each on the left and right halves, it starts merging by comparing the 2 divided subarrays and
#storing it in the original array
#Time Complexity = O(logn) Space Complexity= O(n)
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr)/2
left = arr[:mid]
right = arr[mid:]
mergeSort(left)
mergeSort(right)
i=j=k = 0
#Compares the elements in left and right array and copies to the original array
while( i<len(left) and j <len(right)):
if(left[i]<right[j]):
arr[k] = left[i]
i = i+1
else:
arr[k] = right[j]
j = j+1
k = k+1
#checks if there is any data left in the left and right arrays then it copies it to the original array
while i< len(left):
arr[k] = left[i]
i = i+1
k = k+1
while j< len(right):
arr[k] = right[j]
j = j+1
k = k+1
# Code to print the list
def printList(arr):
for a in arr:
print(a)
# driver code to test the above code
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print ("Given array is")
printList(arr)
mergeSort(arr)
print("Sorted array is: ")
printList(arr)
| true |
750b8a7f546ec79d8b40c534af1a0234a5b9bc5d | swayamsudha/python-programs | /Freq_List.py | 626 | 4.15625 | 4 | #Frequency of each element in the array:
Arr=[]
Freq=[]
size=int(input("Enter the size of Array:"))
for i in range(size):
print("Value in index",i)
item=int(input())
Arr.append(item)
Freq.append(-1)
print("The Array is",Arr)
for i in range(size):
count=1
for j in range(i+1,size):
if(Arr[i]==Arr[j]):
count+=1
Freq[j]=0
if(Freq[i]!=0):
Freq[i]=count
print("Frequency of each Elements in the list is as follows: ")
for i in range(size):
if(Freq[i] != 0):
print("{0} occures {1} time(s) is the list.".format(Arr[i],Freq[i]))
| true |
041b49be465114a2b052ca1608e518de1e50e3de | swayamsudha/python-programs | /factorial.py | 280 | 4.40625 | 4 | ##WAP to calculate factorial of a number:
num=int(input("Enter the number:"))
fact=1
if(num<0):
print("factorial can not be calculated! please Enter a positive number")
else:
for i in range (1,num+1):
fact=fact*i
print("Factorial of ",num ,"is" ,fact)
| true |
79d67deee5b4eadf1fb7d13b0923583779425b5f | swayamsudha/python-programs | /Sum_Natural.py | 252 | 4.15625 | 4 | ##WAP to find sum of the natural numbers;
num=int(input("Enter the number:"))
sum=0
temp=num
if(num<0):
print("Not a valid input!!")
else:
while(num!=0):
sum+=num
num-=1
print("The sum of " ,temp, "natural number is" ,sum)
| true |
9fe286e3d320776996f2daa4af96e97172e3db0d | JasonPlatzer/class8 | /exchange_rate.py | 1,885 | 4.25 | 4 | """ Uses exchangeratesapi.io to get exchange rates
Validation, error handling omitted for clarity. """
import requests
def main():
currency = get_target_currency()
dollars = get_dollar_amount()
converted = convert_dollars_to_target(dollars, currency)
display_result(dollars, currency, converted)
def get_target_currency():
""" Get target currency, and return as uppercase symbol.
TODO add validation, error handling """
currency = input('Enter target currency code e.g. EUR, CAD: ')
return currency.upper()
def get_dollar_amount():
""" Get number of dollars. TODO add validation, error handling """
return float(input('Enter amount of dollars to convert: '))
def convert_dollars_to_target(dollars, target_currency):
""" Convert amount of dollars to target currency """
exchange_rate = get_exchange_rate(target_currency)
converted = convert(dollars, exchange_rate)
return converted
def get_exchange_rate(currency):
""" Call API and extra data from response """
response = request_rates(currency)
rate = extract_rate(response, currency)
return rate
def request_rates(currency):
""" Perform API request, return response. TODO add error handling """
params = {'base': 'USD', 'symbols': currency}
url = 'https://api.exchangeratesapi.io/latest'
return requests.get(url, params=params).json()
def extract_rate(rates, currency):
""" Process the JSON response from the API, extract rate data. TODO add error handling """
return rates['rates'][currency]
def convert(amount, exchange_rate):
""" Convert using the given exchange rate """
return amount * exchange_rate
def display_result(dollars, currency, converted):
""" Format and display the result """
print(f'${dollars:.2f} is equivalent to {currency} {converted:.2f}')
if __name__ == '__main__':
main() | true |
468322d64263baf41b0f3ba2f2931653d2b68db0 | Xytam/201 | /HW/HW2/part3.py | 1,116 | 4.1875 | 4 | #File: part1.py
#Author: Jake Horvers
#Date: 09/22/114
#Section: 4
#E-mail: horvers1@umbc.edu
#Description: Uses if/else input to diagnose
print("Hello User! This program is designed to dianose how horribly sick you are!")
#If the user has a fever, continues to ask questions
fever = str(input("Do you have a fever? (y/n): "))
if(fever == ("y")):
rash = str(input("Do you have a rash? (y/n): "))
#Prints measles diagnosis
if(fever == ("y") and rash == ("y")):
print("Diagnosis: Measles")
#If there's no rash, asks about ears
elif(fever == ("y") and rash == ("n")):
ear = str(input("Do your ears hurt? (y/n): "))
#Determines Ear infection or flu
if(ear == ("y")):
print("Diagnosis: Ear Infection")
else:
print("Diagnosis: Flu")
else:
print("Invalid response...")
#If the user doesn't have a fever, asks about nose
else:
nose = str(input("Do you have a stuffy nose? (y/n): "))
if(fever == ("n") and nose == ("n")):
print("Diagnosis: Hypochondriac")
elif(fever == ("n") and nose == ("y")):
print("Diagnosis: Head Cold")
| true |
263cdfab52d05d0f76f87e22b46e110d4f78fd52 | superyang713/DeepLearning | /scratch/optimization/batch_stochastic_gradient_descent.py | 1,467 | 4.15625 | 4 | """
A simple optimization method in machine learning is gradient descent. When you
take gradient steps with respect to all m samples on each step, it is also
called Batch Gradient Descent.
"""
X = data_input
Y = labels
parameters = initialize_parameters(layers_dims)
for i in range(0, num_iterations):
# Forward propagation
a, caches = forward_propagation(X, parameters)
# Compute cost.
cost = compute_cost(a, Y)
# Backward propagation.
grads = backward_propagation(a, caches, parameters)
# Update parameters.
parameters = update_parameters(parameters, grads)
"""
Stochastic Gradient Descent, which is equivalent to mini-batch gradient descent
where each mini-batch has just 1 example. The update rule will not change. What
changes is that you would be computing gradients on just one training sample
at a time, rather than the whole training set. The code examples below
illustrate the difference between stochastic gradient descent and batch
gradient descent.
"""
X = data_input
Y = labels
parameters = initialize_parameters(layers_dims)
for i in range(0, num_iterations):
for j in range(0, m):
# Forward propagation
a, caches = forward_propagation(X[:,j], parameters)
# Compute cost
cost = compute_cost(a, Y[:,j])
# Backward propagation
grads = backward_propagation(a, caches, parameters)
# Update parameters.
parameters = update_parameters(parameters, grads)
| true |
10e810a9ecdb377e53ef1de86b097a61dc897963 | Overboard/discoverhue | /demo.py | 1,178 | 4.15625 | 4 | """ Demo file of use """
import discoverhue
# Call with no parameter to discover all bridges
# Returns a dictionary of found `serial number: ip address` pairs
print("Searching for any bridges...")
found = discoverhue.find_bridges()
print("Found {}".format(len(found)))
for bridge in found:
print(' Bridge ID {br} at {ip}'.format(br=bridge, ip=found[bridge]))
# Call with a dictionary of `serial number: ip address` pairs
# Will check the provided ip for a bridge matching serial number
# Will attempt discovery if not all bridges were matched
# Returns a dictionary of found `serial number: ip address` pairs
search_id = {'0017884e7dad':'192.168.0.1',
'001788102201':'192.168.0.2'}
print("\nSearching for {s}...".format(s=search_id))
found = discoverhue.find_bridges(search_id)
print("Found {}".format(len(found)))
for bridge in found:
print(' Bridge ID {br} at {ip}'.format(br=bridge, ip=found[bridge]))
# Call with a string representing serial number
# Will discover and return a string of the base ip address
search_id = '0017884e7dad'
print("\nSearching for {s}...".format(s=search_id))
found = discoverhue.find_bridges(search_id)
print(found)
| true |
deb630f8ea5cf08099401ab96d36a2f7369a83e5 | hasanIqbalAnik/interview-prep | /string_operations/reversing_string.py | 481 | 4.1875 | 4 | """
The extended slicing method is much faster than ''.join(reversed(string))
"""
def reverse_string(s):
"""
Python doesn't have the facility to reverse a string in place.
Python strings are immutable. We can use slice operator with negative index.
But that creates a new string.
However, in another universe, we could use bitwise XOR operation to do that.
:param s:
:return: reverted string
"""
return s[::-1]
print reverse_string('asdf')
| true |
e8d72688d1413e41bdd1b34906a50fb73d6b13fd | hasanIqbalAnik/interview-prep | /searching/binary_search.py | 1,543 | 4.375 | 4 | def binary_search_recursive(array, start, end, elem):
"""
Recursive approach for binary search. Uses O(k) extra memory for the stack frames. O(1) for the best case
runtime and O(logn) in the worst case.
:param array: the sorted array to search in
:param start: starting point of the array
:param end: ending point of the array
:param elem: the element to look for
:retrun index: the actual index of the element in the array, or -1 if not found
"""
if start > end:
return -1
if array:
mid = start + (end - start) // 2
if array[mid] == elem:
return mid
elif array[mid] < elem:
start = mid + 1
return binary_search_recursive(array, start, end, elem)
else:
end = mid - 1
return binary_search_recursive(array, start, end, elem)
def binary_search_iterative(array, elem):
"""
Iterative approach for binary search. O(1) extra memory. Runtime is O(logn)
:param array: the sorted array to search in
:param elem: the element to look for
:retrun index: the actual index of the element in the array, or -1 if not found
"""
start = 0
end = len(array) - 1
while start <= end:
mid = start + (end - start) // 2
if array[mid] == elem:
return mid
elif array[mid] < elem:
start = mid + 1
else:
end = mid - 1
return -1
a = [1, 2, 3, 4, 5, 6, 7, 8]
# print binary_search_recursive([], 0, len(a) - 1, 8)
# print binary_search_iterative(a, 5)
| true |
1eb71c4bf1f28d96a0309fed78a09a7cf8a59294 | holleyvoegtle/Election_analysis | /Python_practice.py | 1,488 | 4.4375 | 4 | print("Hello World")
counties = ["Arapahoe", "Denver", "Jefferson"]
if counties[1] == 'Denver':
print(counties[1])
counties = ["Arapahoe", "Denver", "Jefferson"]
if counties[1] == 'Denver':
print(counties[1])
temperature = input("What is the temperature outside")
print(temperature)
if int(temperature) > 80:
print("Turn on the AC")
else:
print("Open the windows")
93
#What is the score?
score = int(input("What is your test score? "))
# Determine the grade.
if score >= 90:
print('Your grade is an A.')
else:
if score >= 80:
print('Your grade is a B.')
else:
if score >= 70:
print('Your grade is a C.')
else:
if score >= 60:
print('Your grade is a D.')
else:
print('Your grade is an F.')
counties = ["Arapahoe","Denver","Jefferson"]
if "El Paso" in counties:
print("El Paso is in the list of counties.")
else:
print("El Paso is not the list of counties.")
if "Arapahoe" in counties and "El Paso" in counties:
print("Arapahoe and El Paso are in the list of counties.")
else:
print("Arapahoe or El Paso is not in the list of counties.")
if "Arapahoe" in counties or "El Paso" in counties:
print("Arapahoe or El Paso is in the list of counties.")
else:
print("Arapahoe and El Paso are not in the list of counties.")
x = 0
while x <= 5:
print(x)
x = x + 1
for county in counties:
print(county)
| true |
35617f1beb6afec9372bb32bd7b1029d752c5d71 | AhmedAbdel-Aal/CSEN703-Algorithms-in-Python | /Divide_and_Conquer/Trailing_Zeroes_in_Factorial.py | 1,429 | 4.46875 | 4 | # to get the number of zeroes in factorial of number we have two methods
# 1- brute force method -> calculate the factorial and count number of zeros
# 2- we count the number of divisions that our number could be divided by the power of 5
# for more info about this method see https://www.geeksforgeeks.org/count-trailing-zeroes-factorial-number/
def TrailingZereo(n):
count=0
i=5
while(n/i>=1):
count+=int(n/i)
i*=5
return int(count)
# the problem statment
# Given an integer n, find the number of positive integers whose factorial ends with n
# zeroes using divide and conquer
def FindNumbers(n):
low = n*4 # a proof why low = n*4 and high = n*5 is attached in file Trailing_Zeroes_in_Factorial_Explain
high = n*5
while(low<high):
mid = (int)((low+high)/2)
k = TrailingZereo(mid)
if(k<n):
low= mid+1
else:
high=mid
# low now is the first number to have n zeroes in its factorial
answer = 0
l = []
while(TrailingZereo(low)==n):
l.append(low)
low+=1
answer+=1 # we can get len(l) in the main function but to show return of more than one value
return answer , l
def main():
a = 250
k , list= FindNumbers(a)
print("there are %d numbers" % k)
print("which are = ",list)
for i in range (len(list)) :
print(TrailingZereo(list[i]))
main() | true |
8565bd99d8649bc0002961bfa44b655976f0b3b8 | arpreading/ISD2014 | /simp_calc.py | 1,599 | 4.21875 | 4 | ##
# Sample calculator program
# areadi01
#
##
# functions
#
def add(firstNumber,secondNumber):
return firstNumber+secondNumber
def subtract(firstNumber,secondNumber):
return firstNumber-secondNumber
def multiply(firstNumber,secondNumber):
return firstNumber*secondNumber
def divide(firstNumber,secondNumber):
return float(firstNumber)/float(secondNumber)
##
#program
#
def main():
while True:
firstNumber = int(input("Please enter the first number to be calculated: "))
secondNumber = int(input("Please enter the second number to be calculated: "))
operator = input("Please enter the action you wish to perform '+,-,/,*': ")
if operator != "+" and operator != "-" and operator != "*" and operator != "/":
print ("Sorry the calculation you have entered is not valid!")
main()
else:
print("You wish to perform: ",firstNumber,operator,secondNumber)
if operator == "+":
print("The answer is: ",add(firstNumber,secondNumber))
elif operator == "-":
print("The answer is: ",subtract(firstNumber,secondNumber))
elif operator == "*":
print("The answer is: ",multiply(firstNumber,secondNumber))
elif operator == "/":
print("The answer is: ",divide(firstNumber,secondNumber))
another_calc = input("Would you like to perform another calculation? yes/no? ")
if another_calc != "yes":
print("Goodbye!")
break
else:
continue
main()
| true |
a775a5a420f5acc9d451861a4ee3c3675b85a59d | barathganesh/ROCK-PAPER-SCISSOR | /RockPaperScissor.py | 1,376 | 4.125 | 4 | """ Rock Paper Scissors
----------------------------------------
"""
import random
import os
import re
os.system('cls' if os.name=='nt' else 'clear')
while (1 < 2):
print ("\n")
print ("Rock, Paper, Scissors - Let's Go!")
userChoice =input("Choose your weapon [R]ock, [P]aper, [S]cissors, or press 'N' to exit: ")
if not re.match("[SsRrPpNn]", userChoice):
print ("Please choose a letter: and enter 'N' to end the game")
print ("[R]ock, [S]cissors or [P]aper.")
continue
if userChoice.upper()=='N':
print("The game ends!")
exit()
# Echo the user's choice
print ("You chose: " + userChoice)
choices = ['R', 'P', 'S']
opponenetChoice = random.choice(choices)
print ("I chose: " + opponenetChoice)
if opponenetChoice == str.upper(userChoice):
print ("It's a Tie! ")
#if opponenetChoice == str("R") and str.upper(userChoice) == "P"
elif opponenetChoice == 'R' and userChoice.upper() == 'S':
print ("Scissors beats rock, I win! ")
continue
elif opponenetChoice == 'S' and userChoice.upper() == 'P':
print ("Scissors beats paper! I win! ")
continue
elif opponenetChoice == 'P' and userChoice.upper() == 'R':
print ("Paper beat rock, I win! ")
continue
else:
print ("You win!")
| false |
4e8a8deee241a2a616eff56505e4624dc8d2ede1 | Lzffancy/Aid_study | /fancy_month01/day12_fancy/day12_teacher/exercise01.py | 1,425 | 4.28125 | 4 | """
练习2:创建图形管理器
1. 记录多种图形(圆形、矩形....)
2. 提供计算总面积的方法.
满足:
开闭原则
测试:
创建图形管理器,存储多个图形对象。
通过图形管理器,调用计算总面积方法.
要求:
画出架构设计图
编码.调试(体会多态)
写出三大特征,设计原则的体现
"""
class GraphicManager:
def __init__(self):
self.__all_graphic = []
def add_graphic(self, graphic):
if isinstance(graphic,Graphic):
self.__all_graphic.append(graphic)
def get_total_area(self):
total_area = 0
for item in self.__all_graphic:
total_area += item.calculate_area()
return total_area
class Graphic:
def calculate_area(self):
pass
# ----------程序员------------
class Rectangle(Graphic):
def __init__(self, l, w):
self.l = l
self.w = w
def calculate_area(self):
return self.l * self.w
class Circle(Graphic):
def __init__(self, r):
self.r = r
def calculate_area(self):
return 3.14 * self.r ** 2
# ----------入口------------
manager = GraphicManager()
manager.add_graphic(Circle(5))
manager.add_graphic(Rectangle(2, 3))
manager.add_graphic("圆形")
print(manager.get_total_area())
| false |
b48bfad4893acf4259175f369c6dce3dced850b4 | Stefanh18/python_projects | /mimir/assingnment_10/q3.py | 546 | 4.1875 | 4 | # Your functions should appear here
def triple_list(a_list):
outcome = a_list * 3
return outcome
def populate_list(a_list):
new = True
while new == True:
user_input = input("Enter value to be added to list: ")
if user_input.lower() == "exit":
new = False
else:
a_list.append(user_input)
return user_input
# Main program starts here - DO NOT change it.
initial_list = []
populate_list(initial_list)
new_list = triple_list(initial_list)
for items in new_list:
print(items)
| true |
b00de0c081c3026c8e0996898bfa7f35f8eb20de | Stefanh18/python_projects | /mimir/assingnment_7/q5.py | 458 | 4.21875 | 4 | # palindrome function definition goes here
def palidrome(sentence):
result = ""
for letter in sentence:
if letter.isalpha():
result += letter
return result.lower()
in_str = input("Enter a string: ")
x = palidrome(in_str)
y = palidrome(in_str)[::-1]
if x == y:
print('"' + in_str + '"',"is a palindrome.")
else:
print('"' + in_str + '"',"is not a palindrome.")
# call the function and print out the appropriate message | true |
fd43def31492d10e913c165d98ea087efcce9510 | Stefanh18/python_projects | /mimir/assingnment_14/q3.py | 1,272 | 4.1875 | 4 | def menu_selection():
print('Menu:')
choice = input('add(a), remove(r), find(f): ')
return choice
def execute_selection(choice, a_dict):
if choice == 'a':
key = input('Key: ')
value = input('Value: ')
if key in a_dict:
print('Error. Key already exists.')
else:
a_dict[key]=value
elif choice == 'r':
key = input('key to remove: ')
if key not in a_dict:
print('No such key exists in the dictionary.')
else:
del a_dict[key]
elif choice == 'f':
key = input('Key to locate: ')
if key not in a_dict:
print('Key not found.')
else:
value = a_dict[key]
print ("Value: ", value)
def dict_to_tuples(a_dict):
dictlist = []
for key,value in a_dict.items():
a_tuple = (key, value)
dictlist.append(a_tuple)
return dictlist
# Do not change this main function
def main():
more = True
a_dict = {}
while more:
choice = menu_selection()
execute_selection(choice, a_dict)
again = input("More (y/n)? ")
more = again.lower() == 'y'
dictlist = dict_to_tuples(a_dict)
print(sorted(dictlist))
main() | true |
e265fdd2997d225e07740e19735e02aabaa203fc | Stefanh18/python_projects | /mimir/assingment_11/q4.py | 537 | 4.1875 | 4 | def get_emails():
list_of_email = []
email = "x"
while email.lower() != "q":
email = input("Email address: ")
list_of_email.append(email)
if email == "q":
list_of_email.pop()
return list_of_email
def get_names_and_domains(email_list):
new_list = [tuple(x.split("@")) for x in email_list]
return new_list
# Main program starts here - DO NOT change it
email_list = get_emails()
print(email_list)
names_and_domains = get_names_and_domains(email_list)
print(names_and_domains) | true |
faf1d11e4ae7057449250f23b532a38cbba118c5 | Stefanh18/python_projects | /prof1/3.py | 753 | 4.46875 | 4 | # To determine whether a year is a leap year, follow these steps:
# 1. If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.
# 2. If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.
# 3. If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.
# 4. The year is a leap year (it has 366 days).
# 5. The year is not a leap year (it has 365 days).
year = int(input("Enter a year: "))
leap_year = "This year is a leap year"
not_leap_year = "This year is not a leap year"
if year % 2 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(leap_year)
else:
print(not_leap_year)
else:
print(leap_year)
else:
print(not_leap_year) | true |
d267542eecd7edb83f1cd5ddc5b5948741dacd84 | bin994622/VIPclass1 | /unittest_test/test_myfun.py | 1,618 | 4.15625 | 4 | """
unittest.main () 方法
设计TestCase测试用例
@classmethod 方法
"""
# 导入unittest包
import unittest
from unittest_test.myfun import *
# 固定写法--测试用例类要继承unittest.TestCase类
class TestMyFun(unittest.TestCase):
# 初始化方法 setUp方法 结束工作方法 tearDown
@classmethod # classmethod 方法
def setUpClass(cls) -> None:
print('setUpClass整个测试用例执行前执行一次')
def setUp(self):
print('setUp每条测试用例执行前执行一次')
# 结束工作方法 tearDown
@classmethod # 类方法
def tearDownClass(cls) -> None:
print('tearDownClass整个测试用例执行后执行一次')
def tearDown(self) ->None:
print('tearDown每条测试用例执行后执行一次')
# 测试用例 方法以test开头
# 加法
def test_add(self):
print('执行测试add方法')
# 使用断言
self.assertEqual(add(1, 2), 3) # add(1,2)为预期结果,3为实际结果,预期结果和实际结果的顺序可以相互变化(实际结果,预期结果)
# 减法
def test_minus(self):
print('执行测试minus方法')
# 使用断言
self.assertEqual(2, minus(5, 3))
# 乘法
def test_multi(self):
print('执行测试multi方法')
# 使用断言
self.assertEqual(multi(2, 3), 6)
# 除法
def test_divide(self):
print('执行测试divide方法')
# 使用断言
self.assertEqual(2, divide(4, 2))
# main方法
if __name__ == 'main':
unittest.main() | false |
8022fe5164da5b20d2c4911bc00618fbee39ced7 | NickMonks/AlgorithmsAndDataStructure | /Node_depth.py | 2,605 | 4.125 | 4 | import unittest
def nodeDepths2(root, depth = 0):
# handle base case
if root is None:
return 0 # why 0? because otherwise it will return NoneType and adding int + None gives a
# Recursive formula: f(n,d) = d + f(l, d+1) + f(r, d+1)
# remember: we use use root.left and root.right but it will be recursively to root.left.left.[...]
return depth + nodeDepths2(root.left, depth + 1) + nodeDepths2(root.right, depth + 1)
# For this solution, an alternative approach is used: we will store
# for each node a hash table (dictonary in python, HashMap in Java)
# of the node itself AND THE DEPTH
# HINT: How to come up with this solution? Simply try to think ; if you need an ordered
# data structure with more than one field, choose a combination of Hash Table + X
# Time: O(n) | Space : O(h) -> if we check the stack, the size it will be roughly the height of the tree
def nodeDepths(root):
sumOfDepths = 0
# For this solution, we will store each node with a dictionary of node and depth
stack = [{"node": root, "depth":0}]
# The approach will be the following:
# - Append each node child: left and right, inside a stack, with the correspondent parent depth +1
# - Extract each time we loop a node with the node and depth:
# * If Node = None , then ignore and don't add the depth (that means it is a leaf)
# * If exists, add the depth
#
# Since we popped the node, it wont iterate more
# WHILE CONDITION: Until the stack length is zero (that means we pop all the possible options)
while len(stack) > 0:
nodeExtract = stack.pop()
node, depth = nodeExtract["node"], nodeExtract["depth"]
if node is None:
continue
sumOfDepths += depth
stack.append({"node": node.left, "depth": depth+1})
stack.append({"node": node.right, "depth": depth+1})
return sumOfDepths
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
#---- UNIT TEST
class TestProgram(unittest.TestCase):
def test_case_1(self):
root = BinaryTree(1)
root.left = BinaryTree(2)
root.left.left = BinaryTree(4)
root.left.left.left = BinaryTree(8)
root.left.left.right = BinaryTree(9)
root.left.right = BinaryTree(5)
root.right = BinaryTree(3)
root.right.left = BinaryTree(6)
root.right.right = BinaryTree(7)
actual = nodeDepths(root)
self.assertEqual(actual, 16)
if __name__=='__main__':
unittest.main() | true |
3856ae220665fe1bdd02e4f2afccf24dcd352ce6 | NickMonks/AlgorithmsAndDataStructure | /MinMaxStack.py | 2,447 | 4.125 | 4 | import unittest
# ----- UNIT TEST SECTION --------
def testMinMaxPeek(self, min, max, peek, stack):
self.assertEqual(stack.getMin(), min)
self.assertEqual(stack.getMax(), max)
self.assertEqual(stack.peek(), peek)
class TestProgram(unittest.TestCase):
def test_case_1(self):
stack = program.MinMaxStack()
stack.push(5)
testMinMaxPeek(self, 5, 5, 5, stack)
stack.push(7)
testMinMaxPeek(self, 5, 7, 7, stack)
stack.push(2)
testMinMaxPeek(self, 2, 7, 2, stack)
self.assertEqual(stack.pop(), 2)
self.assertEqual(stack.pop(), 7)
testMinMaxPeek(self, 5, 5, 5, stack)
# ----- CODE SECTION
class MinMaxStack:
def __init__(self):
# Create an array of MinMax values; this will be stored every time we push
# even if they are the same. when we pop, we will have tracked the reference of this
# values
self.minMaxStack =[]
self.stack =[]
# O(1) time | O(1) space
def peek(self):
return self.stack[len(self.stack)-1]
# O(1) time | O(1) space
def pop(self):
self.minMaxStack.pop()
return self.stack.pop()
# O(1) time | O(1) space
def push(self, number):
# we want to push, not only the new value but also populate
# and push the new element of the minMaxStack. For that, we will first create
# a hash table (a dictionary in Python).
# Then, we create the new MinMax struct/hash table
newMinMax = {"min": number, "max": number}
# Check if the minmaxstack is empty
if len(self.minMaxStack):
lastMinMax = self.minMaxStack[len(self.minMaxStack) -1]
#check the last value of the minMax array and extract min and max
# with python builtin methods.
newMinMax["min"] = min(lastMinMax["min"], number)
newMinMax["max"] = max(lastMinMax["max"], number)
# append the value at the end of the array
self.minMaxStack.append(newMinMax)
self.stack.append(number)
# O(1) time | O(1) space
def getMin(self):
return self.minMaxStack[len(self.minMaxStack)-1]["min"]
# O(1) time | O(1) space
def getMax(self):
return self.minMaxStack[len(self.minMaxStack)-1]["max"]
if __name__ == '__main__':
unittest.main() | true |
426dd843a7739104a2b43f0854b84f0b524ba490 | NickMonks/AlgorithmsAndDataStructure | /Sums-BinaryTree.py | 1,667 | 4.15625 | 4 | import unittest
# ----- CODE ANSWER ----------
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# O (N) Time | O (N) Space
def branchSums(root):
# declare an empty list here (in fact, that's why we create two functions)
# if we had declared this one in the same function we would have problems
sums = []
calculateBranchSums(root, 0, sums)
return sums
def calculateBranchSums(node, runningSum, sums):
if node is None:
return
# sum the node value with the runningSum
# body of the recursion function
newRunningSum = runningSum + node.value
# return conditions
if node.left is None and node.right is None:
sums.append(newRunningSum)
return
calculateBranchSums(node.left, newRunningSum, sums)
calculateBranchSums(node.right, newRunningSum, sums)
class BinaryTree(BinaryTree):
def insert(self, values, i=0):
if i >= len(values):
return
queue = [self]
while len(queue) > 0:
current = queue.pop(0)
if current.left is None:
current.left = BinaryTree(values[i])
break
queue.append(current.left)
if current.right is None:
current.right = BinaryTree(values[i])
break
queue.append(current.right)
self.insert(values, i + 1)
return self
class TestProgram(unittest.TestCase):
def test_case_1(self):
tree = BinaryTree(1).insert([2, 3, 4, 5, 6, 7, 8, 9, 10])
self.assertEqual(branchSums(tree), [15, 16, 18, 10, 11])
if __name__ == '__main__':
unittest.main() | true |
f3c319a5dc5ee8e66f2703a4f0a386e92bbb8d5a | giuliasindoni/Algorithm-runtimes | /insertion_sort.py | 347 | 4.125 | 4 | def insertion_sort(array):
for i in range(len(array)):
tmp = array[i]
j = i - 1
while j >= 0 and tmp < array[j]:
array[j + 1] = array[j]
j = j -1
array[j + 1] = tmp
return(array)
# x = [0, 89, -2, 9, 10]
# example = [-14, 7, 8, 6, -2, -1, -100]
# example2 = [67, 0, -1, 90, 89, 5, 9, 7, 7]
# print(insertion_sort(example))
| false |
b1195e4a360b083eb7a40daf18dd555a1266f01e | ShineVector/Python | /1.py | 1,191 | 4.21875 | 4 |
#intenger
#number = 5
#float
#fnumber = 5.7
#string
#name = "Kukyeong"
#bool
#status = True #False
#age = 27
# можно писать всё что угодно
# Экранирование
#print("hello,\n world")
#Конкатенация
#print ("Hello, my name is " + name + "!")
#print("I'm " + str(age))
#name = input("your name: ")
#age = input("your age: ")
#print("Hello, " + name + "!")
#print("your are already " + age)
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enler choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
# +, -, *, /,**,%
| false |
a845828a6c8730c335d103fecfc18e00d27d9860 | Pwojton/python | /nauka/12-funkcje.py | 597 | 4.1875 | 4 | countries_information = {}
countries_information["Polska"] = ("Warszawa", 37.97)
countries_information["Niemcy"] = ("Berlin", 83.02)
countries_information["Słowacja"] = ("Bratysława", 5.45)
for country in countries_information.keys():
print(country)
def show_country_info(country):
country_information = countries_information.get(country)
print()
print(country)
print("Stolica: " + country_information[0])
print("Liczba mieszakńców (mln): " + str(country_information[1]))
country = input("Informacje o jakim kraju chcesz wyświetlić")
show_country_info(country)
| false |
dfde0296d3f08b60a9d1fe0f12e60d2d68490cfd | ITanmayee/Project_Euler | /PE_14.py | 1,144 | 4.28125 | 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?
def generate_collatz_sequence(num) :
collatz = []
while num != 1 :
if num % 2 == 0:
collatz.append(num)
num = (num // 2)
else :
collatz.append(num)
num = (3 * num) + 1
return collatz
def get_length_of_collatz_sequence(num) :
collatz_sequence = generate_collatz_sequence(num)
return len(collatz_sequence) + 1 # 1 is added to the length because 1 is excluded from the sequence
lengths_of_collatz_sequence = [(get_length_of_collatz_sequence(i) , i) for i in range(2, 1000000) ]
print(max(lengths_of_collatz_sequence))
| true |
dce83215201ea694334b17c44c8f4d3340c27d0c | MattMannix/Python-Lessons | /AreaCalc.py | 1,617 | 4.375 | 4 | ###Something to do with calculating the area of a shape using maths stuffs###
from math import pi
from time import sleep
from datetime import datetime
now = datetime.now()
print "Calculation commencing ..."
print "Current Time: %.2d/%.2d/%.2d %.2d:%.2d" % (now.month, now.day, now.year, now.hour, now.minute)
sleep (1)
hint = "Don't forget to include the correct units! \nExiting..."
option = raw_input("\nEnter C for Circle, R for Rectangle, S for Square or T for Triangle, then hit <Enter>: ")
option = option.upper()
if option == "C":
radius = float(raw_input("Please provide the radius of the circle: "))
area = pi * (radius * radius)
print "The pie is baking...\n"
sleep(1)
print "The area of the circle is %.2f \n\n%s" % (area, hint)
elif option == "T":
base = float(raw_input("Please provide the base of the triangle: "))
height = float(raw_input("Provide the height of the triangle: "))
area = base * height / 2
print "Uni Bi Tri...\n"
sleep(1)
print "The area of the triangle is %.2f \n\n%s" % (area, hint)
elif option == "S":
height = float(raw_input("Provide the height of the square: "))
area = height * height
print "Ensquaring...\n"
sleep(1)
print "The area of the square is %.2f \n\n%s" % (area, hint)
elif option == "R":
width = float(raw_input("Provide the width of the rectangle: "))
length = float(raw_input("Provide the length of the rectangle: "))
area = width * length
print "Juan Toe Free...\n"
sleep(1)
print "The area of the rectangle is %.2f \n\n%s" % (area, hint)
else:
print "You have entered an invalid value. The program will exit."
| true |
90faec5baaa5a0ebd230c6db2eef2aae967a6d2c | sunkaiiii/study_computer_science | /Learn_Python/Python基础教程(第三版)/Chapter4/dict.py | 760 | 4.21875 | 4 | from copy import deepcopy
# 函数dict
items = [('name','gumby'),('age',42)]
d = dict(items) # 从list当中映射
print(d)
# 将字符串格式设置功能用于字典
print("The name is {name}".format_map(d))
# 字典的copy是浅复制
# 当替换里面的值时候,原件不受影响。然而,如果是修改副本中值,原件也将发生变化
d['classmate'] = ['bob','dylan']
d2 = d.copy()
d3 = deepcopy(d)
d3['classmate'].append("tom")
d2['classmate'].append('harry')
print(d)
print(d3)
# 按照key 创建字典
print({}.fromkeys(['bob','tom']))
print({}.fromkeys(['bob','tom','jerry'],'noname'))
d = {}.fromkeys(['bob','tom','jerry'],'noname')
d2 = {"bob":"bob","tom":"tom"}
d.update(d2) # 使用一个字典的项来更新字典
print(d)
| false |
a9ebb67a857bb356d4921b747de6d5a1093bb8a5 | fisher0251/RPi-ledmulti | /displayexample.py | 908 | 4.1875 | 4 | # displayexample.py
# Example program showing how to use the ledmulti library functions
# Dan Fisher, 2014-01-10
# updated 2014-01-15
import ledmulti as led
import time
import RPi.GPIO as GPIO
# Displays a number for display time in seconds, with up to 3 decimal places
# Segments all go off after display time is complete
# Example: display(number,decimals,display_time)
led.display(1234,0,3)
time.sleep(1)
led.display(432.1,1,3)
time.sleep(1)
led.display(2.12345,3,3)
time.sleep(1)
# Counting up from 0 to 100. Notice there is no need for a delay
# between displays since the display() function is timed already
for i in range(101):
led.display(i,0,0.1)
time.sleep(1)
# Numbers that are too high default to 9999, and numbers that
# are too low (negative) default to 0
led.display(12500.55,2,3)
led.display(-500,0,3)
# Good to do at the end of your program to shut off all the GPIO
# pins
GPIO.cleanup()
| true |
cd1b080219772bdd59b45cfe78991615b443fa5d | bootkernel/Interview-Questions | /findMissingNumberinArray.py | 1,531 | 4.5625 | 5 | # Defining the Missing Number Function
def FindMissing(array):
n = len(array) + 1 # Knowing that there are 5 elements. So, we just add
# 1 to whatever the given array length
given_n = len(array) # Length of given array
# Print the number of elements including the missing number
print("Number of Elements including the missing number in the main array, n =", n)
# The formula for adding all the elements in an Array including missing number (Arithmetic Progression)
main_array = n * (n+1) / 2
# Sum of all elements in the given array
sum_of_all_elements_in_array = sum(array)
print("Number of Elements in the given array, n =", given_n)
print("Sum of all elements in the main array including the missing number =", main_array)
print("Sum of all elements in the given array =", sum_of_all_elements_in_array)
# Returning the differece between the main_array and the given array will give us the missing number
return main_array - sum_of_all_elements_in_array
# Testing with an array
array = [1, 3, 5, 2]
print("Given Array =", array)
result = FindMissing(array)
print("Number", result, "is missing from the array.")
# Output
# Given Array = [1, 3, 5, 2]
# Number of Elements including the missing number in the main array, n = 5
# Number of Elements in the given array, n = 4
# Sum of all elements in the main array including the missing number = 15.0
# Sum of all elements in the given array = 11
# Number 4.0 is missing from the array.
| true |
d194c8ce90df90c6a5992a7679bb1395c91bdb97 | nramanath/Interactive-Programming-in-Python | /Scripts/PyScript3_GuessTheNumberName.py | 1,783 | 4.21875 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
num_range = 100
secret_number = 0
remaining_guesses = 7
# helper function to start and restart the game
def new_game():
global secret_number, num_range, remaining_guesses
if(num_range == 100):
remaining_guesses = 7
else:
remaining_guesses = 10
print ""
print "New Game. Range is from 0 to",num_range
secret_number = random.randrange(num_range)
print "Number of remaining guesses is",remaining_guesses
def reduce_guess():
global remaining_guesses, secret_number
remaining_guesses = remaining_guesses - 1
print "Number of remaining guesses is",remaining_guesses
def range100():
global num_range
num_range = 100
new_game()
def range1000():
global num_range
num_range = 1000
new_game()
def input_guess(guess):
global secret_number, num_range, remaining_guesses
result = ""
print ""
print "Guess was", guess
guess = float(guess)
reduce_guess()
if(guess == secret_number):
result = "Correct!"
elif(guess > secret_number):
result = "Higher"
else:
result = "Lower"
print result
if(result == "Correct!"):
new_game()
if(remaining_guesses == 0):
print "You ran out of guesses ! ! ! The number was", secret_number
new_game()
# creating frame
f = simplegui.create_frame("Guess the number",200,200)
# registering event handlers for control elements and start frame
f.add_button("Range is [0,100)", range100, 200)
f.add_button("Range is [0,1000)", range1000, 200)
f.add_input("Enter a guess", input_guess, 200)
new_game()
| true |
0237f3d030486b9106615d00c62f658e8dc2942b | Madongmingming/CodeWars-Python | /10. Valid Parentheses/valid_parenthese.py | 1,205 | 4.46875 | 4 | def valid_parentheses(string):
# your code here
if not string:
return True
else:
stack = []
for char in string:
if char == '(':
stack.append('(')
elif char == ')':
if not stack:
return False
else:
stack.pop()
else:
continue
if not stack:
return True
else:
return False
print(valid_parentheses(" ("))
print(valid_parentheses(")test"))
print(valid_parentheses(""))
print(valid_parentheses("hi())("))
print(valid_parentheses("hi(hi)()"))
# Write a function called validParentheses that takes a string of
# parentheses, and determines if the order of the parentheses is valid.
# validParentheses should return true if the string is valid, and false if
# it's invalid.
# Examples:
# validParentheses( "()" ) => returns true
# validParentheses( ")(()))" ) => returns false
# validParentheses( "(" ) => returns false
# validParentheses( "(())((()())())" ) => returns true
# All input strings will be nonempty, and will only consist of open
# parentheses '(' and/or closed parentheses ')'
| true |
3c661fb4696b27fabf6e2bb66200423968e3e2f9 | JayMackay/PythonCodingFundamentals | /[Session 1] Basic Syntax & String Manipulation/[3] While Loops/08 while.py | 233 | 4.1875 | 4 | # while statement
i = 1
while i < 6:
print(i)
i = i + 1
# A variable is initialised.
# It is tested in the while condition.
# It is updated near the end of the while's body.
# This is a very common pattern for while loops.
| true |
6a45c5619f577cbd8ced4c0e6d32c325c2bea436 | JayMackay/PythonCodingFundamentals | /[Session 2] File Handling/File Handling Application/by_last_first alt ifs.py | 1,199 | 4.21875 | 4 | import csv
from operator import itemgetter
from pprint import pprint
def csv_to_list_of_dicts(csv_file_to_convert):
"""Convert a CSV file to a list of dictionaries.
"""
list_of_dicts = []
with open(csv_file_to_convert) as csv_file:
csv_reader = csv.DictReader(csv_file)
for line in csv_reader:
list_of_dicts.append(line)
return list_of_dicts
# Read in CSV file
player_list = csv_to_list_of_dicts("women_tennis_players.csv")
# Multilevel sort by Last Name then First Name
players_by_firstname = sorted(player_list, key=itemgetter("First Name"))
players_by_last_first = sorted(players_by_firstname, key=itemgetter("Last Name"))
# Display result
for player in players_by_last_first:
# This is called a conditional expression or ternary operator
retired = player["Retired"] if player["Retired"] else "Present"
print(
f"{player['First Name']} {player['Last Name']}: "
f"{player['Turned Pro']} - {retired}"
)
for player in players_by_last_first:
retired = player["Retired"] or "Present"
print(
f"{player['First Name']} {player['Last Name']}: "
f"{player['Turned Pro']} - {retired}"
)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.