blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
21964a6a9150ffc373599207402aef774f5917a8 | rarezhang/ucberkeley_cs61a | /lecture/l10_data_abstraction.py | 1,233 | 4.4375 | 4 | """
lecture 10
Data Abstraction
"""
# data
print(type(1))
## <class 'int'> --> represents int exactly
print(type(2.2))
## <class 'float'> --> represents real numbers approximately eg. 0.2222222222222222 == 0.2222222222222227 True
print(type(1+1j))
## <class 'complex'>
print(type(True))
## <class 'bool'>
print(1+1.2)... | true |
efd57652ea766f2eead4561e8d9737163de0ef8a | cIvanrc/problems | /ruby_and_python/2_condition_and_loop/check_pass.py | 905 | 4.1875 | 4 | # Write a Python program to check the validity of a password (input from users).
# Validation :
# At least 1 letter between [a-z] and 1 letter between [A-Z].
# At least 1 number between [0-9].
# At least 1 character from [$#@].
# Minimum length 6 characters.
# Maximum length 16 characters.
# Input
# W3r@100a
# Output
#... | true |
74d1f20b9a008084b1200a73a16d6e7d79866db0 | cIvanrc/problems | /ruby_and_python/8_math/binary_to_decimal.py | 484 | 4.40625 | 4 | # Write a python program to convert a binary number to a decimal number
class Convert():
def binary_to_decimal(self):
binary_num = list(input("Input a binary number: "))
value = 0
len_binary_num = len(binary_num)
for i in range(len_binary_num):
digit = binary_num.pop... | false |
5ca2ba498860e710f44477f96523c0413ed54cbe | cIvanrc/problems | /ruby_and_python/12_sort/merge_sort.py | 1,497 | 4.40625 | 4 | # Write a python program to sort a list of elements using the merge sort algorithm
# Note: According to Wikipedia "Merge sort (also commonly spelled mergesort) is an 0 (n log n)
# comparasion-baed sortgin algorithm. Most implementations produce a stable sort, which means that
# the implementation preserves the input or... | true |
68456f7fa3638ae327fc6874c22b74099b28f351 | cIvanrc/problems | /ruby_and_python/3_list/find_max.py | 648 | 4.28125 | 4 | # Write a Python program to get the smallest number from a list.
# max_num_in_list([1, 2, -8, 0])
# return 2
def find_max():
n = int(input("How many elements you will set?: "))
num_list = get_list(n)
print(get_max_on_list(num_list))
def get_list(n):
numbers = []
for i in range(1, n+1):
... | true |
9600319f92cf09f3eef5ec5e5cdfbe80c2c8e81a | asingleservingfriend/PracticeFiles | /regExpressions.py | 1,796 | 4.125 | 4 | import re
l = "Beautiful is better than ugly"
matches = re.findall("beautiful", l, re.IGNORECASE)
#print(matches)
#MATCH MULTIPLE CHARACTERS
string = "Two too"
m = re.findall("t[wo]o", string, re.IGNORECASE)
#print(m)
#MATCH DIGITS
line = "123?34 hello?"
d = re.findall("\d", line, re.IGNORECAS... | true |
10a1d131ff6eb33d0f12d8aa67b3e9fd93e05153 | christianmconroy/Georgetown-Coursework | /ProgrammingStats/Week 8 - Introduction to Python/myfunctions.py | 2,006 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 07 18:33:25 2018
@author: chris
"""
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 07 18:29:10 2018
@author: chris
"""
# refer slide 41
# Program with functions
# Name this program withfunctions.py
# the entire program; there is one small change
# that small change is ... | true |
3608552cce91138d629a3ad9cb2208b2b8f15b2f | Latoslo/day-3-3-exercise | /main.py | 617 | 4.1875 | 4 | # 🚨 Don't change the code below 👇
year = int(input("Which year do you want to check? "))
# 🚨 Don't change the code above 👆
# > `on every year that is evenly divisible by 4
# > **except** every year that is evenly divisible by 100
# > **unless** the year is also evenly divisible by 400`
#Write your code below... | true |
80b2020aeabd82d5390c8ef044523e6d3fb616c4 | shubhamkanade/all_language_programs | /Evenfactorial.py | 363 | 4.28125 | 4 | def Evenfactorial(number):
fact = 1
while(number != 0):
if(number % 2 == 0):
fact = fact * number
number -= 2
else:
number = number-1
return fact
number = int(input("Enter a number"))
result = Evenfactorial(... | true |
e0461c90da83c9b948352e729a91c80b24ed2817 | shubhamkanade/all_language_programs | /checkpalindrome.py | 460 | 4.21875 | 4 | import reverse
def checkpalindrome(number):
result = reverse.Reverse_number(number)
if(result == number):
return True
else:
return False
def main():
number = int(input("Enter a number\n"))
if(checkpalindrome(number)== True):
print(... | true |
a1a1c971e1fa7008b457aa67d8d784b054f0b671 | workwithfattyfingers/testPython | /first_project/exercise3.py | 553 | 4.40625 | 4 | # Take 2 inputs from the user
# 1) user name
# 2) any letter from user which we can count in SyntaxWarning
# OUTPUT
# 1) user's name in length
# 2) count the number of character that user inputed
user_name=input(print("Please enter any name"))
char_count=input(print("Please enter any character which you want to coun... | true |
8ca6c553c9d2fcf7d142b730e5b455a781cf22da | Phone5mm/MDP-NTU | /Y2/SS/MDP/NanoCar (Final Code)/hamiltonianPath.py | 2,928 | 4.125 | 4 | # stores the vertices in the graph
vertices = []
# stores the number of vertices in the graph
vertices_no = 0
graph = []
#Calculate Distance
def distance(p1, p2):
return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) ** 0.5
#Add vertex to graph
def add_vertex(v):
global graph
global vertices_no
global vertices
... | true |
863817a9ec431234468b53402deaccd657227c15 | brianabaker/girlswhocode-SIP2018-facebookHQ | /data/tweet-visualize/data_vis_project_part4.py | 2,586 | 4.25 | 4 | '''
In this program, we will generate a three word clouds from tweet data.
One for positive tweets, one for negative, and one for neutral tweets.
For students who finish this part of the program quickly,
they might try it on the larger JSON file to see how much longer that takes.
They might also want to try subjective... | true |
f0e1863b39362db65c98698eff2b6c7150984475 | G-Radhika/PythonInterviewCodingQuiestions | /q5.py | 1,469 | 4.21875 | 4 | """
Find the element in a singly linked list that's m elements from the end.
For example, if a linked list has 5 elements, the 3rd element from the end is
the 3rd element. The function definition should look like question5(ll, m),
where ll is the first node of a linked list and m is the "mth number from the
end". You s... | true |
6ed2cd27f06b2bb4f00f0b14afd94e42e7173164 | MichaelAuditore/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 706 | 4.40625 | 4 | #!/usr/bin/python3
def add_integer(a, b=98):
"""
Add_integer functions return the sum of two numbers
Parameters:
a: first argument can be integer or float
b: Second argument initialized with value 98, can be integer or float
Raises:
TypeError: a must be an integer or float
... | true |
a30bd99e44e61f3223dfa2ba64adb89dc19ad0b2 | Debu381/Conditional-Statement-Python-Program | /Conditional Statement Python Program/Guss.py | 213 | 4.125 | 4 | #write a python program to guess a number between 1 to 9
import random
target_num, guess_num=random.randint(1,10), 0
while target_num !=guess_num:
guess_num=int(input('Guess a number'))
print('Well guessed') | true |
b6ace974b9b55f653fe3c45d35a1c76fd3322f7e | lucasloo/leetcodepy | /solutions/36ValidSudoku.py | 1,530 | 4.1875 | 4 | # 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 ce... | true |
98c092348ce916622847924b48967ef75ce99d9e | SaralKumarKaviti/Problem-Solving-in-Python | /Day-3/unit_convert.py | 1,738 | 4.25 | 4 | print("Select your respective units...")
print("1.centimetre")
print("2.metre")
print("3.millimetre")
print("4.kilometre")
choice= input("Enter choice(1/2/3/4)"
unit1=input("Enter units from converting:")
unit2=input("Enter units to coverting:")
number=float(input("Enter value:"))
if choice == '1':
if unit1 == 'c... | true |
e49dd0973443fb86684f5ef112091382d7afa607 | ClaudiaSianga/Python-para-Zumbis | /Lista3/exercicio03_guilhermelouro_01.py | 404 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor
seja inválido e continue pedindo até que o usuário informe um valor válido.
"""
nota = ""
while nota < 0 or nota > 10:
nota = float(input("Digite uma nota de 0 a 10: "))
print "... | false |
2d082dda2f464f6da9d9a043a90ca7599a4b92bd | anikanastarin/Learning-python | /Homework session 4.py | 1,516 | 4.375 | 4 | '''#1. Write a function to print out numbers in a range.Input = my_range(2, 6)Output = 2, 3, 4, 5, 6
def my_range(a,b):
for c in range(a,b+1):
print (c)
my_range(2,6)
#2. Now make a default parameter for “difference” in the previous function and set it to 1. When the difference value is passed, the d... | true |
6ae607ac50b7fe370e6257fd083fc369a5ac7a14 | Dcnqukin/A_Byte_of_Python | /while.py | 383 | 4.15625 | 4 | number=23
running=True
while running:
guess=int(input("Enter an integer:"))
if guess==number:
print("Congratulation, you guessd it.")
running=False #this causes the while loop to stop
elif guess<number:
print("No, it is a little higher")
else:
print("No, it is a little l... | true |
b5cf0e1ec9d8ad7f5f60e89891ee08ef6e3bc6f9 | marieramsay/IT-1113 | /Miles_To_Kilometers_Converter.py | 2,618 | 4.5625 | 5 | # Marie Ramsay
# Prompts the user to select whether they want to convert Miles-to-Kilometers or Kilometers-to-Miles, then asks the user
# to enter the distance they wish to convert. Program converts value to the desired unit.
# Program will loop 15x.
import sys
# converts input from miles to kilometers
def... | true |
e07ac75e79a257241d4a467320e113247db4df8b | calebwest/OpticsPrograms | /Computer_Problem_2.py | 2,211 | 4.40625 | 4 | # AUTHOR: Caleb Hoffman
# CLASS: Optics and Photonics
# ASSIGNMENT: Computer Problem 2
# REMARKS: Enter a value for the incident angle on a thin lens of 2.0cm, and
# the focal length. A plot will open in a seperate window, which will display
# light striking a thin lens, and the resulting output rays. This program use... | true |
756a096e6c156f1f5be7347067903a3135008535 | 22fansje/python | /modb_challenge.py | 1,034 | 4.21875 | 4 | def main():
#Get's info on the user's name than greets them
first_name = input("What is your first name?: ")
last_name = input("What is your last name?: ")
print("Hello, %s %s!"%(first_name,last_name))
print()
#Lists the foods avaliable
food = ['Cookie', 'Steak', 'Ice cream', 'Apples']
... | true |
7f6071b0aa4ea291a567a7f766ffaef00349e373 | geronimo0630/2021 | /clases/operaciones.py | 683 | 4.15625 | 4 | # se utilizan dos int y se les da un valor designado
numeroA = 87
numeroB = 83
#se suman los int
sumar = numeroA + numeroB
#pone en pantalla el resultado
print ("el resultado es", sumar)
#se restan los int
restar = numeroA - numeroB
#pone en pantalla el resultado
print ("el resultado es ",restar)
#se multiplican lo... | false |
6fd29cfa6d3667c2316c0322e35451ee9bfeefc2 | dwlovelife/Python-Note | /code/basic/day05/test02.py | 249 | 4.1875 | 4 | def factorial(num):
"""
求阶乘
"""
result = 1
for x in range(1, num + 1):
result *= x
return result
m = int(input("请输入m:"))
n = int(input("请输入n:"))
print(factorial(m)//factorial(n)//(factorial(m - n))) | false |
acf5f7ff2b563f54375c5dbfeb24294d6673f2f8 | dwlovelife/Python-Note | /code/basic/day07/test04.py | 262 | 4.15625 | 4 | """
集合切片
"""
def main():
list = [1, 2, 3, 4]
list.append(5)
for x in list:
print(x, end = " ")
print()
list2 = list[2:4]
print(list2)
list3 = list[::-1]
print(list3)
if __name__ == "__main__":
main()
| false |
88222260f53d9cf84b52f5c4c74cf85ebafb8b82 | harry990/coding-exercises | /strings/generate-all-permutations-of-a-string.py | 534 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "David S. Batista"
__email__ = "dsbatista@inesc-id.pt"
"""
- Generate a list of all permutation of a string
"""
def permute(s):
res = []
if len(s) == 1:
res = [s]
else:
for i, c in enumerate(s):
for perm in permute(s[... | false |
19eb4be275bd3a0477a42ec205be2596a5c459db | harry990/coding-exercises | /trees/tree-string-expression-balanced-parenthesis.py | 1,107 | 4.15625 | 4 |
from collections import defaultdict
"""
Given a tree string expression in balanced parenthesis format:
(A(B(C)(D))(E)(F))
A
/ | \
B E F
/ \
C D
The function is to return the root of the tree you build, and if you can please
print the tree with indent... | true |
1c90e6c43a74e92dc37477692317ae008d9ec415 | btrif/Python_dev_repo | /Courses, Trainings, Books & Exams/Lynda - Python 3 Essential Training/11 Functions/generator_01_sequence_tuple_with_yield.py | 1,411 | 4.59375 | 5 | #!/usr/bin/python3
# A generator function is function that return an iterator object.
# So this is how you create functionality that can be used in a for loop or any
# place an iterator is allowable in Python
def main():
print("This is the functions.py file.")
for i in inclusive_range(2, 125, 4): ... | true |
89c5785788e5171d33ef0e2cc34622b8781004af | btrif/Python_dev_repo | /BASE SCRIPTS/Logic/basic_primes_generator.py | 980 | 4.125 | 4 | #!/usr/bin/python3
# comments.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
for n in primes(): #generate a list of prime numbers
if n > 100: break
print(n, end=' ')
def isprime... | true |
6c9a13d67dea2ce2672fc0dad170207bdfce715f | btrif/Python_dev_repo | /BASE SCRIPTS/module bisect pickle.py | 2,002 | 4.46875 | 4 | import bisect, pickle
print(dir(bisect))
########################
# The bisect() function can be useful for numeric table lookups.
# This example uses bisect() to look up a letter grade for an exam score (say)
# based on a set of ordered numeric breakpoints: 90 and up is an ‘A’, 80 to 89 is a ‘B’, and so on:
def gr... | true |
2dbae09466384658d5906425b8aeb6095495ac1a | btrif/Python_dev_repo | /BASE SCRIPTS/searching.py | 1,535 | 4.75 | 5 | # ### Python: Searching for a string within a list – List comprehension
# The simple way to search for a string in a list is just to use ‘if string in list’. eg:
list = ['a cat','a dog','a yacht']
string='a cat'
if string in list:
print ('found a cat!')
# But what if you need to search for just ‘cat’ or some oth... | true |
a42127989a11eabe0a112f58ec1e6ca0a4be9bcd | btrif/Python_dev_repo | /BASE SCRIPTS/OOP/static_variables.py | 2,037 | 4.5 | 4 | # Created by Bogdan Trif on 17-07-2018 , 3:34 PM.
# I noticed that in Python, people initialize their class attributes in two different ways.
# The first way is like this:
class MyClass:
__element1 = 123 # static element, it means, they belong to the class
__element2 = "this is Africa"... | true |
0b4eae1855d2a62e6152419526c4f49d08c1085d | btrif/Python_dev_repo | /Courses, Trainings, Books & Exams/EDX - MIT - Introduction to Comp Science I/bank_credit_account.py | 844 | 4.65625 | 5 | '''
It simulates a credit bank account. Suppose you have a credit. You pay each month a monthlyPaymentRate
and each month an annualInterestRate is calculated for the remaining money resulting in a remaining balance
each month.
'''
balance = 5000 # Balance
monthlyPaymentRate = 2/100 # Monthly payment rate... | true |
d8cd80845a11d5a6c9f469729cc42f3cf6f5a978 | btrif/Python_dev_repo | /BASE SCRIPTS/object_types_conversion.py | 2,527 | 4.125 | 4 | print('----------'*13)
print('........................Function which transforms a string into a list: ....................')
def string_to_list(strng):
if (type(strng) == str):
lst = list(strng)
print(lst)
print('The type of ',lst, 'is : ',type(lst))
return lst
else: print('Not a stri... | false |
53958a00677713402c549640639d87442b94d9d2 | btrif/Python_dev_repo | /plots exercises/line_animation.py | 1,087 | 4.40625 | 4 | __author__ = 'trifb' #2014-12-19
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure() #defining the figure
ax = plt.axes(xlim=(0, 10), ylim=(-8, 8)) # x-axes limit... | true |
24e78bf77cad25af185baf4fd71d6953e86620c7 | fransikaz/PIE_ASSIGNMENTS | /homework8.py | 2,880 | 4.5 | 4 | import os
# import os.path
from os import path
'''
HOMEWORK #8:
Create a note-taking program. When a user starts it up, it should prompt them for a filename.
If they enter a file name that doesn't exist, it should prompt them to enter the text they want to write to the file.
After they enter the text, it should ... | true |
d20f44d4150c21a96b178b3aac74b45e25c5fab1 | AndersenDanmark/udacity | /test.py | 2,516 | 4.5 | 4 | def nextDay(year, month, day):
"""
Returns the year, month, day of the next day.
Simple version: assume every month has 30 days.
"""
# YOUR CODE HERE
if day+1>30:
day=1
if month+1>12:
month=1
year=year+1
else:
month=month+... | true |
14389832de4c1e1317bd88f01b2686a83eb36017 | KeelyC0d3s/L3arning | /squareroot.py | 1,126 | 4.375 | 4 | # Keely's homework again.
# Please enter a positive number: 14.5
# The square root of 14.5 is approx. 3.8.
# Now, time to figure out how to get the square root of 14.5
#import math
#math.sqrt(14.5)
#print( "math.sqrt(14.5)", math.sqrt(14.5))
#Trying Newton Method.
#Found code here: https://tinyurl.com/v9ob6nm
# Fu... | true |
dad8ce6b3d20dff1ffcaef7146ecfbd88c3b54b0 | adarshk007/DATA-STURCTURES-and-ALGORITHMS | /DATA STRUCTURE/QUEUE/queue_all.py | 886 | 4.15625 | 4 | # QUEUE
#SUB TOPICS :
"""
1}Enqueue
2}Dequeue
3}Print: rear element
front element
"""
# ADARSH KUMAR
#__________________________________CODE________________________________________#
class queue:
def __init__(self):
self.new_queue=[]
self.size=0
self.f... | false |
8aaf6cd5b8634dfdcd5a6e6923dbea448100b983 | carlanlinux/PythonBasics | /9/9.6_ClonningLists.py | 418 | 4.25 | 4 | '''
If we want to modify a list and also keep a copy of the original, we need to be able to make a copy of the
list itself, not just the reference. This process is sometimes called cloning, to avoid the ambiguity of
the word copy.
The easiest way to clone a list is to use the slice operator.
'''
a = [81,82,83]
... | true |
ce9a774c06363afc1f03da671d9276d5ae11b758 | MalteMagnussen/PythonProjects | /week2/objectOriented/Book.py | 974 | 4.21875 | 4 | from PythonProjects.week2.objectOriented import Chapter
class Book():
"""A simple book model consisting of chapters, which in
turn consist of paragraphs."""
def __init__(self, title, author, chapters=[]):
"""Initialize title, the author, and the chapters."""
self.title = title
se... | true |
0c209da23bd3717cad46e0bb0ad8d2e5401c177b | ReWKing/StarttoPython | /操作列表/创建数值列表/numbers.py | 208 | 4.34375 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
# Author:William Gin
# 使用函数range()
for value in range(1, 5):
print(value)
# 使用函数range()创建数字列表
numbers = list(range(1, 6))
print(numbers)
| false |
3e31f087d0703727310e782ad61f60682fc50d2a | tizziana/GrafoMundial | /pruebas/heap.py | 2,062 | 4.1875 | 4 |
# -------------------------------------------------------------------
# PRIMITIVAS DEL HEAP |
# -------------------------------------------------------------------
class Heap:
"""Representa un heap de min con operaciones de encolar, desencolar,
ver_maximo, cantidad y verificar si está vacio."""
def __... | false |
875bc855207b37cedee6c9799951afcb63b2bf5f | JohnEstebanAP/FundamentosProgramacionPython | /Sesión1/sesion1.py | 1,894 | 4.46875 | 4 | #Instrucciones, Variables, y Operaciones Matemáticas
#Comencemos por lo más sencillo...
# Recuerda que programar significa
# darle instrucciones al computador
# para que haga lo que yo quiera.
# Podemos comenzar por pedirle que
# imprima algo para nosotros:
print("¡Hola soy john!")
print("\n")
# Para asignarle... | false |
fdde0b3b81e7987289e4134ff4a523f5b6544587 | saurabh-pandey/AlgoAndDS | /leetcode/binary_search/sqrt.py | 1,075 | 4.25 | 4 | #URL: https://leetcode.com/explore/learn/card/binary-search/125/template-i/950/
#Description
"""
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of
the result is returned.
Note: You are not allowed... | true |
7ff689c4e4d6f95ad27413579ee15919eee29e15 | saurabh-pandey/AlgoAndDS | /leetcode/bst/sorted_arr_to_bst.py | 1,129 | 4.25 | 4 | #URL: https://leetcode.com/explore/learn/card/introduction-to-data-structure-binary-search-tree/143/appendix-height-balanced-bst/1015/
#Description
"""
Given an integer array nums where the elements are sorted in ascending order, convert it to a
height-balanced binary search tree.
A height-balanced binary tree is a bi... | true |
c5361ad406f3da27f7960150fb6afbd44bbae03e | saurabh-pandey/AlgoAndDS | /leetcode/queue_stack/stack/target_sum.py | 2,326 | 4.1875 | 4 | #URL: https://leetcode.com/explore/learn/card/queue-stack/232/practical-application-stack/1389/
#Description
"""
You are given an integer array nums and an integer target.
You want to build an expression out of nums by adding one of the symbols '+' and '-' before each
integer in nums and then concatenate all the integ... | true |
72d27e13ba30f9d65f0e0b4e105389f80d2fcd03 | loolu/python | /CharacterString.py | 830 | 4.15625 | 4 | #使用字符串
#字符串不可改变,不可给元素赋值,也不能切片赋值
website = 'http://www.python.org'
website[-3] = 'com'
#
format = "Hello, %s. %s enough for ya?"
values = ('world', 'hot')
print(format % values)
from string import Template
tmpl = Template("Hello, $who! $what enough for ya?")
print(tmpl.substitute(who='Mars', what='Dusty'))
print("{}... | true |
61bb1f7871db613627d1edd50128a7c5c88d0b4b | Stemist/BudCalc | /BudgetCalculatorCLI.py | 1,577 | 4.28125 | 4 | #!/usr/bin/env python3
people = []
class Person:
def __init__(self, name, income):
self._name = name
self._income = income
self.products = {}
def add_product():
try:
product = str(input("Enter product name: "))
cost = float(input("Enter product cost ($): "))
products[product] = price
except:... | true |
36d1d6f8060a6e7dcdf58b48b12bfea2396d6023 | joshrili/rili | /cpt_05.py | 1,662 | 4.15625 | 4 | '''
Description: python code, exercises of chapter 5, python crash course
Author: joshrili
Date: 2020-03-22
'''
cars = ['audi', 'bmw', 'subaru', 'toyota']
print(cars)
for car in cars :
if car == 'bmw' :
print(car.upper())
print('I like ' + car.upper() + '\n')
else :
print... | false |
4b67eb4c4a802e7980142f6a8ee644f1bda6d867 | huyilong/python-learning | /fibo_module.py | 720 | 4.25 | 4 | #fibonacci numbers module
#could directly input python3 on mac terminal to invoke version 3
def fib(n):
a, b = 0, 1
while b < n:
print( b),
#there is a trailing comma "," after the print to indicate not print output a new line
a, b = b, a+b
print #this is print out a empty line
#if you use print() then it... | true |
6d70e720d4424c0b948c20561fdec80afae21701 | gregxrenner/Data-Analysis | /Coding Challenges/newNumeralSystem.py | 1,752 | 4.46875 | 4 | # Your Informatics teacher at school likes coming up with new ways to help
# you understand the material. When you started studying numeral systems,
# he introduced his own numeral system, which he's convinced will help clarify
# things. His numeral system has base 26, and its digits are represented by
# English capita... | true |
2f74be1a461073ee407ec627e355281950a480a0 | miguel-osuna/PS-Algos-and-DS-using-Python | /Section6_Sorting_Searching/sorting/bubble_sort.py | 2,245 | 4.21875 | 4 | # Bubble Sort Algorithm
def bubble_sort(num_list):
""" Bubble Sort Algorithm """
for passnum in range(len(num_list) - 1, 0, -1):
for i in range(passnum):
# Exchanges items
if num_list[i] > num_list[i + 1]:
temp = num_list[i]
num_list[i] = num_list[... | false |
23de8de49110b4db71833b1b54041bd41fae2b43 | jmobriencs/Intro-to-Python | /O'Brien_Lab1/Lab1-6.py | 436 | 4.3125 | 4 | #John-Michael O'Brien
#w1890922
#CISP 300
#1/31/20
#This program calculates miles walked and calories lost for a specific day of the week.
dayWalked = input('Enter the day of the week you walked: ')
stepsTaken = int(input('Enter the number of steps taken that day: '))
milesWalked = (stepsTaken/2000)
caloriesL... | true |
2c2cd04d5893ebb5e05d463729a999f80e55266c | jmobriencs/Intro-to-Python | /O'Brien_Lab1/Lab1-4.py | 580 | 4.1875 | 4 | #John-Michael O'Brien
#w1890922
#CISP 300
#1/31/20
#This program calculates how many credits are left until graduation.
studentName = input('Enter student name. ')
degreeName = input('Enter degree program name. ')
creditsDegree = int(input('Enter the number of credits needed for the degree. '))
creditsTaken =... | true |
3434b25d66c2edefe39cc30ecc20b8a886d45639 | kundaMwiza/dsAlgorithms | /source/palindrome.py | 869 | 4.1875 | 4 | def for_palindrome(string):
"""
input: string
output: True if palindrome, False o/w
implemented with a for loop
"""
for i, ch in enumerate(string):
if ch != string[-i-1]:
return False
return True
def rec_palindrome(string):
"""
input: string
output: True if p... | true |
5c30a3093ad4fca9ef738d7901f659eff9698700 | ase1590/python-spaghetti | /divide.py | 254 | 4.1875 | 4 | import time
print('divide two numbers')
# get the user to enter in some integers
x=int(input('enter first number: '))
y=int(input('enter number to divide by: '))
print('the answer is: ',int(x/y)),
time.sleep(3) #delay of a few seconds before closing
| true |
5cfd561fc32a028223208019bde4c60736e786a5 | ndvssankar/ClassOf2021 | /Operating Systems/WebServer/test_pipe.py | 1,316 | 4.3125 | 4 | # Python program to explain os.pipe() method
# importing os module
import os
import sys
# Create a pipe
pr, cw = os.pipe()
cr, pw = os.pipe()
stdin = sys.stdin.fileno() # usually 0
stdout = sys.stdout.fileno() # usually 1
# The returned file descriptor r and w
# can be used for reading and
# writing re... | true |
6e2a320b1cf178caf81248050e0184467c000675 | Minaksh1012/If_else_python | /questions.py/loop/if else.py/maximum number.py | 287 | 4.15625 | 4 | num1=int(input("enter the number"))
num2=int(input("enter the number"))
num3=int(input("enter the numbers"))
if num1>num2>num3:
print("num1 is gratest number",num1)
elif num2>num1>num3:
print("num2 is greatest number",num2)
else:
print("num3 is greatest number",num3) | false |
bfafa045df5c449cac9b43b3ab66c0bda07ba5a2 | Minaksh1012/If_else_python | /alphabet digit special character.py | 234 | 4.25 | 4 | ch=input("enter the character")
if (ch>='a'and ch<='z') or (ch>='A'and ch<='Z'):
print("these character is alphabet")
elif ch>='0'and ch<='9':
print("these character is digit")
else:
print("these is special character") | false |
564be3d797b4993009205db721f2fb1c1513c820 | koussay-dellai/holbertonschool-higher_level_programming | /0x06-python-classes/3-square.py | 415 | 4.125 | 4 | #!/usr/bin/python3
class Square:
'''defining a sqaure'''
def __init__(self, size=0):
'''initialize an instance'''
self.__size = size
if type(size) is not int:
raise TypeError("size must be an integer")
elif (size < 0):
raise ValueError("size must be >= 0")... | true |
99f7f46430267a6ee17e0288b14511e3cbef57fc | koussay-dellai/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 350 | 4.1875 | 4 | #!/usr/bin/python3
"""
module to print lines of a file
"""
def read_lines(filename="", nb_lines=0):
"""
function to print n lines of a file
"""
number = 0
with open(filename, encoding="UTF8") as f:
for i in f:
number += 1
print(i, end="")
if nb_lines == ... | true |
fce2be88790287f25b5d6cf863720bbf172f772c | katealex97/python-programming | /UNIT2/homework/hw-1.py/hw-3.py | 394 | 4.21875 | 4 | odd_strings = ['abba', '111', 'canal', 'level', 'abc', 'racecar',
'123451' , '0.0', 'papa', '-pq-']
count = 0
for string in odd_strings:
#find strings greater than 3 and have same
#first and last character
first = string[0]
last = string[len(string) - 1] #python allows neg. indexes last = string[-1]
... | true |
cde77dfa50a8a370bf1c589bc8d262488dc81e29 | thecipherrr/Assignments | /New Project/Number1.py | 488 | 4.25 | 4 | # Main Function
def convert_to_days():
hours = float(input("Enter number of hours:"))
minutes = float(input("Enter number of minutes:"))
seconds = float(input("Enter number of seconds:"))
print("The number of days is:", get_days(hours, minutes, seconds))
# Helper Function
def get_days(hours, mi... | true |
1414aef6db7b039b2f065d68376d903c79e7ba3f | seangrogan-archive/datastructures_class | /TP2/BoxClass.py | 1,691 | 4.28125 | 4 | class BoxClass:
"""class for easy box handling"""
def __init__(self, name, width, height):
"""init method"""
self._name = name
self._width = width
self._height = height
self._rotate = False
def __lt__(self, other):
"""for sorting"""
return ... | true |
31c4f9cfd348ce0f411785c3f38933964b76701e | seangrogan-archive/datastructures_class | /Demo 3/Sorts.py | 2,040 | 4.25 | 4 | def main():
liste = ['B','C','D','A','E','H','G','F']
print(liste)
insert = InsertSort(liste)
print(insert)
merge = MergeSort(liste)
print(merge)
quick = inplace(liste, 0, len(liste) - 1)
print(quick)
def InsertSort(element):
for i in range(len(element)):
j ... | false |
a761dad436a049421f7e6fa8b0bf3c478df6b8aa | pavanjavvadi/leet_code_examples | /anagram.py | 1,681 | 4.3125 | 4 | """
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","b... | true |
6a82cb3ca8845b3b2c9837d3d16d91025cffabf1 | pavanjavvadi/leet_code_examples | /sorting/inserion_sort.py | 369 | 4.125 | 4 | def insertion_sort(array):
for i in range(len(array)):
key = array[i]
j = i - 1
while j>=0 and key < array[j]:
array[j + 1] = array[j]
j = j - 1
array[j + 1] = key
return array
array = [21, 4, 19, 16, 54, 86, 70]
array = insertion_sort(array)
for i in... | false |
66d180a6bfbc522549ac68db6d3b04d940455159 | Rinatik79/PythonAlgoritms | /Lesson 1/lesson1-7.py | 609 | 4.21875 | 4 | sides = input("Enter length of every side of triangle, separated by ';' : ")
sides = sides.split(";")
sides[0] = float(sides[0])
current = sides[0]
sides[1] = float(sides[1])
if sides[1] > sides[0]:
sides[0] = sides[1]
sides[1] = current
current = sides[0]
sides[2] = float(sides[2])
if sides[2] > sides[0]:... | true |
4977a7a7e99f1f571ade665a927e97a059287ae4 | AtharvBagade/Python | /Question7.py | 304 | 4.28125 | 4 | string=input("Enter the string")
def Most_Duplicate_Character(str1):
count = 0
for i in str1:
count2 = str1.count(i)
if(count2 > count):
count = count2
num = i
print(num,"Count:",count)
Most_Duplicate_Character(string)
| true |
3ab954e552bb38cea30ad5bf3bea69592c6988f6 | LyunJ/pythonStudy | /08_list/sort.py | 473 | 4.28125 | 4 | # sort() reverse() sorted()
# #리스트를 정렬
# a = [3,6,0,-4,1]
# a.sort()
# print(a)
# a.reverse()
# print(a)
# # 정렬 후 새로운 리스트를 반환
# new_a = sorted(a,reverse=True)
# print(new_a)
# string = ['Apple','Banana','melon','apple']
# string.sort()
# print(string)
# # 대소문자 구분 없이 정렬
# string.sort(key=str.upper)
# print(string)
# ... | false |
6b7843bef67b2a2c9f1782b7200c3ff40b9edab6 | LyunJ/pythonStudy | /1_OT/hello.py | 1,990 | 4.125 | 4 | # 첫번째 프로그램
# print('Lee YunJae')
'''
# 변수에 값을 저장
x = 10
y = 20
z = 30
print(x,y,z)
# 여러개의 변수에 여러개의 값을 저장
x, y, z = 10, 20, 30
print(x,y,z)
# 여러개의 변수에 동일한 값을 할당
a = b = c = 100
print(a,b,c)
# 두 변수의 값을 교환
a, b = 10, 20
print('a=',a)
print('b=',b)
a,b = b,a
print('a=',a)
print('b=',b)
# 변수를 삭제
x = 100
print(x)
pri... | false |
cf05f6410b6878b34067ecb3b89b38bef59f59b5 | Design-Computing/me | /set3/exercise2.py | 1,216 | 4.5 | 4 | """Set 3, Exercise 2.
An example of how a guessing game might be written.
Play it through a few times, but also stress test it. What if your lower bound
is 🍟, or your guess is "pencil", or "seven"
This will give you some intuition about how to make exercise 3 more robust.
"""
import random
def exampleGuessingGam... | true |
03f695385e9a5b6dd258029d10e11b9bb6ffa371 | ahmedzaabal/Beginner-Python | /Dictionary.py | 606 | 4.28125 | 4 | # Dictionary = a changeable, unorderd collecion of unique key:value pairs
# fast because they use hashing, allow us to access a value quickly
capitals = {'USA': 'Washington DC',
'India': 'New Delhi',
'China': 'Beijing',
'Russia': 'Moscow'}
capitals.update({'Germany': 'B... | true |
c5d91ba52a45b61a4442201fc22f7a20aa575c63 | malay1803/Python-For-Everybody-freecododecamp- | /files/findLine.py | 1,218 | 4.375 | 4 | # Exercise 2: Write a program to prompt for a file name, and then read through the file and look for lines of the form:
#X-DSPAM-Confidence: 0.8475
# When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart the line to extract the floating-point number on the line. Count these lines and then comput... | true |
53c6e9853a06f737c8c43009c4ed2c154e11e107 | vmysechko/QAlight | /metiz/files_and_exceptions/file_writer.py | 720 | 4.21875 | 4 | filename = "programming.txt"
with open(filename, 'w') as file_object:
file_object.write("I love programming.\n")
# 'w' argument tells Python that we want to open a file in write mode.
# In the write mode Python will erase the content of the file.
# 'r' - read mode
# 'a' - append mode
# 'r+' - read/write mode
wi... | true |
7f26b982dd0543a277216ca671b882f9d1c1f3a1 | calder3/BCA_Project- | /hang_man2.py | 1,186 | 4.15625 | 4 | '''
This will play the game hangman. Need to have the random word modual installed.
'''
from random_word import RandomWords
r = RandomWords()
word = r.get_random_word(hasDictionaryDef = 'true')
word = word.lower()
space = list(word)
dash = []
dash.extend(word)
#print(word)
for i in range(len(dash))... | true |
028e73aab6a25145064048c00eb5d9f35d8037c1 | PriyaRcodes/Threading-Arduino-Tasks | /multi-threading-locks.py | 995 | 4.375 | 4 | '''
Multi Threading using Locks
This involves 3 threads excluding the main thread.
'''
import threading
import time
lock = threading.Lock()
def Fact(n):
lock.acquire()
print('Thread 1 started ')
f = 1
for i in range(n,0,-1):
f = f*i
print('Factorial of',n,'=',f)
lock.release()
de... | true |
c30ede39f24692490d2d3530dfbba510118fdd7b | kevenescovedo/PYTHON-work_arquivos | /exercicio3.py | 2,320 | 4.53125 | 5 |
""""
Elabore uma estrutura para representar e armazenar 10 alunos
(matricula, nome, telfone). Utilize os recursos de arquivo para armazenar estes dados
permanentemente. O nome do arquivo deve ser o mesmo da estrutura. Construa um menu com as seguintes opções,
cada uma delas deve ter uma função e a main para chama... | false |
5a6c3768825ef7ec1e97cae8e6f533457fcfba5c | eriDam/CursoPython | /Fase 4 - Temas avanzados/Tema 14 - Bases de datos con SQLite/Ejercicios/restaurante_ej_2_interfaz.py | 1,885 | 4.46875 | 4 | """
2) En este ejercicios debes crear una interfaz gráfica con tkinter (menu.py) que muestre de forma elegante el menú del restaurante.
Tú eliges el nombre del restaurante y el precio del menú, así como las tipografías, colores, adornos y tamaño de la ventana.
El único requisito es que el programa se conectará a la ba... | false |
8cd40a51022bf66e2c94809f094e182b89710008 | nigeltart/Pythagorean-Triples | /Pythagorean_triples.py | 754 | 4.40625 | 4 | # A program to find Pythagorean triples
a_triple=[]
hypotenuse=5
triples=[]
triples.append(a_triple)
#print (triples)
while hypotenuse <100:
base = 1
height = hypotenuse-1
#print ("before loop: ", base, height, hypotenuse)
while height>base:
#print ("before if: , base, height, hypotenuse")
i... | false |
a9cf859429a310242c31b3edcac61225feac869d | dzieber/python-crash-course | /ch3/every.py | 535 | 4.21875 | 4 | '''
exercise 3.8
'''
things = ['one', 'fish', 'two', 'fish']
print(things)
print(things[0])
print(things[-1])
things[0] = 'moose'
print(things)
things.append('squid')
print(things)
things.insert(2,'fish')
print(things)
print(things.pop(2))
print(things)
del things[1]
print(things)
bad = 'fish'
things.remove(bad)
print... | false |
6fe40fec45477da49060eb84fc699ce68e6075c7 | ant0nm/reinforcement_exercise_d23 | /exercise.py | 818 | 4.375 | 4 | def select_cards(possible_cards, hand):
for current_card in possible_cards:
print("Do you want to pick up {}?".format(current_card))
answer = input()
if answer.lower() == 'y':
if len(hand) >= 3:
print("Sorry, you can only pick up 3 cards.")
else:
... | true |
28789e85fe5a651088aed96262a4ba1c9bb97bed | ntuong196/AI-for-Puzzle-Solving | /Week7-Formula-puzzle/formula_puzzle.py | 1,095 | 4.34375 | 4 | #
# Instructions:
#
# Complete the fill_in(formula) function
#
# Hints:
# itertools.permutations
# and str.maketrans are handy functions
# Using the 're' module leads to more concise code.
import re
import itertools
def solve(formula):
"""Given a formula like 'ODD + ODD == EVEN', fill in digits to... | true |
80cb9850a1ebed8a1569f0c6f46b9b23e54363bd | khalidprogrammer/python_tuts | /fault_calculator.py | 1,422 | 4.34375 | 4 | print("============================ Welcome To Faulty Calculator=========================")
print("================Please enter this operator +,*,/,_,%** =================================")
def calculator():
operator = input("Enter operator\n")
number1 = int(input("Enter num1 \n"))
number2 = int(input("E... | false |
aa5bfc0a89a37962ee6178bf33ef5b21aa7a53da | MaxBranvall/practicepython.org-Exercises | /ex2.py | 482 | 4.28125 | 4 | # Ask user for number
# print appropriate message if it's odd or even
num = int(input("Please enter a number: "))
if num % 2 == 0 and num % 4 == 0:
print("Even and divisble by 4!")
elif num % 2 == 0:
print("Just even!")
elif num % 4 == 0:
print("Just divisible by 4")
else:
print("Odd!")
num = int(inp... | false |
1c44fed92ef5e6e7c986f79a0f2473de31325184 | hansweni/UBC_PHYS_Python-crash-course | /2. Arduino for Data Collection/RGB_LED.py | 1,311 | 4.28125 | 4 | '''
Program to demonstrate how to flash the three colors of a RGB diode
sequentially using the Arduino-Python serial library.
'''
# import libraries
from Arduino import Arduino
import time
board = Arduino() # find and connect microcontroller
print('Connected') # confirms the microcontroller has been found
# give pi... | true |
65418f750afea14168ea6f8095b9bf1234b722a8 | KiranGowda10/Add-2-Linked-Lists---LeetCode | /add_2_num.py | 832 | 4.125 | 4 |
class Node:
def __init__(self, data = None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = Node()
def append(self, data):
new_node = Node(data)
current_node = self.head
while current_node.next is not None... | true |
25a39a23d66108f8909741e94c7e9e290479c044 | fatmazehraCiftci/GlobalAIHubPythonCourse | /Homeworks/homework2.py | 482 | 4.1875 | 4 | """
Create a list and swap the second half of the list with the first half of the list and
print this list on the screen
"""
def DivideandSwap(list):
length=len(list)
list1=[]
list2=[]
for i in range(int(length/2)):
list1.append(list[i])
remainder=length-int(length/2)
... | true |
3766e43d653c9e92a2fdb946a34de44c0e43905c | shivamagrawal3900/Python-crash-course | /chapter5-if_statements.py | 1,249 | 4.1875 | 4 | cars = ['Audi', 'BMW', 'Jaguar', 'LandRover']
for car in cars:
if car == 'Jaguar':
print(car.upper())
else:
print(car)
# == is case sensitive
print(cars[1]=='bmw')
# > False
# !=
print(cars[1]!='Audi')
# > True
# Numerical Comparisions
# ==, !=, <, >, <=, >=
# Checking multiple values
# 'and' and 'or' ope... | true |
d9d121a9240b4712f6cbacb802064f235ff57413 | Avis20/learn | /python/books/essential_algo/ch3-linked_list/main.py | 2,286 | 4.125 | 4 | class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
class LinkedList:
def __init__(self, head: Node | None = None):
self.head = head
def add_after(self, search_val: int, new_node: Node):
node = self.head
while node:
if n... | false |
09ea43cd396693c775912dd83794f43c38de8ee5 | deepikaasharma/Parallel-Lists-Challenge | /main.py | 1,333 | 4.125 | 4 | """nums_a = [1, 3, 5]
nums_b = [2, 4, 6]
res = 0
for a, b in zip(nums_a, nums_b):
res += a * b"""
"""Write a function called enum_sum which takes a list of numbers and returns the sum of the numbers multiplied by their corresponding index incremented by one.
Ex: enum_sum([2, 4, 6]) -> (index 0 + 1)*2 + (index 1 ... | true |
8976ba885b018f928284de9128f6b2ce4725c4dc | BibhuPrasadPadhy/Python-for-Data-Science | /Python Basics/100_Python_Programs/Question2.py | 501 | 4.4375 | 4 | ##Write a program which can compute the factorial of a given numbers.
##The results should be printed in a comma-separated sequence on a single line.
##Suppose the following input is supplied to the program:
##8
##Then, the output should be:
##40320
##
##Hints:
##In case of input data being supplied to the ques... | true |
6b68f861e8ba815ad33e546ca6d5ff28b2fb3add | navjo7/DataStructure | /python/sorting/sort.py | 489 | 4.1875 | 4 | unsortedArray = [ 5, 3, 6, 8, 2, 1, 4, 5, 6 ]
print("unsorted : ",*unsortedArray)
# selection sort
for i in range(len(unsortedArray)):
minimumIndex = i
for j in range(i+1,len(unsortedArray)):
if unsortedArray[j] < unsortedArray[minimumIndex]:
minimumIndex = j
temp = unsortedArray[i]
... | false |
d68c9cf85a4f6a2cb377a94c2c124a55feccd66c | pmk2109/Week0 | /Code2/dict_exercise.py | 1,513 | 4.28125 | 4 | from collections import defaultdict
def dict_to_str(d):
'''
INPUT: dict
OUTPUT: str
Return a str containing each key and value in dict d. Keys and values are
separated by a colon and a space. Each key-value pair is separated by a new
line.
For example:
a: 1
b: 2
For nice pyth... | true |
a63908c918a6b0cbd35b98485fc79683c3923138 | joy-joy/pcc | /ch03/exercise_3_8.py | 1,075 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 17 21:17:17 2018
@author: joy
"""
# Seeing the World
visit_list = ["Machu Picchu", "Phuket", "Bali",
"Grand Canyon", "Santorini", "Dubai",
"New York City", "Paris", "London", "Sydney"]
print("\nVisit List:")
print(vi... | true |
093fbab0a28da1fb96ac4cf105847729dccf9a35 | joy-joy/pcc | /ch03/exercise_3_10.py | 2,229 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 17 21:38:45 2018
@author: joy
"""
# Every function
countries = ['USA', 'UK', 'USSR', 'Brazil', 'India', 'Bangladesh',
'Pakistan', 'Mexico', 'Saudi Arabia', 'Australia']
print("\nHere's our initial list of countries:\n", countries)
#... | false |
7705715e8e7b21cfbc6b0b3c32d44f9463333c80 | janbalaz/ds | /selection_sort.py | 1,048 | 4.28125 | 4 | from typing import List
def find_smallest(i: int, arr: List[int]) -> int:
"""
Finds the smallest element in array starting after `i`.
:param i: index of the current minimum
:param arr: array of integers
:return: position of the smallest element
"""
smallest = i
for j in range(i + 1, l... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.