blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b900777c43b0910d9329b4a3e492e0da64aaf625 | ooladuwa/cs-problemSets | /Week 2/027-WordPattern.py | 1,640 | 4.21875 | 4 | """
Given a pattern and a string a, find if a follows the same pattern.
Here, to "follow" means a full match, such that there is a one-to-one correspondence between a letter in pattern and a non-empty word in a.
Example 1:
Input:
pattern = "abba"
a = "lambda school school lambda"
Output: true
Example 2:
Input:
pat... | true |
690ffbac5d76e55e2ce80ff075bc81f97defbbd8 | Deepakat43/luminartechnolab | /variabl length argument method/varargmethd.py | 460 | 4.15625 | 4 | def add(num1,num2):
return num1+num2
res=add(10,20)
print(res)
#here 2 argumnts present
#what if there are 3,4,5 etc arguments present
#so we use ****variable length argument method****
def add(*args):
print(args)
add(10)
add(10,20)
add(10,20,30,40,50)
#using this frmat we get argmnts in a (tuple) frmat
#f... | true |
01c8e2d62c8464e223d0e239bd08d9cd054966e4 | arsh479/dv.pset | /0055 - Ascending or descending/0055.py | 1,062 | 4.1875 | 4 | import random
i = 1
print(' Welcome to find ascending or descending numbers')
print(end ='\n')
while i == 1:
x = int(input('Enter number: ')) #5 different inputs so to set conditions for each input with every other input
y = int(input('Enter number: '))
... | false |
afb2f7f9f469e96b342930d31461d9b9fa259171 | jpierrevilleres/python-math | /square_root.py | 1,291 | 4.28125 | 4 | import math #imports math module to be able to use math.sqrt and abs function
#Part 1 defining my_sqrt function
def my_sqrt(a): #Python code taken from Section 7.5
x = a / 2 #takes as an argument and uses it to initialize value of x
while True: #uses while loop as mentioned in Section 7.5
y =... | true |
633b1ea1c5d61c406e9745dfe351f15cdf2b8bfd | markymauro13/CSIT104_05FA19 | /Exam-Review-11-6-19/exam2_review3.py | 490 | 4.3125 | 4 | x = "Computational Concepts 1"
y = "MSU"
# What are the results of the following expressions?
# a. How many ‘o’ in string x?
# b. How can you find the substring “Concepts” in x?
# c. How can you check if y starts with “M”?
# d. How can you replace “MSU” in y with “Montclair State University”?
#a
print(x.c... | true |
2a499ffe9355bb49ff0ca6ff45b8648a1841af15 | markymauro13/CSIT104_05FA19 | /Assignment3/1_calculateLengthAndExchange.py | 443 | 4.25 | 4 | x = str(input("Enter a string: ")) # ask for input from user
if(len(x)>0):
print("The length of string is: " + str(len(x))) # print the length of the string
print("The resulted string is: " + str(x[-1]) + str(x[1:len(x) - 1]) + str(x[0])) # print the result of the modified string
else:
print("Try ... | true |
c9cece85db973eedfc69fb0d9e8592935d21232e | markymauro13/CSIT104_05FA19 | /Exam-Review-11-6-19/exam2_review6.py | 445 | 4.1875 | 4 | #6
for i in range(1,7): # controls the numbers of rows
for j in range(1,i+1): # controls the numbers on those lines
print(j, end = '')
print()
print("------")
i = 1
while i <= 6:
for j in range(1, i+1):
print(j, end = '')
print()
i+=1
print("------... | true |
548c422e96d13360a458557f1e0e2a465bf3f782 | AastikM/Hacktoberfest2020-9 | /Python_Solutions/Q24_factorial(recursion).py | 451 | 4.3125 | 4 | #Function for calulating the factorial
def factorial(x):
if x == 1 or x== 0 : #base/terimination condition
return 1
elif(x < 0) :
print("Sorry, factorial does not exist for negative numbers")
else:
return (x * factorial(x-1)) #Recursive Call for function factorial
# main
num ... | true |
2d1c82316be30bb1a893f9d6c58b4678137e6814 | AastikM/Hacktoberfest2020-9 | /Python_Solutions/Q2BinaryDecimal.py | 521 | 4.53125 | 5 | # Python program to convert binary to decimal
#Function to convert binary to decimal
def binaryToDecimal(n):
num=n;
decimal=0;
#Initializing base value to 1, i.e 2^0
base = 1;
temp = num;
while temp:
last_digit=temp%10;
temp//= 10;
decimal += last_digit * base;
... | true |
bf8e19eae13001826a645bdb92e1897927875d54 | davinpchandra/ITP_Assignments | /AssignmentPage46 | 1,747 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 10:11:08 2019
@author: davinpc
"""
# 3-4 GuestList
guest_list = ["Steve Jobs","Robert Downey Jr","Will Smith"]
for guest in guest_list:
print("Dear " + guest + ", please come to my dinner.")
print(" ")
# 3-5 ChangingGuestList
print(guest_l... | true |
5d1d39f36540615bb64b1b6aeb2907e3f76d4cd3 | irk2adm/pythontutor | /01/07_SchoolDesks.py | 982 | 4.1875 | 4 | # В школе решили набрать три новых математических класса. Так как занятия по математике у них проходят в одно и то же время, было решено выделить кабинет для каждого класса и купить в них новые парты. За каждой партой может сидеть не больше двух учеников. Известно количество учащихся в каждом из трёх классов. Сколько в... | false |
bfbc32395535b56de1c2749b04614343afb18789 | Dencion/practicepython.org-Exercises | /Exercise11.py | 688 | 4.28125 | 4 | def checkPrime(userNum):
'''
Checks if the users entered number is a prime number or not
'''
oneToNum = []#Creates a list starting from 1 - userNum
divisorList = []#Empty list to be filled with divisors form userNum
i = 1
while i <= userNum:
oneToNum.append(i)
i += 1
... | true |
f455442985533db35f2a5b41219274d5e12ef36c | YaoLaiGang/LearnPython | /len_iterator_yield.py | 858 | 4.3125 | 4 | #Python中的迭代器和生成器(使用yield的函数)
#迭代器常使用iter()为构造方法 next()为遍历方法
x = list(range(5))
it = iter(x)
for i in it:
print(i)
#使用yield的函数称为迭代器生成器函数,这个函数的特点如下
#1、该函数返回一个迭代器,但调用时函数不会执行
#2、每依次访问该迭代器,函数就执行到yield的地方返回一个值,并暂停执行
#3、依次执行,函数也依次执行
def fibonacci(n):#需要检查N的合法性,此处省略
a , b = 0 ,1
for i in range(n):
yield ... | false |
aefb7cc14cbf7df71feca90f6ea56a440b325da2 | YaoLaiGang/LearnPython | /len_Tuple.py | 1,028 | 4.3125 | 4 | #元组的基本操作
"""
元组和列表类似,但是元组不能修改,且使用()
"""
tuple1 = ('abcd',787,2.33,'laigang',70.2)
tuple2 = (123,'laigang')
print(tuple1)
print(tuple1[0])
print(tuple1[1:3])
print(tuple1[2:])
print(tuple1*2)
print(tuple1+tuple2)
#我们可以把字符串看成特殊的元组
#元组的元素是不能更改的,但是元组内可以嵌套list可变数据结构
tuple1 = ([1,2,3],[4,5,6])
tuple1[0][1]=30
print(tuple1)
... | false |
92411f12036363a6056c85f71df242dbb9a119de | KenjaminButton/runestone_thinkcspy | /6_functions/exercises/6.13.3.exercise.py | 629 | 4.25 | 4 | # 6.13.3 Exercise:
# Write a non-fruitful function drawPoly(someturtle, somesides, somesize)
# which makes a turtle draw a regular polygon. When called with
# drawPoly(tess, 8, 50), it will draw a shape like this:
import turtle
# Initializing turtle
window = turtle.Screen()
window.bgcolor("lightgreen")
# Changing c... | true |
a9fae446d7e342cc7e4ffc014d00f42993877f62 | KenjaminButton/runestone_thinkcspy | /14_web_applications/14.5.py | 1,922 | 4.375 | 4 | # Writing Web Applications with Flask
'''
In this section, you will learn how to write web applications using
a Python framework called Flask.
Here is an example of a Flask web application:
The application begins by importing the Flask framework on line 1.
Lines 6-11 define a function hello() that serves up a simple ... | true |
9ad02888fbdeb4a86afc10d8be138e173475e075 | KenjaminButton/runestone_thinkcspy | /10_lists/10.12.cloning_lists.py | 603 | 4.34375 | 4 | # 10.12 Cloning Lists
'''
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.
Tak... | true |
1ee694e9e288b104b3f6054b511fb9768e71a535 | KenjaminButton/runestone_thinkcspy | /9_strings/9.9.strings_are_immutable.py | 899 | 4.34375 | 4 | # 9.9 Strings Are Immutable
'''
One final thing that makes strings different from some other Python collection
types is that you are not allowed to modify the individual characters in the
collection. It is tempting to use the [] operator on the left side of an
assignment, with the intention of changing a character in a... | true |
9435b6fa5b480be9729ec52eaa5b87f7207401e5 | KenjaminButton/runestone_thinkcspy | /10_lists/10.17.lists_and_loops.py | 1,006 | 4.46875 | 4 | # 10.17 Lists and Loops
'''
'''
fruits = ["apple", "orange", "banana", "cherry"]
for afruit in fruits: # by item
print(afruit)
'''
In this example, each time through the loop, the variable position
is used as an index into the list, printing the position-eth element.
Note that we used len as the upper bound ... | true |
d7c00c2393c1b3df29c77d606ccd92e456f5a5d9 | KenjaminButton/runestone_thinkcspy | /11_files/exercises/11.9.4.py | 2,501 | 4.25 | 4 | '''
Interpret the data file labdata.txt such that each line contains a an x,y coordinate pair. Write a function called plotRegression that reads the data from this file and uses a turtle to plot those points and a best fit line according to the following formulas:
𝑦=𝑦¯+𝑚(𝑥−𝑥¯)
𝑚=∑𝑥𝑖𝑦𝑖−𝑛𝑥¯𝑦¯∑𝑥2𝑖−𝑛𝑥¯2
... | true |
af4d0611190081213e50361f1913ee68f694257e | KenjaminButton/runestone_thinkcspy | /2_simple_python_data/2.7.operators_and_operands.py | 1,457 | 4.53125 | 5 | # Operators and Operands
print("\n----------------------------")
print(2 + 3) # <<< 5
print(2 - 3) # <<< -1
print(2 * 3) # <<< 6
print(2 ** 3) # <<< 8
print(3 ** 2) # <<< 9
print("\n----------------------------")
minutes = 645
hours = minutes / 60
print(hours) # <<< 10.75
print("\n----------------------------")
prin... | true |
aec94d7f54cc24921ab10dabc07957947fa8f212 | KenjaminButton/runestone_thinkcspy | /4_python_turtle_graphics/4.1.hello_little_turtles.py | 1,538 | 4.84375 | 5 | # 4.1 Hello Little Turtles
'''
There are many modules in Python that provide very powerful features that we can use in our own programs. Some of these can send email or fetch web pages. Others allow us to perform complex mathematical calculations. In this chapter we will introduce a module that allows us to create a da... | true |
dba922ce03038984d3c5e5faa6b557ec54243e53 | KenjaminButton/runestone_thinkcspy | /4_python_turtle_graphics/4.11_11_exercise.py | 661 | 4.25 | 4 | '''
# 11. Write a program to draw some kind of picture.
Be creative and experiment with the turtle methods provided in Summary of Turtle Methods.
https://runestone.academy/runestone/books/published/thinkcspy/PythonTurtle/SummaryofTurtleMethods.html#turtle-methods
'''
import turtle
window = turtle.Screen()
ken = t... | false |
dbd691354cf51c9b8c5ec66617d41ad250ca51cd | KenjaminButton/runestone_thinkcspy | /12_dictionaries/exercises/12.7.1.exercise.py | 1,064 | 4.25 | 4 | '''
Write a program that allows the user to enter a string. It then prints a table of the letters of the alphabet in alphabetical order which occur in the string together with the number of times each letter occurs. Case should be ignored. A sample run of the program might look this this:
Please enter a sentence: ThiS... | true |
90e719b77b8664dd93f4b8a09b9fd822f5d64a5d | KenjaminButton/runestone_thinkcspy | /2_simple_python_data/2.8.input.py | 887 | 4.25 | 4 | # Input
n = input("Please enter your name: ")
print("\nHello", n)
print("\n--------------------------")
string_seconds = input("Please input the number of seconds you wish to convert: ")
total_seconds = int(string_seconds)
hours = total_seconds // 3600
seconds_still_remaining = total_seconds % 3600
minutes = seconds_s... | true |
9b12a2e9f5566691a9b1b6799dcdd4f5c0d08cb1 | KenjaminButton/runestone_thinkcspy | /6_functions/6.1.functions.py | 2,493 | 4.15625 | 4 | # Functions
'''
def name( parameters ):
statements
'''
'''
import turtle
def drawSquare(turt, size):
# Make turtle aka turt draw a square and with size of the side
for i in range(4):
turt.forward(size)
turt.left(90)
# Setting up windows and its attributes
window = turtle.Screen()
window... | false |
36755b3f1801a8ed276545370b54deaa06eeda2d | KenjaminButton/runestone_thinkcspy | /17_classes_and_objects_basics/exercises/17.11.2.exercise.py | 553 | 4.125 | 4 | '''
Add a method reflect_x to Point which returns a new Point, one which is
the reflection of the point about the x-axis.
For example, Point(3, 5).reflect_x() is (3, -5)
'''
import math
class Point:
def __init__(self, initX, initY):
self.x = initX
self.y = initY
def reflect_x(self):
... | true |
a7e1aa3372a75ce887a35011f0669cf329db940d | KenjaminButton/runestone_thinkcspy | /4_python_turtle_graphics/4.11_13_exercise.py | 709 | 4.3125 | 4 | '''
# 13 A sprite is a simple spider shaped thing with n legs coming out from a center point. The angle between each leg is 360 / n degrees.
Write a program to draw a sprite where the number of legs is provided by the user.
'''
number_of_legs = input("input a number of legs (choose between 0 and 360): ")
number_of_l... | true |
36a370c8100c4b59b269f1eec97f1f6f9966c02b | KenjaminButton/runestone_thinkcspy | /6_functions/exercises/6.13.11.exercise.py | 602 | 4.5 | 4 | # Extend the star function to draw an n pointed star.
# (Hint: n must be an odd number greater or equal to 3).
# n pointed star
import turtle
# Initializing turtle
window = turtle.Screen()
window.bgcolor("lightgreen")
# Changing colors and pensize for turtle
kendrick = turtle.Turtle()
kendrick.color("hotpink")
kend... | true |
f70d6eb25a2ea7a650c3309478a51c881c8eeb37 | KenjaminButton/runestone_thinkcspy | /6_functions/exercises/6.13.6.exercise.py | 662 | 4.34375 | 4 | # Write a non-fruitful function drawEquitriangle(someturtle, somesize) which
# calls drawPoly from the previous question to have its turtle draw a
# equilateral triangle.
import turtle
# Initializing turtle
window = turtle.Screen()
window.bgcolor("lightgreen")
# Changing colors and pensize for turtle
kendrick = turt... | true |
327dac896917535638efe1b3cca6bf3fb5727d11 | KenjaminButton/runestone_thinkcspy | /11_files/exercises/11.9.3.py | 477 | 4.15625 | 4 | '''
Using the text file studentdata.txt (shown in exercise 1) write a
program that calculates the minimum and maximum score for each
student. Print out their name as well.
'''
def min_and_max():
f = open('studentdata.txt', 'r')
for i in f:
items = i.split()
# print(items[1:])
minimum =... | true |
95f96088c1d431c2ef6a1d6d8b1864c4a27c0b20 | eoinpayne/Python | /Lab2circle.py | 277 | 4.15625 | 4 | from math import pi
r = 12
area = pi * r ** 2
circumference = 2*pi*r
#circumference = 2*pi*r... ca calculate on the fly or define the sum up here.
print ("The area of a circle with radius", r, "is", area)
print ("The circumference of a circle with radius" , r, "is", 2*pi*r) | true |
1c13bb45f9fe5ef9b7eedd2d4e02575119566751 | eoinpayne/Python | /Lab2average.py | 1,297 | 4.40625 | 4 | __author__ = 'D15123620'
#(1 point) Write a program average.py that calculates and prints the average of three
#numbers. Test it with 3, 5 and 6. Does it make a difference if you treat the input strings as
#float or int? what about if you print the output result as float or an int?
'''def what_is_average (num_1, num_... | true |
82c53d6b7907cee15e954d16089ad4d3f04d9bd8 | svamja/learning_assignments | /2-fibonacci.py | 242 | 4.125 | 4 | n = int(input("Enter the number: "))
x = 0
y = 1
count = 0
total = 0
print("Fibonacci Number: ")
while count < n:
if count % 2 == 0:
total += count
x = y
y = count
count = (x + y)
print(count)
| false |
45b5235a525b2007c4124fd16fb894f7f10f9c0f | ivyostosh/algorithm | /data_structure/queue.py | 1,921 | 4.5 | 4 | # Queue Implementation (https://www.educative.io/blog/8-python-data-structures
"""
We can use append() and pop() to implement a queue, but this is inefficient as lists must shift elements one by one.
Instead, the best practice is to use a deque from collections module.
Deques (double-ended queue) allow you to access b... | true |
b0debf7de24d42f2106213afda16edb349e0c4dd | bikegirl/NLP-Nitro | /Word.py | 878 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Word class holds the properties of a word:
token, part_of_speech, and frequency.
Has a method for computing complexity
"""
import math
class Word:
def __init__(self, word, part_of_speech, frequency = 0):
self.__word = word
self.__part_... | true |
c9af8dd04b7a7cbac9ac159c22379174525ebc9a | suriyaaws2020/Python | /Create/NewfolderPython/python_101.py | 807 | 4.34375 | 4 | #variable declaration
X=2, Y=-3, Z=0.4
#above declares the variables under respective variable type#
#example X=2 is an integar, Z=0.4 is an float type#
#print function is used to print the value#
print(type(x))
#the above prints the value of X as 2. Output will be 2
#below command shows how to assign values into a var... | true |
5d41a7c7404af46e3d985142f487373e60a3f206 | usn1485/TipCalculator | /TipCalculator.py | 2,422 | 4.3125 | 4 | #Import the required Modules
import math
import os
#Take user input for bill amount.
bill=float(input("Enter the bill Amount:"))
# Write function to calculate tip.
def tipCalculator(bill,percent):
# convert the percent input to whole number if it is given as 0.15
if(percent<1):
tipPercent=percent*100
... | true |
d684aacc8759a7a4eb3b3e039e4813934624d407 | campjordan/Python-Projects | /Numbers/pi.py | 1,243 | 4.28125 | 4 | '''
Find PI to the Nth Digit - Enter a number and have the program generate PI
up to that many decimal places. Keep a limit to how far the program will go.
'''
def arctan(x, one=1000000):
"""
Calculate arctan(1/x)
arctan(1/x) = 1/x - 1/3*x**3 + 1/5*x**5 - ... (x >= 1)
This calculates it in fixed poi... | true |
c2d9a1ac9c8ce3a8f2c63b1fa8768ffc5400f68f | rulesrmnt/python | /calc.py | 350 | 4.34375 | 4 | print (2+3) #addition
print (2*3) #multiplication
print (2-3) # substraction
print (2/3) #float division
print (2//3) #integer division
print (3%2) # Module, gives remainder
print (2%2)
print(round(2/3,2)) #round function
print (2**5) # exponent i.e. 2 to the power 5
print (2**5**2) # associative rule i.e exponents are... | true |
4355be5058d5d5a3858c4cee03ea4a219a35293b | jwarlop/UCSD | /Extension/Cert_DM_Adv_Analytics/2018Win_Py4Info/Homework/A06/URL_reader.py | 1,267 | 4.125 | 4 | # Assignment 6
# Network Programming
# John M Warlop
# Python 3.x
# Due 3/4/2018
from urllib.request import urlopen
url = input("type url(ex: www.ibm.com): ")
url = "http://"+url
try:
res=urlopen(url)
except:
print("Could not open "+url)
size=0
Chunk = 512
flag = False
while True:
chunk = res.read(Chunk)
... | true |
72611838082c1243f1fb63fab711af4c832459ab | vijayramalingom/SYSC-1005-Introduction-to-Software-Development- | /math_quiz_v3.py | 1,776 | 4.25 | 4 | """
Version 3 of a math quiz program.
Adapted from a programming problem by Jeff Elkner.
dlb Dept. of Systems and Computer Engineering, Carleton U.
Initial release: October 21, 2014 (SYSC 1005)
Revised: November 4, 2015 (SYSC 1005)
The user is prompted to enter a command ("T" or "Q").
If the user types "Q", ... | true |
512746e85cd9cc1c4b18b29fd05a103e4a915db1 | dtingg/Fall2018-PY210A | /students/C_Farris/session03/list_lab.py | 1,272 | 4.25 | 4 | #!/usr/bin/env Python3
"""
Date: November 11, 2018
Created by: Carol Farris
Title: list Lab
Goal: learn list functions
"""
def displayPfruits(myFruit):
for x in myFruit:
if x.lower().startswith('p'):
print(x)
else:
print(x + " doesn't start with p")
def addUsingInsert(m... | true |
8ce538d1282639c0040cc9101cf9ca1750192fcf | dtingg/Fall2018-PY210A | /students/ZidanLuo/session02/printGrid.py | 602 | 4.125 | 4 | import sys
def print_grid(x,y):
count = 1
#count all the possible number of lines
lines = (y + 1) * x + 1
plus = "+"
minus = "-"
shu = "|"
empty = " "
#draw the horizontal and vertical lines
Horizontal = (plus + y * minus) * x +plus
Vertical = (shu + y * empty) * x + shu
... | true |
3ea0e0bef450bd1adf0135bbc54775a7aade1fb4 | dtingg/Fall2018-PY210A | /students/ericstreit/session03/list_lab.py | 2,511 | 4.15625 | 4 | #Lesson03
#String Exercises ##
#
#!/usr/bin/env python3
#define variables
mylist = ["Apples", "Pears", "Oranges", "Peaches"]
#define function
def myfunc(n):
"""Update the DocString"""
pass
#series 1
print("The list currently contains: ", mylist)
additem = input("Pleaes enter another item: ")
mylist.append(addit... | true |
cc81bbb1e52a93c61b9f96b60930e38bf18f02cb | dtingg/Fall2018-PY210A | /students/KannanSethu/session8/circle.py | 1,237 | 4.28125 | 4 | #!/usr/bin/env python3
import math
'Create a circle using classes'
class Circle:
def __init__(self, radius):
self.radius = radius
_diameter = None
@property
def diameter(self):
self._diameter = self.radius * 2
return self._diameter
@diameter.setter
def diameter(self, dia... | false |
50f8171ffe7f7bb9e9b7b531314acfa999c88933 | dtingg/Fall2018-PY210A | /students/student_framllat/session02/series.py | 1,600 | 4.125 | 4 | a = int(input("How many nums shall I calculate for you? "))
def fibonacci(n):
"""This function calculates the nth value of a Fibonacci number
starting at the zero index
"""
if n < 0:
return None
elif n == 0:
return 0
elif n == 1:
return 1
else:
return f... | false |
ab2aed6b36ee8a39a05d108704db93cad76a1311 | dtingg/Fall2018-PY210A | /students/ZackConnaughton/session03/list_lab.py | 709 | 4.15625 | 4 | #!/usr/bin/env python
def series1():
"""
Shows what can be done with a simple list of fruitsself.
"""
fruits = ['Apples', 'Pears', 'Oranges', 'Peaches']
print(fruits)
response = input('Input another Fruit: ')
fruits.append(response)
print(fruits)
fruit_number = input('Enter the numb... | true |
a0619210034948ccc632e944142c72e302bfd522 | dtingg/Fall2018-PY210A | /students/KannanSethu/session3/slicing_functions.py | 1,324 | 4.28125 | 4 | """some functions that take a sequence as an argument, and return a copy of that sequence"""
A_STRING = "this is a string"
A_TUPLE = (2, 54, 13, 12, 5, 32)
def exchange_first_last(seq):
""" with the first and last items exchanged """
return seq[-1:] + seq[1:-1] + seq[0:1]
assert exchange_first_last(A_STRIN... | false |
e07217f51ac1b0401635329a3ae81a54495135a7 | dtingg/Fall2018-PY210A | /students/DiannaTingg/Session05/comprehensions_lab.py | 2,453 | 4.4375 | 4 | # Lesson 05 Exercise: Comprehensions Lab
# Count Even Numbers
# Using a list comprehension, return the number of even integers in the given list.
def count_evens(l):
return len([i for i in l if i % 2 == 0])
assert count_evens([2, 1, 2, 3, 4]) == 3
assert count_evens([2, 2, 0]) == 3
assert count_evens([1, 3, 5]... | true |
29c93f8ba7065b60a30ea4264f4678eb90e8301a | dtingg/Fall2018-PY210A | /students/ZachCooper/session01/break_me.py | 1,139 | 4.125 | 4 | #!/usr/bin/env python
# I tried a couple of error exceptions that I commonly ran into during my Foundations class
# Example of ZeroValueError
def divide_things(num1, num2):
try:
print(num1 / num2)
except ZeroDivisionError:
print("Ummm...You totally can't divide by 0")
raise ZeroDivision... | true |
f6a456ba4595fcbbf2e3a4143b2c0ca4f131df96 | dtingg/Fall2018-PY210A | /students/HABTAMU/session02/printer_Grid_Ex.py | 2,344 | 4.125 | 4 | #!/usr/bin/env python3
# Goal:
# Write a function that draws a grid like the following:
# + - - - - + - - - - +
# | | |
# | | |
# | | |
# | | |
# + - - - - + - - - - +
# | | |
# | | |
# | | |
# | | ... | false |
91d188d6e4655d7d88dddef897aeec6d4a0ced09 | dtingg/Fall2018-PY210A | /students/DrewSmith/session05/comprehension_exercise.py | 2,266 | 4.4375 | 4 | """
Comprehension exercise solutions
"""
from collections import defaultdict
def count_evens(nums):
"""
Return number of even integers in nums
:param nums: sequence of integers
"""
return len([num for num in nums if num % 2 == 0])
def print_dict(food_prefs):
"""
Print a dictionary using... | false |
340220654fed7bc3d3de00da2a5f3fd4fc230121 | dtingg/Fall2018-PY210A | /students/JugalKishore/Session_3/slicing_lab.py | 2,432 | 4.15625 | 4 | #!/usr/bin/env python3
def exchange_first_last(seq):
"""
:param: sequence
:return: sequence with first and last item exchanges and all other item remain same
"""
if len(seq) <= 1:
return seq
return seq[-1:] + seq[1:-1] + seq[:1]
def other_item_removed(seq):
"""
:param: sequence
:return: sequence with ever... | false |
f3348cba2eaaa6e973b8a28497d0cd5d942389a4 | dtingg/Fall2018-PY210A | /students/HABTAMU/session04/dict_lab.py | 2,076 | 4.125 | 4 | #!/usr/bin/env python3
"""Dictionaries 1"""
# Create a dictionary containing “name”, “city”, and “cake” for “Chris” from “Seattle” who likes “Chocolate”
# (so the keys should be: “name”, etc, and values: “Chris”, etc.)
my_dict = {"name": "Chris","city": "Seattle","cake": "Chocolate"}
# Display the dictionary.
print... | true |
b74f0019166cd600f9a17433f5b1807b7f94548b | dtingg/Fall2018-PY210A | /students/DiannaTingg/Session04/get_languages.py | 2,111 | 4.40625 | 4 | # Lesson 04 Exercise: File Exercise
# File reading and parsing
# Write a program that takes a student list and returns a list of all the programming languages used
# Keep track of how many students specified each language
# It has a header line and the rest of the lines are: Last, First: Nicknames, languages
def get... | true |
63a2168eeeddcc102e648ea5130a40d888569a7d | dtingg/Fall2018-PY210A | /students/JonSerpas/session02/series.py | 1,395 | 4.25 | 4 |
def fibonacci(n):
#first create our list with starting integers
fiblist = [0,1]
#appends to the end list of integers the sum of the previous two integers
#this will loop until the length of the list is n long
#finally we return the n value of the list
while len(fiblist) < n:
fiblist.append(sum(fiblist[-2:]))
... | true |
e571de78c6e4fd094bcf760e2f2f522ff53958aa | dtingg/Fall2018-PY210A | /students/Adolphe_N/session03/slicing.py | 1,307 | 4.5 | 4 | #! python3
a_string = 'this is a string'
a_tuple = (2,54,13,12,5,32)
name = 'Seattle'
'''
prints the list with the last item first and first item last
'''
def exchange_first_last():
#this will exchange the first and last character of the string
print(a_string)
print ('{}{}{}'.format(a_st... | true |
8dc90534107673e7574626c9816423f8c72bf4f2 | Miriam-Hein/pands-problem-sheet | /es.py | 710 | 4.125 | 4 | # es.py
# This program reads in a text file and outputs the number of e's it contains.
# Author: Miriam Heinlein
# Import library (System-specific parameters and functions)
import sys
# Function to read letter e in the file from an arugment in the command line
def readText():
with open(sys.argv[1], "r") as f: ... | true |
12b5743215371715e3fb8437c64f2c76ebb68cef | michaelkmpoon/Pandhi_Ayush_-_Poon_Michael_Assignment1_CTA200H | /question_1/find_replace.py | 962 | 4.15625 | 4 | #!/usr/bin/env python3
import os
def find_replace(find: str, replace: str): # type check, only strings allowed as input
os.makedirs(replace) # make directory called replace in working directory
for file_name in os.listdir("."):
if file_name.endswith(".txt"):
file = open(file_name, "r")
... | true |
8a2eb6e733d29afad05b36566efd71406ca57fbc | pankajnimgade/Python_Test101 | /Function_Installation_and_Conditionals/code_with_branches_1_.py | 1,574 | 4.25 | 4 | phone_balance = 9
bank_balance = 100000000
if phone_balance < 10:
phone_balance += 10
bank_balance -= 10
print("Phone Balance: " + str(phone_balance))
print("Bank Balance: " + str(bank_balance))
weight_in_kg = 55
height_in_m = 1.2
if 18.5 <= weight_in_kg/(height_in_m**2) < 25:
print("BMI is considered 'normal... | true |
2076032e181ef578181ea02b669853c79006da38 | Programacion-Algoritmos-18-2/ejercicios-clases2bim-002-paxasaval | /tutoria-2-sc/manejo_archivos/paquete_modelo/mimodelo.py | 2,922 | 4.1875 | 4 | """
creación de clases
"""
class Persona(object):
"""
"""
def __init__(self, n, ape, ed, cod, nota1, nota2):
"""
"""
self.nombre = n
self.edad = int(ed)
self.codigo = int(cod)
self.apellido = ape
self.nota1=int(nota1)
self.nota2=int(n... | false |
6ffe379e6968c1f0262bef8eace517928f4d4849 | dimmonblr/pythonProject2 | /pythonProject3/01_days_in_month.py | 894 | 4.125 | 4 | # -*- coding: utf-8 -*-
# (if/elif/else)
# По номеру месяца вывести кол-во дней в нем (без указания названия месяца, в феврале 28 дней)
# Результат проверки вывести на консоль
# Если номер месяца некорректен - сообщить об этом
# Номер месяца получать от пользователя следующим образом
calendar = {1:31, 2:28, 3:31, 4:... | false |
9b5ad1db488ceb425f57abc3cac88fefa8d581c5 | Prathamdoshi/UC-Berkeley-Data-Analytics-Bootcamp-Module-Exercises | /Python/Netflix.py | 1,405 | 4.125 | 4 | instructions ="""
# Netflix lookup
Finding the info to some of netlfix's most popular videos
## Instructions
* Prompt the user for what video they are looking for.
* Search through the `netflix_ratings.csv` to find the user's video.
* If the CSV contains the user's video then print out the title, what it is rated ... | true |
f2d5ef31396ecea22e9fd495bf7d3538c5d63c96 | damuraiz/python_gb | /lesson2/task02_2.py | 834 | 4.28125 | 4 | #Для списка реализовать обмен значений соседних элементов,
# т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
# При нечетном количестве элементов последний сохранить на своем месте.
# Для заполнения списка элементов необходимо использовать функцию input().
size = int(input('Введите количество элем... | false |
90ec7904e768152ea28f5d2538a8c1b919671848 | damuraiz/python_gb | /lesson3/task03_6.py | 1,039 | 4.28125 | 4 | """
Реализовать функцию int_func(), принимающую слово из маленьких латинских букв
и возвращающую его же, но с прописной первой буквой.
Например, print(int_func(‘text’)) -> Text.
Продолжить работу над заданием.
В программу должна попадать строка из слов, разделенных пробелом.
Каждое слово состоит из латинских букв в ниж... | false |
8507cee32a92b1d19214e08ac731be5a10bc8bb4 | daviddwlee84/LeetCode | /Python3/LinkedList/MergeTwoSortedLists/Better021.py | 892 | 4.125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
from ..ListNodeModule import ListNode
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
... | true |
009fb7f3db4c51738566e83de7ae32ecd2e813f6 | daviddwlee84/LeetCode | /Python3/LinkedList/InsertionSortList/Naive147.py | 1,124 | 4.1875 | 4 | from ..ListNodeModule import ListNode
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
fakeRoot = ListNode(-1)
current = fakeRoot.next = head
while current and current.next:
if current.val <... | true |
df797407e5c699b19a92585715a093d50f867c99 | Kiddiflame/For_Assignment_5 | /Documents/Forritun/max_int.py | 590 | 4.59375 | 5 | #1. Initialize with git init
#2. input a number
#3. if number is larger than 0, it becomes max-int
#4. if number is greater than 0, user can input another number
#5. repeat step 3 and 4 until negative number is given
#6. if negative number is given, print largest number
num_int = int(input("Input a number: "))# Do n... | true |
d5deb525066d1bd891b52c84f63f4033bdcedae8 | andrew-yt-wong/ITP115 | /ITP 115 .py/Labs/ITP115_L8_1_Wong_Andrew.py | 1,568 | 4.28125 | 4 | # Andrew Wong, awong827@usc.edu
# ITP 115, Spring 2020
# Lab 8-1
# Wants to continue function that checks whether the user is going to continue
def wantsToContinue():
# Loop until a valid response is given
validResponse = False
while not validResponse:
# Retrieve the response and capitalize it
... | true |
622b729bde772c0a296e1db8e9c6a84b6f3859e4 | andrew-yt-wong/ITP115 | /ITP 115 .py/Labs/ITP115_L6_2_Wong_Andrew.py | 1,059 | 4.125 | 4 | # Andrew Wong, awong827@usc.edu
# ITP 115, Spring 2020
# Lab 6-2
def main():
# Get the words and convert them into various lists
firstWord = input("Please enter a word or statement: ").replace(" ", "").lower()
secondWord = input("Please enter a second word or statement: ").replace(" ", "").lower()
fir... | true |
b22ff6b7640b969d1721193139810d2534d00298 | banga19/TKinter-Tutorials | /mouse_click_events.py | 443 | 4.1875 | 4 | from tkinter import *
# when you click the left mouse button it displays the "left" on the console
# the same happens to when you click the right and middle mouse button
root = Tk()
def RightClick(event):
print("Right")
def LeftClick(event):
print("Left")
frame = Frame(root, width=500, ... | true |
267f66a3f4e5cbedb9cc20533236f7a730a17a27 | silverbowen/COSC-1330-Intro-to-Programming-Python | /William_Bowen_Lab5b.py | 843 | 4.375 | 4 | ## I used global constants for ease of modding
## in case we return to this program later
## START, END,and INCREMENT set the
## dimensions of the pyramid
START = 10
END = 1
INCREMENT = -1
## SYMBOL sets what the pyramid is made of
## I added spaces on either side of
## the star, to make it nicer
SYMBOL = ' * '
## m... | true |
959174c94e9050e2455c72f02567bab5a088a118 | silverbowen/COSC-1330-Intro-to-Programming-Python | /William_Bowen_lab4a.py | 2,417 | 4.40625 | 4 | ## Define main
def main():
## get measurements to convert, checking for useability
miles = float(input('How many miles would you like to convert? '))
if miles < 0:
print('\nError! You must enter a positive number of miles!\n')
else:
print('')
fahren = float(input('How many fahre... | true |
9a0cd7c3f79ad55ce32a7f771f4b146e8ef5aa8a | paripon123/DSC-430-Python | /Hw4/test.py | 1,281 | 4.125 | 4 | def random_list(i):
"""Random list of number from 0 - 100"""
import random
num_list = sorted(random.sample(range(0, 100), i))
return num_list
def sum_pair_search(lst,number): # O(log N) Binary Search
"""This is the function that do the binary search and the prove the calculation"""
# The list... | true |
323d64b2cd937ab44ba6450a603b8387563e1b55 | RamiroAlvaro/desafios | /maximum_subarray.py | 1,941 | 4.125 | 4 | """
Find the contiguous subarray within an array (containing at least one number)
which has the largest sum.
For example, given the array [−2, 1, −3, 4, −1, 2, 1, −5, 4],
the contiguous subarray [4, −1, 2, 1] has the largest sum = 6.
"""
def max_subarray_quadratic(list_):
if not list_:
return list_, 0
... | false |
e1a789720b6d0a025f2244347927cdc65c741658 | RafaelNGP/Curso-Python | /min_max_aula.py | 976 | 4.28125 | 4 | """
Min e Max
max() - Retorna o maior valor em um iteravel ou o maior de dois ou mais elementos.
min() - Retorna o menor item em um iteravel ou o menor de dois ou mais elementos.
"""
# Exemplos
lista = [1, 8, 4, 99, 34, 129]
print(max(lista))
dicionario = {'a': 1, 'b': 8, 'c': 4, 'd': 99, 'e': 34, 'f': 129}
print(max... | false |
50d722aa3751ae1ef216b25ad73bd2fc69f4d64a | RafaelNGP/Curso-Python | /tipo_booleano.py | 690 | 4.21875 | 4 | """
Tipo Booleano
2 constantes = Verdadeiro ou falso
True ou False
OBS: Sempre com a inicial maisucula.
# >>> num2 = 2
# >>> num3 = 4
# >>> num2 > num3
# False
# >>> num3 <= num2
# False
# >>> type(True)
# <class 'bool'>
"""
print("Atribuindo valor True para 'ativo'")
ativo = True
logado = False
print(ativo)
"""
O... | false |
7ca8e7a0cae3175b9ce91c9026d09e37d29f6cda | RafaelNGP/Curso-Python | /reduce_aula.py | 1,448 | 4.3125 | 4 | """
Reduce
OBS: A partir do Python3+ a funcao reduce() nao eh mais uma funcao integrada (built-in)
Agora precisamos importa-la a partir do modulo 'functools'
Guido van Rossum: utilize a funcao reduce() se voce realmente precisa dela, em 99% das vezes um
loop for eh mais legivel.
Para entender o reduce()
Imagine que ... | false |
3dc6b2bebf4a1fcf58586237d14c458075356708 | RafaelNGP/Curso-Python | /modulo_random.py | 1,653 | 4.28125 | 4 | """
Modulo Random e o que sao modulos?
- em Python, nada mais sao que outros arquivos Python.
- Todos os arquivos que foram criados ate agora sao considerados modulos.
- Deixar os programas mais simples e permitir a reutilizacao do codigo.
- Modulo Random -> Possui varias funcoes para geracao de numeros pseudo... | false |
2771c02c3f512cd85dbd8603ecc7b3279d7b02a5 | RafaelNGP/Curso-Python | /list_comprehension_p1.py | 1,251 | 4.5625 | 5 | """
List Comprehension
- Utilizando List Comprehension, nos podemos gerar novas listas com dados processados a partir de
outro iteravel.
# Sintaxe
[ dado for dado in iteravel ]
"""
def quadrado(valor):
return valor ** 2
# Exemplos
numeros = [1, 2, 3, 4, 5]
res = [numero * 10 for numero in numeros]
print(res)... | false |
9ee7d5d8f9ceb691d5a2883cce950a6272c9a2d0 | RafaelNGP/Curso-Python | /dicionarios_aula.py | 2,387 | 4.28125 | 4 | """
Dicionarios
Em algumas linguagens de programacao, os dicionarios sao conhecidos como mapas.
Dicionarios sao:
- colecoes do tipo chave/valor
- representados por chaves {}
- class <dict>
- 'chave': 'valor'
- Pode ser de qualquer tipo de dado.
"""
paises = {'br': 'Brasil', 'us': 'Estados Unidos'... | false |
5170b1ccf7a5e61e25cb0211d1f3c52a08f67472 | altareen/csp | /05Strings/asciicode.py | 2,511 | 4.3125 | 4 | # convert from a symbol to an ASCII number
numcode = ord("P")
print(numcode)
# convert from ASCII to a symbol
letter = chr(105)
print(letter)
# using the equality operator with strings
password = "basketball"
if password == "basketball":
print("login successful")
# digits come before lowercase letters
if "999" <... | true |
dbf4427d8e35dfb7930df9a865c93603e2106255 | altareen/csp | /05Strings/stringindexes.py | 659 | 4.1875 | 4 | # extracting a single letter from a string
fruit = "watermelon"
first = fruit[0]
print(first)
letter = fruit[5]
print(letter)
letter = "pizza"[1]
print(letter)
last = fruit[9]
print(last)
last = fruit[-1]
print(last)
letter = fruit[-10]
print(letter)
vegetable = "cauliflower"
quantity = len(vegetable)
print(quant... | true |
a24a893b62dcf1015c15aaa3d18f92d1cdea35b6 | silviu20/fzwork | /PythonWork/codeexer/reverse_integer.py | 481 | 4.25 | 4 | #! /usr/bin/python
# -*- coding: utf-8 -*-
"""
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
"""
class Solution:
# @return an integer
def reverse(self, x):
if x>0:
y_str = str(x)
y_str = y_str[::-1]
return int(y_str)
... | true |
c263dcbc053d4e0ad67b8e898c559501723b964f | ChocolatePadmanaban/AlgosAndDs | /mit_6.0001/ps1/ps1c.py | 1,415 | 4.15625 | 4 | import random
# Get the input
annual_salary= float(input("Enter the starting annual salary: "))
monthly_salary= annual_salary/12
# Fixed Parameters
semi_annual_raise=.07
r=0.04
portion_down_payment = .25
total_cost=1000000
down_payment = total_cost*portion_down_payment
#set problem parameters
epsilon = 100
bisect... | true |
425329f129d00e0607da7c566853e4876df5d628 | Feolips/ADS18A.10-Paradigma-Orientado-a-Objetos | /Listas de Exercício/POO Atividade 02 - Questões 07 e 08.py | 2,901 | 4.25 | 4 | # Aluno: Felipe Souza Vieira
# Atividade 02 para 12/02/2021
# Questões 07 e 08
'''
1. Crie uma classe com três variáveis: nome, sobrenome e salário mensal.
Defina um construtor para iniciar essas variáveis. Então, demonstre o
salário anual de três objetos da sua classe. OBS: inserir comentários
nos trechos ... | false |
94b55dc0a52f6788bf1649786a0f8a776c5697f3 | mariocpinto/0008_MOOC_Getting_Started_with_Python | /Exercises/Week_07/assignment_5.1.py | 702 | 4.21875 | 4 | # Write a program that reads a list of numbers until "done" is entered.
# Once done is entered, print count, total and avergae of numbers.
# If the user enters anything other than a number,
# print an error message and skip to the next number.
# Initialize count & sum
count = 0
sum = 0
while True :
input_n... | true |
37ecbf35cc9dabbaf94e13628ced1e53501a63cc | VladimirBa/python_starter_homework | /003_Conditional Statements/003_practical_2.py | 775 | 4.15625 | 4 | X_ODD_MESSAGE = "нечётное"
X_EVEN_MESSAGE = "чётное"
X_NEGATIVE_MESSAGE = "отрицательное"
X_POSITIVE_MESSAGE = "положительное"
x = float(input("Введите число: "))
x_length = len(str(abs(int(x))))
if x == 0:
print('Число: ', x)
elif x % 2 == 0 and x < 0:
print(x, f"{X_EVEN_MESSAGE} {X_NEGATIVE_MESSAGE} число."... | false |
7ef3e6b2bf9ed19c2853b541b16abadf1cc8b971 | DynamicManish/Guessing_game | /guessing_game.py | 1,448 | 4.15625 | 4 | import random as r
import time as t
random_value = r.randint(2,9)
guesses = 0 #user haven't made any guess yet!
value = 0
user_name = input('Howdy?May I know your name? ').strip().capitalize()
t.sleep(1)
print("Hello,"+"{}!".format(user_name))
t.sleep(1)
ques_choice = input('Are you ready to guess?[Y/N]... | true |
a99e65bc94d699eedf234968d4d1d4b6fd70f2ad | Fractured2K/Python-Sandbox | /tuples_sets.py | 1,029 | 4.34375 | 4 | # A Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
# Simple tuple
fruit_tuple = ('Apple', 'Orange', 'Mango')
print(fruit_tuple)
# Using constructor
fruit_tuple_constructor = tuple(('Apple', 'Orange', 'Mango'))
print(fruit_tuple_constructor)
# Get value by index
print(fruit_tuple[1... | true |
dc1b1e6fd9a2a88bdb48ab9ac21d806939640ed7 | HyperPalBuddy/Rando-Python-Codes | /Python_stacks.py | 1,090 | 4.21875 | 4 | def createStack():
stack = []
return stack
def isEmpty(stack):
return len(stack) == 0
def push(stack, number):
if len(stack) == size:
print("Stack Overflow")
return
stack.append(number)
def pop(stack):
if isEmpty(stack):
print("Stack Underflow")
... | true |
3a864c7b963ab09cc0cce9f326c1fa6ca80f1a7a | lucianoww/Python | /pybrexer0005.py | 304 | 4.4375 | 4 | '''
Solução para exercicios https://wiki.python.org.br/EstruturaSequencial
#05)Faça um Programa que converta metros para centímetros.
'''
metro = 100
valorcm = float(input('Digite valor em centimetros:'))
print('{} centimetros equivale a {} metros'.format(valorcm, valorcm/metro))
| false |
af3df83e40ec18a4433cbe8b3d35f86bf9d67655 | PHOENIXTechVault/Beginner-Python-Codes | /functions.py | 1,855 | 4.375 | 4 | # Manually printig out hello welcome without the use of a function
print("hello welcome")
print("hello welcome")
print("hello welcome")
print("hello welcome")
print("hello welcome")
def print_welcome_messsage(): #definig a function to print out the welcome message 5 times
print("Hello welcome\n"*5)
de... | true |
ee1b6cde06a6d04938042060fe2dade87224e5df | PHOENIXTechVault/Beginner-Python-Codes | /logical-operators.py | 920 | 4.15625 | 4 | # AND
a = 5
b = 5
c = 7
print(a == b and c > b) #return True since both conditions are True
print((a != b and c > b) and c > a) #return False since one of the conditions is False
# OR
print(a == b or c > a) #return True since both conditions are True
print(a != b or c > b) #return True... | true |
f25e37f28903a6986791b7162058af0ed17dffe8 | fredyulie123/Python-Programming | /Yifeng HE Exam2.py | 2,532 | 4.125 | 4 | # Exam 2 Yifeng He
# Trip Planner
planner_name = 'C:/Users/Yifeng He/Desktop/graduated/2nd graduate semester/Python/Trip Planner.txt' # create file path
print('Welcome to the road trip planner!')
## recording trip details
allstation = [] # prepare for append trip details
gasprice = 3 # gas per gallon price
m... | true |
696432da440dea2a60515d028a5e75fa1dc66528 | kamit17/Python | /W3Resource_Exercises/Strings/6.py | 733 | 4.625 | 5 | #6. Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged. Go to the editor
#Sample String : 'abc'
#Expected Result : 'abcing'
#Sample ... | true |
25ee3fc42087fd87633e5b9bd84834716f7e4e0d | kamit17/Python | /AutomateTheBoringStuff/Chapter7/password_checker.py | 764 | 4.125 | 4 | '''
A strong password is defined as one
that is at least eight characters long,
contains both uppercase and lowercase characters,
and has at least one digit.
You may need to test the string against multiple regex patterns to validate its strength.
'''
#Program to detect if password is strong or not
import re
#TODO: c... | true |
1d0d569f1d6d2693964cb452ebc2ef9b5628f1e7 | kamit17/Python | /Think_Python/Chp7/Exercise/ex6.py | 407 | 4.34375 | 4 | #Count how many words occur in a list up to and including the first occurrence of the word “sam”. (Write your unit tests for this case too. What if “sam” does not occur?)
def sam_count(names):
counter = 0
for name in names:
if name != 'sam':
counter += 1
else:
break
... | true |
45c70edbcf891323fca8d4fe90816adca83b4b1e | kamit17/Python | /Think_Python/Chp7/Examples/collatz_sequence_1.py | 1,072 | 4.28125 | 4 | def next_collatz(n):
if n % 2 == 0:
return n // 2
else:
return 3 * n + 1
def collatz_sequence(n):
""" assembles a list based on next collatz function and then prints that list. """
assert type(n) == int
assert n > 0
sequence = [n]
while n != 1:
n = next_collatz(n)
... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.