blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
89ffd786d982bc2c96ac235ec93b5ee0df0155b0 | pianorita/lab6 | /recitation test.py | 361 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 19 15:32:21 2017
@author: Rita
"""
def factorial(num):
if num == 1:
return 1
else:
return num * factorial(num - 1)
def main():
number= int(input('Enter a nonnegative integer:'))
fact = factorial(number)
print('T... | false |
99b3f30eff84ec601734b54f2bdf596fda25fc37 | Stevella/Early-days | /regexSearch.py | 1,092 | 4.3125 | 4 | # python 3
#regexSearch.py opens all .txt files in a folder and searches for any
# line that matches a user-supplied regular expression. results are printed to the screen
import os,re,glob,sys
#print(sys.argv[1])
if len(sys.argv) < 3:
#ask for directory and regexpattern if commandline arguments is insufficien... | true |
eae604c50b0450db7ee01da3b9600149bdca2ac2 | mark-kohrman/python_practice | /python_practice.py | 1,626 | 4.25 | 4 |
# 1. Write a while loop to print the numbers 1 through 10.
i = 1
while i <= 10:
print i
i = i + 1
# # # 2. Write a while loop that prints the word "hello" 5 times.
i = 1
while i <= 5:
print "hello"
i += 1
# 3. Write a while loop that asks the user to enter a word and will run forever until the user enters th... | true |
6afdce799ca7121e1ce5cf1274660407706cf732 | diketj0753/CTI110 | /P2_PayRate_DiketJohn.py | 472 | 4.25 | 4 | Hours=float(input('How many hours did you work last week? '))
# Creates a variable named PRate with user generated information.
GrossPay=float(input('How much did you make over this time? '))
# Multiplies the two variables together to determine Gross Pay and rounds to
# two decimal places.
PRate=float(GrossPay... | true |
7d8f996b50024904bdabed331ba996578ab1dd44 | planets09/HB_Final-Project | /ToDoList.py | 1,459 | 4.15625 | 4 | #NOTE: Final project
Rena_to_do = {"Shopping":"Groceries", "Pay_Bills":"Rent", "Pay_Utilities":"Water, Heat and Electric", "Repair": "Car", "Pet_Care": "Dog grooming"}
print "Welcome to Rena's TO DO List!"
while(True):
instructions = "Type A to see list., Type B to see Shopping, Type C to see Pay_Bills, Type D... | true |
fe33f96dae69f5469d83f9c69f7df77d4862557d | Irlet/Python_SelfTraining | /Find_multiply.py | 750 | 4.625 | 5 | """ In this simple exercise, you will build a program that takes a value, integer,
and returns a list of its multiples up to another value, limit.
If limit is a multiple of integer, it should be included as well.
There will only ever be positive integers passed into the function, not consisting of 0.
The limit will... | true |
d40b3893bef288d7a47b2ddb1537df43e3a6c85b | Irlet/Python_SelfTraining | /Text_analyser_1st_lvl.py | 1,107 | 4.1875 | 4 | # Ask over text and check: no. of characters, find vowels, every second char., no. of letters in words,
# find indicated character and element
my_text = input("Enter text: ")
number_of_text_char = len(my_text)
my_text_splitted = my_text.split()
vowels = "AaEeIiOoUuYy"
vowels_in_text = []
every_second_char = []
print(... | true |
a272c7266131e411c60eefaa5c2474dd466b780a | abanuelo/Code-Interview-Practice | /LeetCode/Google Interview/Interview Process/lisence-key-formatting.py | 2,189 | 4.15625 | 4 | '''
You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes.
Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be sho... | true |
33b19d17c43d84e6254c945b2fe105b058ccf692 | NGHTMAN/study_0022-03 | /NM5&7.py | 2,335 | 4.25 | 4 | # Наша функция
def create_dict():
# Первый список слов
first_words = input("Введи первый список слов через запятую: ")
# split - разбиение строки на части
# В нашем случае разделитель - запятая
first_list = first_words.split(',')
# Вывод количества слов с помощью поиска пробелов + 1, так как ... | false |
20fa547df238d952da01752d372a0e7118214c89 | dcantor/python-fun1 | /dictionaries/dictionary1.py | 526 | 4.53125 | 5 | # Dictionary sample (key value pair)
food = {'chocolate' : 101, 'cheese' : 102, 'soup' : 103}
print "Food dictionary is: "
print food
print
# what is the value for key chocolate
print food['chocolate']
print
# for loop test
print "iterate over the food dictionary"
for x in food:
print food[x]
# add new key/val... | true |
b7d768961b7dfa886096d40d0c808e04a9fc03f1 | vtu4869/Hangman | /hangmen.py | 2,664 | 4.28125 | 4 | #author: Vincent Tu
#modules to use for the game
import time
import random
#Asked for the username
name = input("Input your player name: ")
choice = False
#Different difficulties choice of words for the user to choose
ListOfDifficulties = [" ", "easy", "medium", "hard"]
EasyWords = ["listen", "phones", "games", "smil... | true |
1df0550461b931a48c1a0a2b6144cb5e418fca24 | jen8/Python-Chapters | /MISC/Collabedit_Tests_2.py | 1,055 | 4.25 | 4 | def num_odd_digits(n):
"""
>>> num_odd_digits(1234567)
2
>>> num_odd_digits(2468)
0
>>> num_odd_digits(1357)
4
>>> num_odd_digits(1)
1
>>> num_odd_digits(31)
2
"""
count = 0
while n:
if n % 2 != 0:
count = count + 1
... | false |
31ccc7fba49171694ab5b62dc42f61ea3961cf2d | jen8/Python-Chapters | /CH6/ch06.py | 2,713 | 4.15625 | 4 | # print "produces\nthis\noutput."
def sqrt(n):
approx = n/2.0
better = (approx + n/approx)/2.0
while better != approx:
print better
approx = better
better = (approx + n/approx)/2.0
return approx
#print sqrt(25)
def print_multiples(n):
i = 1
while i <= 6:
pri... | false |
b4ede7dd7bb11b4b691e0830040f6f8388ac1434 | rekhert/Python3 | /lesson4taskA.py | 880 | 4.1875 | 4 |
'''
Задание A
Напишите функцию которая будет конвертировать время
из 24 часового представления в 12 часовое представление с суффиксом AM
если это первая половина дня и PM если вторая
'''
time = input("Введите время в формате ЧЧ:ММ")
def timeconverter (time):
h = int(time[:2])
m = int(time[-2:])
if h > 2... | false |
93c406f2a2c14bce1fd123df16aba1dadb53e732 | dtilney/minimax | /ttt.py | 2,947 | 4.125 | 4 | '''
ttt.py
Implements a general tic tac toe board.
'''
class Board:
'''
__init__
Sets up an empty tic tac toe board
R: number of rows
C: number of columns
N: number to get in a row to win
'''
def __init__(self, R, C, N):
self.R = R
self.C = C
self.N = N
s... | false |
0ea1e3024677c97325c93bf4d7984b11521d64b6 | CereliaZhang/leetcode | /217_Contains_Duplicate.py | 745 | 4.125 | 4 | '''
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Input:... | true |
a41aef1333c2dbfef42e99ef46b288dd2cfeffc7 | yousuf550/Basic_Python_Projects | /Grocery_Cashier.py | 1,452 | 4.21875 | 4 | #Grocery Store
'''
The program evaluates the total bill price and the discount price of the bill
according to the membership grade. The product price and buying list are both
presented in dictionary format. Then we create two functions that read the
dictionaries to get the bill price and the discount price.
'''
... | true |
fd0035ec10de79eb8fe60970267e7780238b7a11 | Sumedh3113/Python-codes | /pangram.py | 796 | 4.21875 | 4 | """
Write a Python function to check whether a string is pangram or not.
Note : Pangrams are words or sentences containing every letter of the alphabet at least once.
For example : "The quick brown fox jumps over the lazy dog"
"""
import string
def ispangram(str1, alphabet=string.ascii_lowercase):
str1.lower()
... | true |
7e047589467b22af0f793518d32f31b4c583da4a | yenandrew/CIS3260 | /Assignment 1/Chapter 3/Assignment 3.9.py | 1,102 | 4.3125 | 4 | #Write a program that reads the following information and prints a payroll statement:
#Employee’s name (e.g., Smith)
#Number of hours worked in a week (e.g., 10)
#Hourly pay rate (e.g., 9.75)
#Federal tax withholding rate (e.g., 20%)
#State tax withholding rate (e.g., 9%)
name=input("Enter employee's name: ")
... | true |
be34debf56b4f2435eda7501f8b78cdb6d6b3f9c | yenandrew/CIS3260 | /Assignment 1/Chapter 4/Assignment 4.8.py | 370 | 4.3125 | 4 | # (Sort three integers) Write a program that prompts the user to enter three integers
# and displays them in increasing order.
n1, n2, n3 = eval(input("Enter 3 integers separated by commas no spaces"))
if n1 > n2:
n1, n2 = n2, n1
if n2 > n3:
n2, n3 = n3, n2
if n1 > n2:
n1, n2 = n2, n1
print("So... | true |
f08d2357990b536e5dd686f565d4c9973b99eccc | tecnoedm/PyChat | /PyChat/client/gui/helper/stack.py | 1,328 | 4.1875 | 4 | #!/usr/bin/env python2
##
# PyChat
# https://github.com/leosartaj/PyChat.git
#
# Copyright (c) 2014 Sartaj Singh
# Licensed under the MIT license.
##
"""
Upper key and lower key functionality
when pressed gives last written text
"""
class stack:
"""
Makes a stack
that can be cycled
up and down
"... | true |
b04ca479ff18300017bcf2b1f853fbf4a34ec1ca | mmorrow1/Simple-Calculator | /Simple Calculator.py | 604 | 4.25 | 4 | #simple calculator
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
choice = input("Do you want to add, subtract, multiply, or divide? ")
if choice.upper() == "ADD":
answer = num1 + num2
print(num1, "+", num2, "=", answer)
elif choice.upper() == "SUBTRACT":
answer = num1 ... | false |
8dd41e21cde0e2106cbed0f6a9ada793c16035b3 | Brenno-Daniel/estudos-python | /app-python/aula8_lambda.py | 932 | 4.15625 | 4 | # nome da função,
# lambda para dizer que é uma função anonima,
# um parametro que é necessário, no caso lista,
# devolver uma lista e quantas letras tem cada palavra dentro da lista
contador_letras = lambda lista: [len(x) for x in lista]
lista_animais = ['cachorro', 'gato', 'elefante']
print(contador_letras(lista_an... | false |
5859033462563e5a8977e2dd568bbb75f78807f8 | Martijnde/Jupyter_Portfolio | /Python basics/Regular expressions.py | 1,457 | 4.28125 | 4 | #A regular expression is a sequence of characters that describes a search pattern.
#In practice, we say that certain strings match a regular expression if the pattern can be found anywhere within those strings (as a substring).
#The simplest example of regular expressions is an ordinary sequence of characters. Any st... | true |
cfa66cc2bac72dfc53c43e7035ad3f4851a16e3f | MatheusSaloma0/Clustering | /Python/point.py | 708 | 4.15625 | 4 | # Estrutura representando um ponto de d coordenadas(dimensoes).
# Cada ponto apresenta um identificador(index) que corresponde a ordem deste
# durante o processo de leitura do arquivo contendo todos os pontos.
class Point:
# Inicializa um ponto.
def __init__(self, coordenates, index):
self.coordenates ... | false |
8b1385f2e1e7646d18c29b309c2d78cdb6661d8a | georich/python_bootcamp | /rock_paper_scissors/rps_ai.py | 1,386 | 4.375 | 4 | from random import choice
player_wins = 0
computer_wins = 0
to_win = 3
print("Time to play rock paper scissors, first to three wins!")
while player_wins < to_win and computer_wins < to_win:
player = input("Enter your choice: ").lower()
computer = choice(["rock", "paper", "scissors"])
print(f"The computer ... | true |
030d63e2bb296078a7306d414dcd5e5a0212d540 | georich/python_bootcamp | /lambdas_and_builtin/filter.py | 676 | 4.15625 | 4 | # returns only values which return true to the lambda
l = [1, 2, 3, 4]
evens = list(filter(lambda x: x % 2 == 0, l))
print(evens)
# combining filter and map
names = ["Lassie", "Colt", "Rusty"]
#return a list with the string "Your instructor is "
# + each value in array, only if less than 5 characters
# sends filte... | true |
8346b24ee1c6abb2484391b16940152612a48af4 | gadtab/tutorials | /Python/ex01_ConvertKM2Miles.py | 218 | 4.15625 | 4 | print("This program converts kilometers to miles")
number = float(input("Please enter a number in kilometers: "))
print("You have entered", number, "km")
print("which is", round(number / 1.609344, 4), "miles")
| true |
3e462da7979ae4d023ff1617d1530f46bd9b382d | yasykurrafii/Python_Tkinter | /Basic_Code/Icon.py | 778 | 4.125 | 4 | from tkinter import *
#library untuk memasukan image
#yang di install libnya adalah lib Pillow
#karena Lib Pillow adalah upgrade-an dari lib PIL
from PIL import ImageTk, Image
root = Tk()
root.title("Learn Tkinter")
#Change Icon
root.iconbitmap('C:/Users/Rajwa/Documents/Rafii/Python/Tkinter/Basic_Code/fb.ic... | false |
946f7c3d02074091f7ea3d2f588982d730ee5922 | magnusm18/assignment5 | /max_int.py | 303 | 4.125 | 4 | num_int = int(input("Input a number: ")) # Do not change this line
max_int = 0
while True:
num_int = int(input("Input a number: "))
if num_int < 0:
break
if num_int > max_int:
max_int = num_int
print("The maximum is", max_int) # Do not change this line
print ("lalala") | false |
79ebe029b626361c6a180e10949585183bafcbc3 | niuniu6niuniu/Leetcode | /IV-Perm&Comb.py | 562 | 4.25 | 4 | # # # Combination # # #
# Example
# For several given letters, print out all the combination of it's letters
# Input: 1 2 3
# Output: 1 2 3
# 1 3 2
# 2 1 3
# 2 3 1
# 3 1 2
# 3 2 1
from itertools import permutations,combinations
def comb(n,*args):
_list = []
... | true |
abb6d702f4d52de7239e13a6d601a6578444243b | niuniu6niuniu/Leetcode | /LC-Robot_Moves.py | 1,521 | 4.1875 | 4 | # # # Robot Return to Origin # # #
# There is a robot starting at position (0, 0), the origin, on a 2D plane.
# Given a sequence of its moves, judge if this robot ends up at (0, 0)
# after it completes its moves.
# The move sequence is represented by a string, and the character moves[i]
# represents its ith ... | true |
37d300cd616de4bde0c9d60c6c0cbcf722c6805e | niuniu6niuniu/Leetcode | /Sort_Heap.py | 1,037 | 4.15625 | 4 | # Heap Sort
# Best case & Worst case: O(nlogn)
# Average case: O(nlogn)
# Idea: Build max heap & Remove
# Heapify
# Set root at index i, n is the size of heap
def heapify(arr, n, i):
largest = i # Initialize largets as root
l = 2 * i + 1 # Left child
r = 2 * i + 2 # Right child
... | true |
23de9a39fae97d6b47d6c3e07aef68415e7f57f2 | ParkDongJo/python3_algorithm_training | /algorithm/sort_and_searching.py | 2,079 | 4.15625 | 4 | '''
정렬과 탐색에 대해서 내용 정리
'''
'''
python 리스트 정렬
- sorted(list) : 정렬된 새로운 리스트를 얻어냄
- list.sort() : 해당 리스트를 정렬함
- sorted(list, reverse=True)
- list.reverse() or list.sort(reverse=True)
'''
'''
문자열 정렬
- sorted() 정렬에 이용하는 key를 지정
- sort() 정렬에 이용하는 key를 지정
'''
str_list = ['abcd', 'xy... | false |
1cbe3db493217a7e138404e710b221e9d2424532 | periyandavart/ty.py | /leap.py | 285 | 4.125 | 4 | print("Enter the year")
year=input()
if ((year%4==0)and(year%100!=0)):
print("The year is a leap year")
elif((year%100==0)and(year%400==0)):
print("The year is a leap year")
elif(year%400==0):
print("The year is a leap year")
else:
print("The year is not a leap year")
| true |
d78dfa16dff3d735f5ec17d5b757ee279741d52b | changwang/Union-Find | /src/datastructure.py | 1,550 | 4.25 | 4 | '''
Created on Nov 8, 2009
@author: changwang
Define some data structures that could be used by other data structure.
'''
class Node:
''' The node class represents the node in the disjoint set and union-find tree. '''
def __init__(self, value):
''' construct function. '''
# The ... | true |
3a7b06004f0d3f2079c7adcb3c808b85c666de9e | pawwahn/python_practice | /searches/bisect_algorithm.py | 833 | 4.21875 | 4 | # Python code to demonstrate the working of
# bisect(), bisect_left() and bisect_right()
# importing "bisect" for bisection operations
import bisect
# initializing list
li = [1, 3, 4, 4, 4, 6, 7]
# using bisect() to find index to insert new element
# returns 5 ( right most possible index )
print ("The rightmost inde... | true |
0f2637e48a465145b7aaedd032287a493d250998 | pawwahn/python_practice | /dateutil/no_of_days_since_a_date.py | 382 | 4.46875 | 4 | # Python3 program to find number of days
# between two given dates
from datetime import date
def numOfDays(date1, date2):
return (date2 - date1).days
cur_date = date.today()
#print(cur_date)
yy,mm,dd = cur_date.year, cur_date.month, cur_date.day
#print(yy,mm,dd)
# Driver program
date1 = date(1947, 12, 13)
date... | true |
ad8d1457b814b898f82616824adb1bd04c51eb02 | pawwahn/python_practice | /lists.py | 1,429 | 4.21875 | 4 | a = []
print(a)
print(type(a))
b = [1,2,3]
print("length of b is: {}".format(len(b)))
c = [{'a':1,'b':2}]
print("length of dictonary c is: {}".format(len(c)))
d = [{'a':1},{'b':2},{}]
print("length of d is: {}".format(len(d)))
a = [1,2,3]
print("The value of a is: {}".format(a))
a.extend([4,5,6])
... | false |
0073e180f453878708da80052f1c3c0201a424f6 | pawwahn/python_practice | /logical_or_tough/triplets.py | 707 | 4.125 | 4 | # Sample Input 0
# 5 6 7
# 3 6 10
# Sample Output 0
# 1 1
# Explanation 0
#
# In this example:
#
# Now, let's compare each individual score:
#
# , so Alice receives point.
# , so nobody receives a point.
# , so Bob receives point.
# Alice's comparison score is , and Bob's comparison score is . Thus, we return the arr... | false |
081a411eaa519f60eb34c97f5653f6ba1a0e4f54 | pawwahn/python_practice | /oops_python/create_class_and_object_in_python.py | 426 | 4.21875 | 4 | class Parrot:
# class attribute
species = 'bird'
#instance attribute
def __init__(self,name,age):
self.name = name
self.age = age
#instantiating the class
blu = Parrot("blu",5)
#prints the class object
print(blu)
# 1st way of retriving class attribute
print(Parrot.species)
#2nd way ... | true |
c72a5e7822f21baa6c077a6dbf168de8ae08e6d7 | pawwahn/python_practice | /regular_expressions/reg_exp8_replace.py | 885 | 4.28125 | 4 | # replace a word in the given string
# to replace a word or substring , we need to compile by giving the search pattern
import re
str = "rat pat 'zat' 'fat', 'Mat' ,'hat' ,'Lat', zaq cat string integer"
#regx = re.compile("[d-z]at") # output --- food food food food Mat food Lat zaq cat string int... | false |
bf135b43e94f7e7863b621876f4e5e415e431911 | pawwahn/python_practice | /mnc_int_questions/data_abstraction.py | 1,157 | 4.28125 | 4 | class Employee:
__count = 10
def __init__(self):
Employee.__count = Employee.__count+1
def display(self):
print("The number of employees",Employee.__count)
def __secured(self):
print("Inside secured function..")
def get_count(self):
print("Employee count is :",Emp... | true |
c9cbfafce0956bb999662e6ad30ff458c2bf7ea4 | pawwahn/python_practice | /exceptions/except2.py | 356 | 4.15625 | 4 | lists = ['white','pink','Blue','Red']
clr = input('Enter the color you wish to find ??')
print(clr)
try:
if clr in lists:
print ("{} color found".format(clr))
else:
print("Color not found ")
except Exception as e:
print (e)
print ("IOException: Color not found")
finally:
print("There... | true |
036925d524f9407f11d1fc957881ef8c565d03b4 | pawwahn/python_practice | /numpy concepts/numpy1.py | 657 | 4.53125 | 5 | import numpy as np
a = np.array([1,2,3])
print("The numpy array created is {}".format(a))
print("The numpy array type is {}".format(type(a)))
print("The length of numpy array is {}".format(len(a)))
print("The rank of numpy array is {}".format(np.ndim(a)))
print("*************")
b = np.array([(1,2,3),(4,5,6,7)])
print... | true |
c6b80e32d305b9007a2a2f38cc2ae25b1d3c5afc | Viveknegi5832/Python- | /Practicals.1.py | 1,155 | 4.59375 | 5 | ''' Ques.1 Write a function that takes the lengths of three sides :
side1, side2 and side3 of the triangle as the in put from the user using input function and
return the area and perimeter of the triangle as a tuple. Also , assert that sum of the length of
any two sides is greater than the third side
''... | true |
855ff19d45c7bde65a07fc84a27cc10bc848919f | Viveknegi5832/Python- | /Practicals.7.py | 2,282 | 4.34375 | 4 | '''
Ques.7 Write a menu driven program to perform the following on strings :
a) Find the length of string.
b) Return maximum of three strings.
c) Accept a string and replace all vowels with “#”
d) Find number of words in the given string.
e) Check whether the string is a palindrome or not.
'''
def len_st... | true |
deb484aa1ad4612c916100e222b7629065824a6b | asadmshah/cs61a | /week2/hw.py | 1,689 | 4.15625 | 4 | """
CS61A Homework 2
Asad Shah
"""
from operator import add
from operator import mul
def square(x):
"""
Return square of x.
>>> square(4)
16
"""
return x * x
# Question 1
def summation(n, term):
"""
Return the sum of the first n terms in a sequence.
>>> summation(4, square)
30
"""
t, i = 0, 1
while i... | true |
43bfeab6ec2085e850820b2ed4adb8ed3d94ac12 | andyzhuravlev/python_practice | /task_1.py | 918 | 4.1875 | 4 |
"""
Есть список a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89].
Выведите все элементы, которые меньше 5.
Самый простой вариант, который первым приходит на ум — использовать цикл for:
for elem in a:
if elem < 5:
print(elem)
Также можно воспользоваться функцией filter, которая фильтрует элементы согласно зада... | false |
a48bf0b58650a53816aaa76dafee51b5bc369ae5 | marcmanley/mosh | /python_full/HelloWorld/test.py | 972 | 4.28125 | 4 | # How to print multiple non-consecutive values from a list with Python
from operator import itemgetter
animals = ['bear', 'python', 'peacock',
'kangaroo', 'whale', 'dog', 'cat', 'cardinal']
print(itemgetter(0, 3, 4, 1, 5)(animals))
print(animals)
print(type(animals))
# Slicing indexes
course_name = "Pytho... | true |
bbc19563fe8ff2af7dc2f97aa0fbdb945cdcb0cf | py1-10-2017/OliviaHan-py1-2017 | /Funwithfunctions.py | 736 | 4.125 | 4 | def odd_even():
for i in range (1, 5):
if i%2 != 0:
print "Number is",i,".", "This is an odd number."
else:
print "Number is", i,".", "This is an even number."
odd_even()
# a is for the list. b is the number be multiplied. c is for the results list
def multiply(a,b):
for... | false |
f2fdb7074f35dab7a898f8981df7bd5102abaf22 | godaipl/python3study | /2python基础/1数据类型和变量/1数据类型.py | 556 | 4.1875 | 4 | # 数据类型
# 整数 int
a = 1
b = 100
c = -100
d = 0
# 浮点数 float
f_a = 1.0
# 1.23乘以10的9次方
f_b = 1.23e9
print('1.23e9 is ', f_b)
# 字符串 string
str1 = 'a'
str2 = "'a'"
str3 = "I'm OK"
str4 = "I'm \"OK\""
print(str4)
# 使用 r'' 来标注相应内容无需转义
print(r'\t\n')
# 使用以下方式替换\n 换行操作
print('''aaaaaa
bbbbbb
cccccc''')
# 布尔值 boolean
print(T... | false |
5b05967d412a28c2085b2de504eec80831b6f67b | maskalja/WD1-12_Functions | /12.3_Geography Quiz/main.py | 429 | 4.15625 | 4 | import random
count = 0
capitals = {"Slovenia": "Ljubljana", "Austria": "Vienna", "Hungary": "Budapest", "USA": "Washington"}
countries = ["Slovenia", "Austria", "Hungary", "USA"]
for country in countries:
count += 1
r = random.randint(0, count-1)
answer = input(f"What is the capital of {countries[r]}? ")
if an... | true |
37f5758d6dd77e5a90ccb4a4fd11e8f8b8649041 | kevinjyee/PythonExcercises | /Excercise02_21.py | 480 | 4.4375 | 4 | '''Write a program that prompts the user to enter a monthly saving amount and
displays the account value after the sixth month. Here is a sample run of the
program:
'''
def main():
interest = .05;
total = 0;
savings = int(input("Enter the monthly saving amount: "));
for i in range(0,6):
savi... | true |
bad718105eadf1f0206a4335278b0f74415f457b | kevinjyee/PythonExcercises | /Excercise04_19.py | 510 | 4.3125 | 4 | '''(Compute the perimeter of a triangle) Write a program that reads three edges for a
triangle and computes the perimeter if the input is valid. Otherwise, display that
the input is invalid. The input is valid if the sum of every pair of two edges is
greater than the remaining edge. Here is a sample run'''
def main()... | true |
5e47ac70f312466460693882b93afc8746a3017b | Barret-ma/leetcode | /63. Unique Paths II.py | 1,807 | 4.28125 | 4 | # A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
# The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
# Now consider if some obstacles are added to... | true |
f6b4a44ec75285d1d43e9767e3c0ed3a6cde25ca | Barret-ma/leetcode | /543. Diameter of Binary Tree.py | 1,407 | 4.375 | 4 | # Given a binary tree, you need to compute the length of the
# diameter of the tree. The diameter of a binary tree is the
# length of the longest path between any two nodes in a tree.
# This path may or may not pass through the root.
# Example:
# Given a binary tree
# 1
# / \
# 2 3
# ... | true |
4b8d187a174a15db189f2095ccd00d689b4b991a | Barret-ma/leetcode | /112. Path Sum.py | 1,507 | 4.125 | 4 | # Given a binary tree and a sum, determine if the tree has
# a root-to-leaf path such that adding up all the values along
# the path equals the given sum.
# Note: A leaf is a node with no children.
# Example:
# Given the below binary tree and sum = 22,
# 5
# / \
# 4 8
# / / \
# 11 13 4
# ... | true |
aea69a498caab1fe218aa0df397d93e9e5a937d7 | alexanch/Data-Structures-implementation-in-Python | /BST.py | 2,038 | 4.28125 | 4 | """ Binary Search Tree Implementation: search, insert, print methods. """
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST(object):
def __init__(self, root):
self.root = Node(root)
def insert(self, new_val):
... | true |
3ef383f3fa3969f09a16c32ae03a47a039b42737 | Ibbukanch/Python-programs | /pythonprograms/Algorithm/sqrtnewton.py | 255 | 4.46875 | 4 | # program to find the sqrt of number using newton method
# Take input from user
n=float(input("Enter the Number"))
t = n
# calculates the sqrt of a Number
while abs(t- n/t) > 1e-15 * t:
t = (n/t + t) / 2
# Print the sqrt of a number
print(round(t,2))
| true |
bb44f2a3045953f5c844f233f07e4e310c9aebf4 | ajaybhatia/python-practical-2020 | /18-practical.py | 1,753 | 4.25 | 4 | '''
Practical 18:
Perform following operations on two matrices.
1) Addition 2) Subtraction 3) Multiplication
'''
def print_matrix(matrix):
for row in range(len(matrix)):
for col in range(len(matrix[0])):
print(matrix[row][col], end=" ")
print()
def matrix_addition(a, b):
if le... | false |
b701916d7032b3449af2d316638b828cfcbe4267 | ajaybhatia/python-practical-2020 | /27-practical.py | 1,289 | 4.125 | 4 | '''
Practical 27
Perform following operations on dictionary
1) Insert 2) delete 3) change
'''
book = {
1: "Compute sum, subtraction, multiplication, division and exponent of given variables input by the user.",
2: "Compute area of following shapes: circle, rectangle, triangle, square, trapezoid and parallel... | true |
056eec7bf4c59ea34c4248341d289d168cff0771 | imshile/Python_Regex_Engine | /Python_Regex_Search_Vs_Match.py | 2,149 | 4.375 | 4 | # Python Regex
# re Regular expression operations.
# This module provides regular expression matching operations similar to those found in Perl.
# Both patterns and strings to be searched can be Unicode strings (str) as well as 8-bit strings (bytes).
# However, Unicode strings and 8-bit strings cannot be mixed: th... | true |
6a62677db52869b3aeb03c3c1ee041a98623ab91 | imshile/Python_Regex_Engine | /Python_Regular_Expressions_Named_Group.py | 2,785 | 4.3125 | 4 | # Python Regular Expressions
# Regular expressions (called REs, or regexes, or regex patterns) are essentially a tiny, highly specialized programming language embedded inside Python
# and made available through the re module. Using this little language, you specify the rules for the set of possible strings that you w... | true |
8dbc06994034f1868cb5bc9ea6675c41b7600fbe | jake20001/Hello | /everydays/20200814/4.py | 1,623 | 4.125 | 4 | # coding: utf-8
"""
@author: zhangjk
@file: 14.py
@date: 2020-02-28
说明:iter 迭代器
"""
import sys # 引入 sys 模块
def f1():
# list=[1,2,3,4]
list = "hello world"
it = iter(list) # 创建迭代器对象
while True:
try:
print(next(it))
except StopIteration:
... | false |
aa61fb4c0ea2ae4e8d0b3c89c1e3c690d056a993 | PabloNunes/AceleraDev | /2_Segundo_Modulo/main.py | 2,437 | 4.3125 | 4 | from abc import ABC, abstractclassmethod
class Department:
# Department class: Stores department name and code
def __init__(self, name, code):
self.name = name
self.code = code
class Employee(ABC):
# Employee class: A abstract class for inheritance
# Constants for our Employees
... | true |
cf428b248dd28892aba4affa59ddb983211cc495 | andrefisch/EvanProjects | /text/emailsToSpreadsheet/splitNames.py | 1,054 | 4.21875 | 4 | # Extract first, last, and middle name from a name with more than 3 parts
# determine_names(listy)
def determine_names(listy):
dicty = {}
lasty = []
middley = []
# first spot is always first name at this point
dicty['first_name'] = listy[0]
dicty['middle_name'] = ""
dicty['last_name'] ... | true |
58f1a8fe9eeea28a52f4742358d4095a80309a51 | luizhuaman/platzi_python | /p16_limitRecursividad.py | 2,451 | 4.1875 | 4 | def me():
"""
- INICIO
Este código teiene como propósito Encontrar el límite de recursión teórico de mi máquina y compararlo con el real.
1. Defino una funcion recursiva
2. Le paso dos argumentos: n y resultado_suma haciendo referencia a un número n y mi suma.
3. Imprimo el resulta... | false |
be6d059dbd1b40680f329f5f38330c506e32f85e | ontasedu/eric-courses | /python_advanced_course/Ericsson Python Adv Solutions/q1_nested_if.py | 783 | 4.1875 | 4 | '''
Get the user to input a list of numbers.
Then output a menu for the user to select either the sum/average/max/min.
Then execute the selected function :-
- using nested ifs
- using a dict
'''
from __future__ import division
def average(numbers):
return sum(numbers) / len(numbers)
'get user to ... | true |
307264ac158f25b11562a3f745eaec1d71c4e8ef | jonyachen/TestingPython | /bubblesort3.py | 735 | 4.28125 | 4 | #Bubble sort that's a combo of 1 and 2. while and for loop geared towards FPGA version
myList = [5, 2, 1, 4, 3]
def bubblesort(list):
max = len(list) - 1
sorted = False
i = 0
j = i + 1
while not sorted:
sorted = True
for j in range(0 , max): # or (0, length)
a = lis... | true |
c7c79c54d109229c76ebf8c4ad5b6a309958385c | AlexandreBalataSouto/Python-Games | /PYTHON BASICS/basic_05.py | 363 | 4.28125 | 4 | #List
names = ["Alo","Marco","Lucia"]
print(len(names))
print(names)
names.append("Eustaquio")
print(names)
print(names[1])
print(names[0:3])
print("------------------Loop 01--------------------------")
for name in names:
print(name)
print("------------------Loop 02--------------------------")
for index in r... | true |
41f389f0a9213dc6aada4ae8ffc136e7133a9145 | dinglight/corpus_tools | /scripts/char_frequency.py | 1,071 | 4.375 | 4 | """count the every char in the input file
Usage:
python char_frequency.py input_file.txt
"""
import sys
import codecs
def char_frequency(file_path):
"""count very char in the input file.
Args:
file_path: input file
return:
a dictionary of char and count
"""
char_count_dict = dict()... | true |
3159b7ac32f5389d64ee595deca47a02d38e4d5f | FrimpongAlbertAttakora/pythonWith_w3school | /18-Array.py | 1,595 | 4.5625 | 5 | #Arrays are used to store multiple values in one single variable:
cars = ["Ford", "Volvo", "BMW"]
#You refer to an array element by referring to the index number.
'''
x = cars[0]
print(x)
'''
#Modify the value of the first array item:
'''
cars[0] = "Toyota"
print(cars)
'''
#Use the len() method to return th... | true |
debbe8e2675c001a9ef890b134bd00fd1218e807 | FrimpongAlbertAttakora/pythonWith_w3school | /20-Inheritance.py | 2,930 | 4.65625 | 5 | #Inheritance allows us to define a class that inherits all the methods and properties from another class.
#Parent class is the class being inherited from, also called base class.
#Child class is the class that inherits from another class, also called derived class.
#Any class can be a parent class, so the syntax is ... | true |
5688b0bcff2e91ab54d0b6ba33b6d825adc4d93d | manankshastri/Python | /Python Exercise/exercise61.py | 304 | 4.25 | 4 | #function to check if a number is prime or not
def is_prime(n):
if (n>1):
for i in range(2,n):
if(n%i ==0):
print(n,"is not Prime\n")
break
else:
print(n,"is Prime\n")
else:
print(n,"is not Prime\n")
is_prime(31)
| true |
ea407b375b5f63593b1b16e16ccb7d8d10281f0c | manankshastri/Python | /rps.py | 1,291 | 4.1875 | 4 | from random import randint
def rock_paper_scissors():
player = input('Rock (r/R) , Paper (p/P) or Scissor (s/S)? ')
# a random number is generated (1/2/3)
c = randint(1, 3)
if player == 'r' or player == 'R':
print("O vs", end=" ")
f = 0
p = 1
elif player == 'p' or player ... | false |
8b443ea764bf7e9c05ff2da982fade77b90fc742 | isobelfc/eng84_python_data_collections | /dictionaries.py | 1,422 | 4.1875 | 4 | # Dictionaries
# Dictionaries use Key Value pairs to save the data
# The data can be retrieved by its value or the key
# Syntax {}
# Within the dictionary we can also have list declared
# Let's create one
dev_ops_student = {
"key": "value",
"name": "James",
"stream": "devops",
"completed_lesson": 3,
... | true |
5fe2d1240e185760046c977c435724982867b4b2 | NehaNayak09/Coding-Tasks | /marathon programs/marathon_time_calculator.py | 433 | 4.125 | 4 | # Marathon time calculator
pace = input("Enter Pace in km (mm:ss): ")
mm, ss = map(int, pace.split(":")) #spliting the input in minute and second
paceInSec = mm * 60 + ss #converting the pace in sec
distance = float(input("Enter Distance (km): "))
time = int(paceInSec * distance)
#time in... | true |
af6a76432233bc4da387b2d96ac3f2977e2e0e7a | imaadfakier/turtle-crossing | /player.py | 1,059 | 4.1875 | 4 | from turtle import Turtle
SHAPE = 'turtle'
COLOR = 'black'
STARTING_POSITION = (0, -280)
MOVE_DISTANCE = 10
FINISH_LINE_Y = 280
class Player(Turtle):
"""
Inherits or sub-classes from Turtle class of Turtle module;
creates an instance of the Player class each time a Player
object is created.
"""
... | true |
19c2dfbeb81139e9c4b88db28c8ba9fbbc5a9c5f | Nazar3000/Python_Task2 | /task2.py | 2,379 | 4.3125 | 4 | import re
def input_password():
"""A function that accepts a comma separated list of passwords
from console input.
:return: password: Password string"""
password = input("Input your passwords: ")
password_validator(password)
return password
def password_validator(password):
"""A functi... | true |
4ddccf6bcc18b5c1b2fd4b6484d1f534453721b6 | fengzongming/python_practice | /day27_反射和内置方法/demo_02_反射.py | 693 | 4.21875 | 4 | """
hasattr: 检测属性和方法
getattr: 获取属性和方法
delattr: 删除属性和方法
"""
class Foo:
f = '类的静态变量'
def __init__(self, name, age):
self.name = name
self.age = age
def say_hi(self):
print('hi,%s' % self.name)
obj = Foo('mike', 73)
# 检测对象是否有某属性和方法
print(hasattr(obj, "name"))
print(hasa... | false |
9cd8c350db842c1e8d9bd403f1fd720842db6d44 | CodeVeish/py4e | /Completed/ex_10_03/ex_10_03.py | 641 | 4.25 | 4 | #Exercise 3: Write a program that reads a file and prints the letters in decreasing order of frequency.
#Your program should convert all the input to lower case and only count the letters a-z.
# Your program should not count spaces, digits, punctuation, or anything other than the letters a-z.
# Find text samples fro... | true |
e45cfc043dabf423f899827ad3dfb0913204f85a | CodeVeish/py4e | /Completed/ex_05_02/ex_05_02.py | 567 | 4.1875 | 4 | largest = None
smallest = None
while True :
feed = input('Enter a number: ')
if feed == 'done' :
break
try :
float_feed = float(feed)
except :
print('Invalid Input')
continue
if largest is None :
largest = float_feed
if smallest is None :
smalle... | true |
c5bbf518cb35e39b0927709c77dde307e400a386 | ferdiokt/py4Eexercise | /exercise5_2.py | 591 | 4.25 | 4 | # Compute the largest and the smallest program
largest = None
smallest = None
# Loop to keep inputting until user enter done
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
inum = int(num)
except:
print('Invalid input')
continue
... | true |
4c1ade5b1b5b1fb6e3effba351450e881795381d | tchoang408/Text-Encryption | /Vigenere_cipher.py | 2,308 | 4.21875 | 4 | #Tam Hoang
# this program encrypting a sentence or words using vigenerr
# cypher.
from string import*
def createVigenereTable(keyword):
vigenereTable = []
alphabetList = []
keywordList = []
alphabet = ascii_lowercase
for i in range(len(alphabet)):
alphabetList.append(alphabet[i])
... | true |
d9f85aa910b7bb9cd4b6257713947f2ee23e2f09 | alhambrasoftwaredevelopment/FIAT-LINUX | /Bounties/10ToWin.py | 666 | 4.1875 | 4 | print("")
print("I can tell you if the sum of two numbers is 10 or if one of the numbers is 10 ")
print("False means that neither the sum nor one of the numbers equals 10 ")
print("True means that either the sum or one of the numbers equals 10 ")
print("")
while True:
num1 = int(input("give me a number: "))... | true |
a23bfb4d750b9526f6f495c87f2ce8eb2fbbf098 | RobZybrick/TelemetryV1 | /Step_2.py | 1,109 | 4.25 | 4 | # Using python, create CSV file with 5 rows and 5 columns with specified numbers
# Store the CSV file onto the desktop
# majority of the code referenced from -> https://www.geeksforgeeks.org/working-csv-files-python/
# file path location referenced from -> https://stackoverflow.com/questions/29715302/python-just-openin... | true |
ab9f6fb487d4b3a1cf182982d0fbdf467925cb05 | kubicodes/100-plus-python-coding-problems | /3 - Loop Related/2_largest_element_of_list.py | 589 | 4.34375 | 4 | """
Category 3 - Loop Related
Problem 5: Largest Element of a List
The Problem:
Find the largest element of a list.
"""
"""
Input must be a list of numbers.
Returns the largest value of the list
"""
def largestElement(listOfNumbers):
assert not type(listOfNumbers) != list, ('You have to give a list as input.')
... | true |
dc35bb302151340f6c295c8f5ec59e9965950f5c | kubicodes/100-plus-python-coding-problems | /3 - Loop Related/3_sum_of_squares.py | 807 | 4.15625 | 4 | """
Category 3 - Loop Related
Problem 3: Sum of Squares
The Problem:
Take a number as input. Then get the sum of the numbers. If the number is n. Then get
"""
"""
Input must be a number.
Returns the sum of the numbers. If the number is n. Then get
0^2+1^2+2^2+3^2+4^2+.............+n^2
"""
def sumOfSquares(number):... | true |
9ebcbb00242c1753bcbd2aae984aacb09b3af811 | pingao2019/lambdata13 | /Stats/stats.py | 937 | 4.15625 | 4 |
class Calc:
def __init__(self, a, b):
''' __init__ is called as a constructor. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.'''
self.a = a
self.b = b
def add_me(self):
return self.a + sel... | true |
970a24b801a9009e4126b71e54bf478022b1bae5 | alaouiib/DS_and_Algorithms_Training | /Fibonacci_2_algos.py | 1,448 | 4.25 | 4 | from functools import lru_cache
# O(2^n) Time
def fibonacci_slow(n):
if n in [0, 1]:
return n
return fibonacci_slow(n - 1) + fibonacci_slow(n - 2)
# O(n) Time
@lru_cache(maxsize=1000)
def fibonacci(n):
if n in [0, 1]:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
# ~ O(n) Ti... | false |
a7a9c403e54281cbec2f86ea955f976de3306cf3 | alaouiib/DS_and_Algorithms_Training | /second_largest_element_bst.py | 1,523 | 4.25 | 4 |
def find_rightmost_soft(root_node):
current = root_node
while current:
if not current.right:
return current.value
current = current.right
def find_rightmost(root_node):
if root_node is None:
raise ValueError('Tree must have at least 1 node')
if root_node.right:
... | true |
6c5c74f931b6def3987696eeca57dd57de2fc937 | joshhilbert/exercises-for-programmers | /Exercise_35.py | 848 | 4.15625 | 4 |
# Exercise 35: Picking a Winner
# 2019-05-26
# Notes: Populate an array then pick a random winner
import random
# Get names for array
def get_entrant():
value = input("Enter a name: ")
return value
# Pick winner after all names entered
def pick_winner(n):
value = random.randint(0, n)
... | true |
52fdeebc2126aba020c08ceaadc5140003b652ba | joshhilbert/exercises-for-programmers | /Exercise_11.py | 576 | 4.25 | 4 |
# Exercise 11: Currency Conversion
# 2019-05-24
# Notes: Convert currency to another currency
# Unable to solve due to exchange rate conversion issues
# Define variables
user_euro = int(input("How many euros are you exchanging? "))
user_exchange_rate = float(input("What is the exchange rate? "))
# Unsure h... | true |
3ff448ac7500b9f42566403de2a3ee0f14d40709 | ClaudiaN1/python-course | /bProgramFlow/challenge.py | 507 | 4.3125 | 4 | # ask for a name and an age. When both values have been entered,
# check if the person is the right age to go on on an 18-30 holiday.
# They must be over 18 and under 31. If they are, welcome them to the
# holiday, otherwise print a, hopefully, polite message refusing them entry.
name = input("Please enter your name: ... | true |
f600ba0043ca20d5b6c3055189699b457eeea12d | jieck/python | /guess.py | 2,119 | 4.1875 | 4 | def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
# FILL IN YOUR CODE HERE...
... | true |
3ac7dff543c156e29f8c04246f99ab6fe6cb0936 | JaredGarza444/Programacionavanzada | /preguntadatos.py | 1,417 | 4.25 | 4 | #En este programa se estableceran funciones que
#Permitiran preguntas datos sin ninguna validacion
import datetime
#Los datos otorgados pueden ser de diferente tipo
def main():
Datostring=input ("Dame un dato tipo string:")
#Los datos string no es necesario procesarlos
#Ya que todos los datos otrogados por el u... | false |
c2b40bdfab321a1d4111d7b272f9453b966d3f0d | kvntma/coding-practice | /python_exercises/Exercise 5.3.py | 432 | 4.125 | 4 | def check_fermat(a, b, c, n):
if ((a ** n) + (b ** n)) == c ** n and n > 2:
print("Holy smokes, Fermat was wrong!")
else:
print("No, that doesn't work")
def check_numbers():
a = int(input("Choose number for a: \n"))
b = int(input("Choose number for b: \n"))
c = int(input("Choose num... | false |
cd967e9601b0e5da13b32a4b5b4f057792e714c2 | qordpffla12/p1_201011101 | /w6Main12.py | 353 | 4.125 | 4 | import random
def upDown(begin, end):
rn = random.randrange(begin, end, 1)
num = 0
count = 0
while num != rn:
num = int(raw_input("enter num: "))
count = count+1
if num < rn:
print 'up'
elif num > rn:
print 'down'
else:
prin... | true |
7488518bd1c6ad6778022c0f70eec312be866d5b | AFranco92/pythoncourse | /controlstatements/homework.py | 454 | 4.21875 | 4 | maths = int(input("Enter maths marks: "))
physics = int(input("Enter physics marks: "))
chemistry = int(input("Enter chemistry marks: "))
if maths >= 35 and physics >= 35 and chemistry >= 35:
print "You have passed the exam!"
average = (maths+physics+chemistry)/3
if average <= 59:
print "You got a ... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.