blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
bd69d86a839a6200a41c9fabfce206e374bc2ef7
billwestfall/python
/miscellaneous/math/002/001.py
194
3.78125
4
import matplotlib.pyplot as plt import numpy as np def f(x): return x*(x - 2)*np.exp(3 - x) x = np.linspace(-0.5, 3.0) # 100 values between -0.5 and 3.0 y = f(x) plt.plot(x, y) plt.show()
d228931a1abf22852e4f4aa9898790858e42fb9c
sadimauro/projecteuler
/euler045_v1.py
387
3.5
4
#!/usr/bin/python3 import time tStart = time.time() import stevepe as s def getTri(i): return i*(i+1)/2 i = 286 foundTri = 0 while True: tri = getTri(i) if s.isPentagonal(tri) and s.isHexagonal(tri): foundTri = int(tri) break i += 1 print(__file__ + ": answer: " + str(foundTri)) pri...
45f489ea9e360398c7c0706255ccb4956bf9e33b
KirillSmirnow/inf-exam-2021
/demo2021/17.py
385
3.9375
4
def is_number_of_interest(number): return number % 3 == 0 and number % 7 != 0 and number % 17 != 0 and number % 19 != 0 and number % 27 != 0 numbers_count = 0 max_number = 0 for number in range(1016, 7937 + 1): if is_number_of_interest(number): numbers_count += 1 if number > max_number: ...
479aa9e843f4f50540e384d17d9256ffdd39a8e1
aberi/delta_robot-tic-tac-toe
/test.py
994
3.875
4
import board import numpy as np def test_two_row(b): row = board.two_row(b, "X") print row def test_all_two_rows(b): row = board.all_two_rows(b, "X") print row def test_third_space(b, letter): print "\nPossible rows of three: " rows = board.all_two_rows(b, letter) for r in rows: ...
a0ba58f23860bce0391f6ad743161c716f26a7b2
bebetaro/studyPython
/KELLY/sum.py
332
3.984375
4
def sumBetweenNum(numA, numB): number = 0 for i in range(numA, numB): number += i number += numB return number firstNumber = input("please input first number: ") secondNumber = input("please input second number: ") answer = sumBetweenNum(int(firstNumber), int(secondNumber)) print(f"Answer is...
4a4dd1b35f417b80d020a61ab59f78e909c1def7
ikonbethel/Python-code
/coders apprentice files/vowelcounter1.py
425
4.15625
4
# # message = input("Enter your message: ") new_message = "" VOWELS = ("aeiou") for letter in message: if letter.lower() not in VOWELS: new_message += letter #print("A new message has been created: ",new_message) #print("\nYour new message without vowels is: ",new_message) print("There...
a66a37a3e580d6c105870c46229fe4271ee801dc
yingnan521/python_pycharm
/IP.py
477
3.890625
4
# n=int(input('enter an integer >=0: ')) # fact=1 # for i in range(2,n+1): # fact=fact * i # print(str(n) + ' factorial is ' + str(fact)) #随机产生IP地址,并且打印到屏幕上 import random section1 = random.randint(0,255) section2 = random.randint(0,255) section3 = random.randint(0,255) section4 = random.randint(0,255) random_ip = ...
43079d3f4ba9e57455b8e8c3820c1e31c1b686d5
Iambob4ever/Code
/Code Base/composite_types.py
1,370
3.765625
4
######################################################################################## #Dicts person = { "first_name": "John", "last_name": "Doe", "nationality": "Canada", "birth_year": 1980 } #Retrieving and setting elements: print(person["first_name"]) person["first_name"] = "Jane"...
6934f3fe0bb4e9195dc52ec744641665cdb50849
vincenttuan/PythonCourse
/lesson1/Hello_String.py
225
4
4
s = 'she sell sea shell on the sea shore' print(s.find('sea')) print(s.find('happy')) keyword = 'sea' if s.find(keyword) != -1 : print(s + " 內容中有 " + keyword) else : print(s + " 內容中沒有 " + keyword)
aea2cf41ff1d27346c5cebfa9c8569800b288ae6
leon0241/adv-higher-python
/Term 1/Book-1_task-1_2.py
384
4.1875
4
#Write a program that will accept integers input one at a time from the keyboard and save these in an array until the integer -1 is entered def integers(): intArray = [] loop = False while loop == False: testInt = int(input("enter a whole number")) if testInt == -1: loop = True;...
21a6ca9f6166541283a5351abedab400072dcf35
oliwka212/1AP4
/python/zadanie2.py
442
3.78125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def main(args): start= stop= 0 while start<1: start= int(input('Podaj liczbę m: ')) while stop < 1 or stop <= start: stop= int(input('Podaj liczbę n: ')) for i in range(start, stop+1): print(i, '', end = '') else: ...
0937ac81f78fb6328c4b7d67cf3e57a0ad9abce3
tpunhani/DailyProblems
/Partition Labels/PartitionLabels.py
524
3.921875
4
# A string S of lowercase English letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts. def partitionLabels(S: str) -> list: end_idx = {c: i for i, c in enumerate(S)} ...
11519fc234471db7078f10b1d015601a82af45fa
AndrewBartelsmeyer/web-caesar
/caesar.py
617
4
4
import string from helpers import alphabet_position, rotate_character, check_int from sys import argv def user_input_is_valid(cl_args): if len(cl_args) == 2 and check_int(cl_args[1]): return True else: return False def encrypt(text,rot): new_text = "" for x in text: new_text =...
9a19f9cdb0d5b01ac8f1215eb2831c62775ff3bd
nakano0518/algolism-data-structure-by-python
/algo-data-structure2/09_search.py
1,177
3.78125
4
# 探索 # 配列[1,2,5,8,10]において、ランダムに選択される数字n(nは1以上10以下の整数)が # 配列に含まれる場合はその位置(インデックス番号)を、 # 含まれない場合はNoneを出力するプログラムを作成せよ # 線形探索 def linear_search(arr): for i in range(0, len(arr)): if key == arr[i]: return i return None if __name__ == '__main__': import random key = random.randint(1, 10)...
aac229ff321b6c9ef76bdaf1eb96eca6a0c32b21
BenjaminAage/Kattis_Problems
/symmetricOrder.py
269
3.71875
4
num = "" theSet = set() count = 1 while num != 0: num = int(input()) if num == 0: break for i in range(num): name = input() theSet.add(name) print("SET", count) for j in theSet: print(j) count += 1
2e9601c975e5b6ed5302105bcbdfb93eccd0e6a9
kelasterbuka/Python3.x_Dasar_Programming
/Versi Lama 31 - input output file/main.py
732
3.9375
4
# input output file """ w = write mode / mode menulis dan menghapus file lama, jika file tidak ada maka akan dibuat file baru r = read mode only / hanya bisa baca a = appending mode / menambahkan data di akhir baris r+ = write and read mode """ # membuat file text file = open("data.txt",'w') file.write("ini adala...
5f312f02415a8f02678f1425d20b16234cc99c11
3014zhangshuo/python-learn
/exception/base.py
849
3.65625
4
"""Exception Sytnax: IndentationError SytnaxError NameError DataAccess: IndexError # [1, 2][3] ValueError # int('a') TypeError # 2 + "a" KeyError # {'a': 1}['b'] Import: ModuleNotFoundError # import a python3 ImportError # import a python2 """ import traceback def ...
7153aaf3e83a37007acac28cb66099c8795e8606
isaolmez/core_python_programming
/com/isa/python/chapter2/Exercise_2_7.py
267
3.84375
4
input = raw_input("Enter a string: \n") counter = 0 while counter < len(input): print input[counter], counter += 1 print for i in range(len(input)): print input[i], print for c in input: print c, print for i, c in enumerate(input): print c,
4517129e228b43428d4e6637ca6a69bff59c6d99
test-patterns/command
/command/record_order_command.py
558
3.625
4
""" Sample problem featuring the command pattern. """ from command import Command class RecordOrderCommand(Command): """ A command to record a new order """ def execute(self): """ Base method to execute the commmand """ pizza = "pizza" if int(self._order.quantity) > 1: piz...
58c8231edc0de94fe2dbdc5a2951289e8f8b32a5
tu-nguyen/katas
/python/Equal Sides Of An Array.py
2,807
4.375
4
# Title: Equal Sides Of An Array # Rank: 6 kyu # Language Version: Python 3.6.0 ## Instructions ## # You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is ...
b150a5f7f5dfae9b18c089fc437c01d239326f42
sora5801/Lab3_v.1.0
/SQLdatabase.py
14,971
3.578125
4
import sqlite3 import requests from bs4 import BeautifulSoup from WebScraper import WebScraper class SQLdatabase: def __init__(self): try: self.sqliteConnection = sqlite3.connect('SQLite_Python.db') cursor = self.sqliteConnection.cursor() print("Data...
7b3201b1b3efbd7884fc6bed914c74a8b8500441
szymonln/Python
/riddle.py
701
3.640625
4
#odpytuje dwie liczby, zakres, pozniej zgadujemy #random -> randint import random try: x = (int)(input("Podaj poczatek przedzialu do losowania: ")) except ValueError: print ("Ojej, a przeciez to nie jest liczba...") exit() try: y=(int)(input("Podaj koniec przedzialu: ")) except ValueError: print...
43cfce6bf796f6215d020228e75511977401e629
orloffanya/python
/029.py
302
4.34375
4
# 29 Ask the user to enter an integer that is over 500. Work # out the square root of that number and display it to two decimal places. import math integer = input("please choose a number whole number over 500 ") integer = int(integer) print(f"here is it's square root {round(math.sqrt(integer), 2)}")
83a62052af37397f40d2a266077d38e84bf7c326
nope-applications/OCR_hangul_extraction
/hwang/cnn/cnn_keras.py
3,431
3.515625
4
from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, BatchNormalization, Activation from keras.layers.convolutional import Conv2D, MaxPooling2D from keras.utils import np_utils import numpy as np np.random.seed(1234) img_rows = 28 img_cols = 28 trainin...
858b80b5df792c5e53dc4424af7fd6238eb82b6e
fenglihanxiao/Python
/Module01/DataStructure/SliceDataStructure.py
1,292
4.1875
4
""" 1. Slice only operate on list and tuple, not including set and dict """ list1 = [1, 2, 3, 4, 5, 6] list2 = [1, 2, 3] tuple1 = (101, 32, 121) set1 = {84, 32, 84, 32, 12} dict1 = {"name": "Feng", "age": 18} """ 1. @parm1: start index 2. @param2: end index (exclusive) 3. @param3: step ""...
6fe814fbc53f39bb1ea4c611d678632d7adcb942
Zeeguitarlove/Python-2019
/while.py
278
3.78125
4
import os os.system('clear') ############################ # While Loop ############################ counter = 0 while(counter <= 10): print("The Counter Is:" + str(counter)) print("\n") counter += 1 count = 0 while(count < 5): print("-------->" + str(count)) count += 1
0fd12202b13fd7449733b3d99e9884d42c59be22
paras666/PythonClass
/Ex2.py
389
4.09375
4
##input Function## x1 = int(input("Enter the value of X1:")) x2 = int(input("enter the value of x2:")) print("\n") print("Value you have entered:",x1) print("Data type:", type(x1)) print("\n") print("value you jave entered",x2) # print("data type, ") print("Add:",(x1+x2)) print("subtraction:",(x1-x2)) print("divi...
1532bac3d56e6fbadb3967911803c418e0602588
ariannasg/python3-training
/essentials/hello-numerics.py
1,248
4.375
4
#! usr/bin/env python3 from decimal import * # Numeric types int and float are fundamental built-in types (all types are classes). # Everything is an object in Python 3. x = 7 print(x) print('x is type {}'.format(type(x))) print(x / 3) print(x // 3) # 2 -> removes the remainder of 7/2 print(x % 3) # 1 -> just the ...
de45f234e63c773fd0dd26f3d52acb6e8f08d32a
OrionSuperman/ajax-note-program
/app/models/Note.py
1,626
3.9375
4
""" Sample Model File A Model should be in charge of communicating with the Database. Define specific model method that query the database for information. Then call upon these model method in your controller. Create a model using this template. """ from system.core.model import Model class Not...
8c84b194d5007ac731061b5da5d72561f5b08985
yiyulanghuan/deeplearning
/docs/content/regularization/dropout.py
516
3.625
4
# %% # During eval Dropout is deactivated and just passes its input. # During the training the probability p is used to drop activations. Also, the activations are scaled with 1./p as otherwise the expected values would differ between training and eval. # https://discuss.pytorch.org/t/model-eval-vs-with-torch-no-grad/...
0116dcceed4a512529830c524ffffaec54c73b1a
paradigm777/csis42
/p15.py
5,159
4.34375
4
# Program name: p0.py # Your Name: Alex Stoykov # Python Version: 3.4.4 # Date Started - Date Finished: 08/31/17 # Description: ''' COPY/PASTE DESCRIPTION FROM THE ASSIGNMENT: Write a program which computes the sum and product of two numbers entered by the user. Algorithm: 1) Ask the user to enter two numbers. 2) stor...
e314dc52032717e711f85f62285d17faaa911de0
yasinsb/Classification-Report-as-DataFrame
/example.py
870
3.640625
4
# example for classification_report_df function import numpy as np import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from classification_report_df import classification_report_df from random import randint, uniform, normalvariate #----generat...
8e22fe013ff2149491f7a6a954f558fa21c2c56d
zchen0211/topcoder
/python/leetcode/combinatorial/949_largest_time.py
1,715
3.65625
4
""" 949. Largest Time for Given Digits (Easy) Given an array of 4 digits, return the largest 24 hour time that can be made. The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from 00:00, a time is larger if more time has elapsed since midnight. Return the answer as a string of length 5. If no v...
99cc5ff30c19527a2331661d4ef4700a62b0b54b
ephremworkeye/python-advanced
/LFMRLD/Map_demo.py
931
4.46875
4
# map() function returns a map object(which is an iterator) of the results after applying the given function to each of a given iterable # syntax: map(func, iter) # we can define either in lambda or regular funciton and pass it to the map function def square_number(x): return x**2 square_numbers = lambda x: x**2...
a810d20976fb7669eb8bb31f4078ac61e9eb3c4c
dorukkilitcioglu/sphinx_test
/gha_aut_test/functions.py
314
3.5625
4
import numpy as np def relu(x: np.ndarray) -> np.ndarray: """Rectified Linear Unit Parameters ---------- x: np.ndarray The input array Returns ------- np.ndarray Input array with ReLU applied """ return np.maximum(x, 0.) def uncovered_fn(): return 'a'
30d7ab3790743be48e54836f2b957a771184f3a1
jfdousdu/pythonProject
/jianzhioffer/jiaonan/JZ23.py
2,475
3.984375
4
''' 二叉搜索树的后学遍历序列 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。 如果是则返回true,否则返回false。假设输入的数组的任意两个数字都互不相同。 ''' # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # class BinaryTree: # def createBinaryTree(self, root, node): # if root is None: # ...
8134f859595791e7807b723c84ab48ec3498f7ec
syurskyi/Python_Topics
/018_dictionaries/_templates/Python 3 Most Nessesary/9.1. Creating a dictionary_!cool!.py
1,922
3.625
4
# # -*- coding: utf-8 -*- # # d = di.. ; print(d) # Создаем пустой словарь # # {} # d = di.. a 1 b 2 ; print(d) # # {'a': 1, 'b': 2} # d = di.. a 1 b 2 ; print(d) # Словарь # # {'a': 1, 'b': 2} # d = di.. a 1 b 2 ; print(d) # Список кортежей # # {'a': 1, 'b': 2} # d = di.. a 1, b 2; print(d) # Списо...
7e0b9c0db44c1d5f604e8d291b8556eef1064fbc
VineeS/BookStore
/backend.py
1,766
3.828125
4
import sqlite3 def Create_db(): connected = sqlite3.connect("book.db") cur = connected.cursor() cur.execute("CREATE TABLE IF NOT EXISTS book (Id INTEGER PRIMARY KEY, Title text, Author text, Year INTEGER, ISBN INTEGER)") connected.commit() connected.close() def ViewAll(): connected = sqlite3....
7276cff4b6d1d25fcec328169fd462561b7c829b
xiaohugogogo/python_study
/python_work/chapter_2/name_cases.py
512
4.21875
4
name = "Eric" print("Hello " + name + ", would you like to learn some Python today?") name = "zHAO yU Hu" print(name.lower()) print(name.upper()) print(name.title()) sentence = 'Albert Einstein once said, "A person who never made a mistake never tried anything new."' print(sentence) famous_person = "Albert Einstein"...
01dc7f7154d6dbe9ef5be154ba76ba7d0a257e9a
hkamra/Python
/python-masterclass-udemy/HelloWorld/strings.py
1,193
4.4375
4
print("Today is a good day to learn Python") print("Python is fun") print("Python's string are easy to use") print('We can even include "quotes" in strings') print("hello" + " world") # this is concatenation greeting = "Hello" name = "Himanshu" print(greeting + name) # if we want to add space, we can add that too pr...
c27a3d08bcca30a5de768893600a7f02feb731ca
HPaulowicz/code-challenges
/divisors.py
964
4.09375
4
#Create a function named divisors/Divisors that takes an integer and returns an array with all of the integer's divisors(except for 1 and the number itself). If the number is prime return the string '(integer) is prime' (null in C#) (use Either String a in Haskell and Result<Vec<u32>, String> in Rust). #Example: #divi...
c0199a342d9bc38df2694d57bf7867a3238ae711
alexander-jiang/sage-solitaire-bot
/game/test_deck.py
1,366
3.578125
4
import unittest from deck import Deck class TestDeck(unittest.TestCase): def test_deck_create(self): deck = Deck(seed=123) assert len(deck) == 52 first_card = deck.peek(n=2)[0] second_card = deck.peek(n=2)[1] third_card = deck.peek(n=3)[2] assert len(deck) == 52 ...
91df925284f481184a8592e54a9b1181552d9bd7
belachkar/sgcodewars
/day30/day30.py
4,308
4.125
4
import timeit import random def one_two(): return random.randrange(1,3) # Basic Test ''' length = 60000 treshold = 0.05 count = Counter(one_two_three() for _ in range(length)) # past here student's function print(1 in count, '1 is present') print(2 in count, '2 is present') print(3 in count, '3 is present') pri...
ed7422c81c01307c6c159262155339081c30b22a
dvp-git/Python-Crash-Course
/dictionary-6.7.py
785
4.5
4
## Exercise 6.7 People ## Make an empty list called people people = [] ## Making 2 dictionaries representing 2 different people person = {'first' : 'Darryl', 'last': 'Prabhu', 'Code':'dprabhu', } people.append(person) person = {'first' : 'Rahul', 'last...
2fb52454d94ec05cab9ba907dd56c6995659a694
devoden/py-snake
/main.py
2,447
3.578125
4
import pygame import time import random pygame.init() font = pygame.font.SysFont("None", 35) # window size width = 800 height = 600 display = pygame.display.set_mode((width, height)) pygame.display.set_caption('Snake') # colors green = (0, 255, 0) black = (0, 0, 0) red = (213, 50, 80) # head size segment_size = 20...
2c58f9a4e62dc8dfeed60f17e650f9cf0e1f2fa9
sizijay/python
/stack-from-queue.py
843
4
4
class Queue: def __init__(self): self.items = [] def enqueue(self, item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def isEmpty(self): return self.items == [] def size(self): return len(self.items) class Stack: ...
da09d9a31bf7751a0c7739586deff4f9d62b99fc
sdoktatas/first-project
/functions.py
266
3.765625
4
def sqr(c): return c ** 2 def plus(a=1, b=2):#default paraméterek result = a + b #print(result) #return result return a + sqr(b) plus(2,3) plus(7,3) plus()#default pareméterrel print(plus(3,2)) r = plus(1,3) print("Eredmény " + str(r))
ff28d268f609d6716fcf23d3dc22cc83a204ef3a
eep0x10/Pyton-Basics
/2/py1.py
247
3.9375
4
#Faça um Programa que peça dois números e imprima o maior deles. num1=int(input(print("Digite o 1° número"))) num2=int(input(print("Digite o 2° número"))) if num1>num2 : print(str(num1)+">"+str(num2)) else : print(str(num2)+">"+str(num1))
3af94454e4b81c4471752a4f4f045a3b48ebfef5
venkor/Python3Learning
/ex6.py
1,460
4.53125
5
# setting a variable type_of_people to 10 type_of_people = 10 # setting a new formatted string variable 'x' which conatins text and variable type_of_people inside of it. x = f"There are {type_of_people} types of people." # setting new string named binary binary = "binary" # setting new string named do_not do_not = "don...
18aecbab675750101cc1afebdeec7e553ab63cad
lephuoccat/NLP
/process_data.py
544
3.59375
4
from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import PorterStemmer # Process the dataset def process(data): data = data.lower() words = word_tokenize(data) # stemming ps = PorterStemmer() words = [ps.stem(word) for word in words] # remove st...
b3e9e209d7612c966f307052559a0b040ae7b53b
Rutvik2610/Python-Playground
/Name the States Game/India version/main.py
1,250
3.75
4
import turtle import pandas screen = turtle.Screen() screen.title("India States Game") screen.bgpic('blank_states_img.gif') # To get the screen co-ordinates of the states # def get_mouse_click_coor(x, y): # print(x, y) # # # turtle.onscreenclick(get_mouse_click_coor) # # turtle.mainloop() dataset = pandas.read_c...
60fe6ca5be95d5490e5c10628f0a9b4d460c9455
CSchuster1995/Ex
/ObjEx1.py
980
3.875
4
class Person: def __init__(self, name, email, phone): self.name = name self.email = email self.phone = phone self.friends = [] self.greeting_count = 0 self.unique_greet = [] def greet(self, other_person): print('Hello {}, I am {}!' .format(other...
449d2e9b3e86bf17da06f2921024221b8fcc0ad2
nakiselev/examples-code-tranning
/algo/multy_matrix.py
515
3.78125
4
def multiply(matrix1, matrix2): result = [] for k in matrix1: b = [] for i in zip(*matrix2): res = sum([a*b for a,b in zip(k, i)]) b.append(res) result.append(b) return result #example m1 = [[1, 2, 3], [3, 1, 1], [3, 4, 3] ] m2 = [[4, 2, 2...
6300022ff1df3d84228267a4746d18d1592095c5
FisicaComputacionalPrimavera2018/ArraysAndVectorOperations
/vectoroperations.py
1,254
4.28125
4
import math #### FUNCTIONS # The name of the function is "norm" # Input: array x # Output: the norm of x def norm(x): tmp = 0 for v in x: tmp += v*v norm_x = math.sqrt(tmp) return norm_x def vectorSum(x, y): #z = x + y This doesn't work! # First we check if the dimensions of x and y # are the sam...
ceb6206f4ec6b75220384b30a6dc1ea4156b241f
KVChandrashekar/Basic_Python-questions
/Fibonacci.py
197
4.125
4
def Fibonacci(n): if n<=0: print("Incorrect input") elif n==1: return 0 elif n==2: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2) print(Fibonacci(int(input('enter the number'))))
529fe5c47cf0c9b40fbe6faaf5bc2e623cd377b4
cgarrido2412/PythonPublic
/Learning Tutorials/Practice Python/MASTER.py
6,194
4.25
4
#! /usr/bin/env python3 def integer_check(x): try: int(x) return True except ValueError: return False def character_input(): #X (denotes difficulty rating out of five) ''' Create a program that asks the user to enter their name and their age. Print out a message addressed to...
f661f10be8a74544405302e61323da7c467c2f4a
alikslee/Python-itheima-2019
/01-Python核心编程/代码/05-函数/01-函数一/hm_02_函数的注意事项.py
616
3.984375
4
# 1. 使用一个函数 2.测试注意事项 # 需求:一个函数:打印hello world # info_print() # 报错 # 定义函数 def info_print(): print('hello world') # 调用函数 info_print() """ 结论: 1. 函数先定义后调用,如果先调用会报错 2. 如果没有调用函数,函数里面的代码不会执行 3. 函数执行流程*** 当调用函数的时候,解释器回到定义函数的地方去执行下方缩进的代码,当这些代码执行完,回到调用函数的地方继续向下执行 定义函数的时候,函数体内部缩进的代码并没有执行 """
5e04bb5764a828fb9af35ea91152d0a0d2fb926d
channamallikarjuna/DAAPROJECT
/src/readcsv.py
279
3.5625
4
import csv class readcsv: def readcsv(self): tweets=[] with open('tweets.csv', newline='') as csvfile: data = csv.DictReader(csvfile) for row in data: #print(row['text']) #tweets.append(row['Tweet Content']) tweets.append(row['text']) return tweets
db6226a893d3bd65e5cf88770b0577e4b3d2b2dd
tobyt99/pythoncolt
/rps.py
1,394
4.21875
4
from random import choice, randint player_wins = 0 computer_wins = 0 winning_score = 5 while player_wins < winning_score and computer_wins < winning_score: print(f"Player Score: {player_wins} R2D2 Score: {computer_wins}") player = input("Make your selection...\n...Rock... \n...Paper...\n...Scissors...\n").lowe...
b756b858d3d727b484699d6ba1ff7edefed2a1a1
nflondo/myprog
/python/crash_course/ch8/ex8-9-list-passing.py
638
3.9375
4
# ex 8-9, 8-10, 8-11 def make_great(magicians_list): great_list = [] while magicians_list: current_magician = magicians_list.pop() current_magician += ' the Great' great_list.append(current_magician) while great_list: current_magician = great_list.pop() magi...
da586b92c23b5b2743c2c599f0454e16d9bcbdad
KisaZP/SergeyKisil
/17.py
167
3.875
4
r = int(20) R = float(input('Введите R:')) if R > 20: S = 3.14 * (R**2 - r**2) print(S) else : print('Не правильные данные')
855fbc874c9e07a71845ae0069b24f09682f94e5
pythohshop/pythonintro
/stringsort.py
410
4.0625
4
""" Sorts a string Assumption: String has no white space """ string_to_sort = input('text: ') temp_list = [] for i in range(len(string_to_sort)): temp_list.append(string_to_sort[i]) for i in range(len(string_to_sort)): for j in range(i+1, len(string_to_sort)): if temp_list[i] > temp_list[j]: ...
de0f62ae6967ac4b15bdeb56ad3c92775ea88062
RaddKatt/Python-Scripts
/ATBS/04-Lists/06-passingReference.py
575
4.375
4
# This program demonstrates how List references work # Written in Python 3.5.1 on Mac def eggs(someParameter): someParameter.append('Hello') spam = [1,2,3] eggs(spam) print(spam) # Even though spam and someParameter contain separate references, # they both refer to the same list # This is why the append('Hello')...
b138816a1082da30ce38fcb13b6391c2c98859ec
nirmalhk7/flow-problem
/src/algorithms/utils.py
1,365
3.59375
4
from graph import * def depth_first_search(graph, s, t): for node in graph.nodes(): node.visited = False path = Path(s) if not _dfs(graph, s, t, path): path = None for node in graph.nodes(): del node.visited return path def _dfs(graph, cur, t, path): cur.visited = True ...
c9e95691125546b24ed2b23ecf050940baebf0a6
leeo1116/PyCharm
/Projects/intern/temp/neighbor_team.py
619
4.09375
4
__doc__ = """ Problem 1: Given non-duplicating list A, B and C. Determine which elements appear in both A and B but not in C Problem 2: You have a list of integers. Count the number of times each integer appears in the list Problem 3: Extract the name/value pairs from the following string and put into hash user_id(la...
186594c012873be1a883bb7ebdf7071dca7bcf9e
eemets/Python-labs
/2/2_7.py
426
3.859375
4
x = int(input("x =")) y = int(input("y =")) if(x>0) and (y>0): print("a) принадлежит первому квадранту") if(x<0) and (y>0): print("б) принадлежит второму квадранту") if(x<0) and (y<0): print("c) принадлежит третьему квадранту") if(x>0) and (y<0): print("д) принадлежит четвертому квадранту")
8e5d787dfe76c71072bfbeb0313c177fa463f6a1
kcruz411/textAdventureGWC
/textAdventureGWC.py
4,593
4.03125
4
strength = 10 strenth = int(strength) name = input("Hi! What's your name?") print("Alright, ", name, ". Welcome to Text Adventure.") print("Strength level = ", strength) print("You were hiking on a normal Saturday and decided to leave the trail.") print("You quickly find that you're lost and the sun is setting quick.")...
8134daac769c686de502d30c1cbbf240a85f499a
dtmacroh/KattisCode
/bitbybit.py
1,887
3.859375
4
# bitbybit # Author: Debbie Macrohon # Description: Using various if-else statements and hardcoded commands # for pseudo bit-manipulation using an array. def main(): over = False loop(over) def loop(over): while not over: rounds = int(input()) array = ["?"]*32 if rounds ==0: over = True loop(over)...
2b4fae40d15e1b08321040d461b5e797cd0ac2a7
radian3/Math_Functions
/general/gradecalculator.py
805
3.96875
4
def main(): totalPercent = 0 totalPoints = 0 assignmentType = 1 assignmentValue = 0 assignmentNumber = 0 assignmentPoints = 0 while (totalPercent < 100): percent = int(input("Put in the percent value of assignments of type " + str(assignmentType) + ": ")) assignmentType += 1 totalPercent+=percent ...
012588622b4eb7bfba1cde1f599dd65aaae0f6f0
Chig00/Python
/GunTag.py
9,555
3.71875
4
#!/usr/bin/env python3 """Gun Tag by E1Z0 Gun Tag is like the game tag, but the chasing player uses bullets to tag the runner player. The runner player will get a point for every half second they stay running. Then winner is the player who gets 100 points first. A tag will cause the players to switch roles, which ...
d60f52eeeaefec8702658da27de675bf0da89246
nguyenhvili/inteview-exam
/advanced_calculator/solution/app.py
1,001
4.0625
4
def eval(expression): result = 0 while len(expression) != 0: isPositive = True if expression[0] == " ": expression = expression[1: len(expression)] if expression[0] == "+": expression = expression[2: len(expression)] elif expression[0] == "-": ...
b26e3b1641f936bf81203ed657cfb5a55f92d197
tectonicpie/RobotBartender
/drink.py
2,340
4.375
4
class Drink: """A mixed drink with a list of ingredients and amounts""" def __init__(self, name, ings): """Return a new instance of Drink. Keyword arguments: name -- string, the name of the drink ings -- dictionary of Ingredients (keys) and no. of parts (value) "...
34cd82e0fad93a0f279bd2c8fcb91f36b82fe600
lozo26/box-man
/app/sort-group-rank.py
2,225
4.0625
4
from itertools import groupby from operator import itemgetter, setitem import pprint def denseRanking(groups, setRank): """ '1223' ranking for four items A, B, C, D. If A ranks ahead of B and C (which compare equal) which are both ranked ahead of D, then A gets ranking number 1 ("first"), B gets ra...
014c4caabb482dfb1c86726a3f9560d1fcd9020f
NJTuley/Blackout
/Executable Files/ScoreItem.py
1,337
3.796875
4
# class that formats high score output (this object formats a single high score, and this object will be placed in a table-like format in the HighScoreDisplay class import Colors import Fonts import pygame class ScoreItem(): def __init__(self, index, score, x, y, width, height): self.score = score ...
7a8a92ea59f9d801b637455e2f8aac55d31dfc54
dawidsielski/Python-learning
/other/django girls python exercises/solutions/sum_elements.py
979
4
4
""" Your task is to sum all the elements that are divisible by 7 from the specific range Function takes starting point argument and ending point argument. Function returns sum satisfying """ def sum_elements(starting_point, ending_point): # Put your code here sum = 0 for number in range(starting_point, end...
33cddf7bc312d7dc90649b85a01b47ebbfcd5b2b
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4161/codes/1724_2521.py
196
3.640625
4
from math import* n = int(input("serie: ")) pi = 0 t = 0 while t<n+1: s = 1 r = 0 while r<=t: s = s*((2*r)+1) r = r + 1 pi = pi + factorial(t)/s t = t + 1 pi = pi*2 print(round(pi, 10))
058d0fdd64bf6c7d8863687f7c0e318f8bbbf496
GReichman/EzNmap
/EzNmap/gui.py
4,167
3.578125
4
#!/bin/env python from tkinter import * from subprocess import PIPE, Popen, check_output import sys frame = Tk() frame.geometry("1400x800") frame.title("EzNmap") scanType = IntVar() fileType = IntVar() verbosity = IntVar() ipLabel = Label( text="Please enter the IP(s) you wish to scan \n • Input can be single I...
55624375e0391d35ac29d83a0f5612c4602fbbaa
MDaalder/Med_Imaging_Analysis_MDSC-689.03
/W01_load_display_3Dmed_Image/01_Solutions/readNifti.py
1,958
3.6875
4
import vtk #This is a basic program to read a Nifti image and display the slice indicated by the user #1) Define a Nifti reader NiftiReader = vtk.vtkNIFTIImageReader() #This is a way to get input from the command line NiftiPath = input("Please, indicate the path to the Nifti file: ") #Note this little differen...
53400e21e13f5b491efbecece2cfed229e318753
AP-MI-2021/lab-4-deliasusca
/main.py
6,250
3.75
4
def read_list1(): """ Citire prima lista :return: lista de numere intregi """ n=int(input("Introduceti nr de elemente pentru prima lista: ")) lst1=[] for i in range(n): x=int(input("a[{}]= ".format(i+1))) lst1.append(x) return lst1 def read_list2(): """ Citire a ...
93bd86edb20c5884693c92a1bb2f71131b32525b
AsisRai/210CT---Programming-Algorithms-and-Data-Structures
/Week-1/Week 1,Q2 (Trailing 0's).py
845
4.125
4
"""Function to return the factorial of a number using recursion""" userin = input('Please input a number: ') #takes the imput from the user inconv = int(userin) #converts the string input to integer def trailing0s(n): #Hint: Count the prime factors of 5 #http://code.activestate.com/recipes/577844-calculate-trail...
1cd9b8a127f3b2e5b7d1452171e971120fa1d346
mmmaaaggg/RefUtils
/src/fh_tools/language_test/base_test/threading_test/productor_consumer2.py
2,355
3.546875
4
# -*- coding: utf-8 -*- """ Created on 2017/7/14 @author: MG """ import threading import time from queue import Queue product_queue = Queue() condition = threading.Condition() products = 0 class Producer(threading.Thread): '''生产者''' ix = [0] # 生产者实例个数 # 闭包,必须是数组,不能直接 ix = 0 def _...
18d1f823900bda449471d604d6928c129d4f1bb7
JacobDominski/SearchAndSortAlgorithms
/LinkedList.py
2,826
4.0625
4
class LinkedList: def __init__(self): self.head = None def printList(self): temp = self.head while temp: print(temp.data) temp = temp.next def push(self, data): newNode = Node(data) if self.head is None: self.head = newNode return last = self.head whil...
c6d5a3c54ecb0e1002cab58db59440dbab0a62de
SimonSlominski/Codewars
/7_kyu/7_kyu_First-Class Function Factory.py
647
4.28125
4
""" All tasks come from www.codewars.com """ """ TASK: First-Class Function Factory DESCRIPTION: Write a function, factory, that takes a number as its parameter and returns another function. The returned function should take an array of numbers as its parameter, and return an array of those numbers multiplied by th...
22d17d9d3f09268398cfceedc5a20f8e184057fb
503Hicks/code_guild
/8ball.py
1,432
4.15625
4
# Print a welcome screen to the user. # Use the random module's random.choice() to choose a prediction. # Prompt the user to ask the 8-ball a question "will I win the lottery tomorrow?" # Display the result of the 8-ball. # Below are some example 'predictions': # It is certain # It is decidedly so # Without a doubt #...
ae606bc67142f5f9b1a0a71ab1a6db024f8a6bee
sds1vrk/Algo_Study
/Inflearn_algo/section1_basic/section1.py
1,108
3.875
4
# sep옵션은 띄어쓰기(공백)말고 다른 문자를 넣을수 있도록 함 # end는 다음 print문을 붙여서 사용할때 사용 print("test","hello","hi") print("test","hello","hi",sep="") print("test","hello","hi",sep="-") print("testEnd",end="") print("kkk") # 문자열과 내장함수 # upper,lower는 return 값 존재, 원본은 있음 msg="It is Time" print(msg.upper()) print(msg.lower()) print(msg) # 문자...
bc4d2b56b063197d9c4e1b61a7d604a977f6a4d4
sainad2222/my_cp_codes
/codeforces/233/A.py
117
3.53125
4
n = int(input()) if(n&1): print(-1) else: for i in range(n//2): print(2*(i+1),2*(i+1)-1,end=" ")
ba5a8aac44ab89992ae69f1e6b3424b8011c25bd
tacores/algo-box-py
/other/puzzle_5x5.py
7,425
3.984375
4
# python3 import itertools """ 5×5の正方形パネルを並べるパズルを解く。 (top, left, bottom, right) の形で25枚の四角形が与えられる。 詳細は、puzzle_5x5.xlsx 参照。 特にこれといったアルゴリズムやテクニックは使っていない。 外枠が黒色であることを利用して、まず四隅のパネルを確定し、 四辺の組み合わせを総当たりに近い形で調べている。 """ class Square: def __init__(self, top, left, bottom, right): self.top = top self.left =...
f43adbcb05a526fbcfffaa865132e425a71c6787
Pity-The-Fool/Adv_Alg_2
/Homework_1/find_prime.py
1,084
3.6875
4
from random import randrange, getrandbits def generate_prime_candidate(length): # generate random bits p = getrandbits(length) # apply a mask to set MSB and LSB to 1 p |= (1 << length - 1) | 1 return p def generate_prime_number(length=512): p = 4 # keep generating while the primality test ...
ede7c1e32becf8b3411ee8dccceedd31e754393c
kgyk1993/ABC
/038/b.py
222
3.640625
4
h1, w1 = map(int, raw_input().split()) h2, w2 = map(int, raw_input().split()) if h1 == h2: print "YES" elif h1 == w2: print "YES" elif h2 == w1: print "YES" elif w1 == w2: print "YES" else: print "NO"
fd272649112b6e30775b3a5ffe4b55e2ec6b079a
sourabh07patwari/InsightChallenge
/src/h1b_counting.py
6,119
3.84375
4
import csv import sys # This method will return the total number of certified professionals in the csv file and also store the dictionary # where dict_states stores number of certified professionals with respect to different states # and where dic_occupation stores number of certified professionals with respect to di...
a7ca3d31f2c3a551af7796236711307f2c3ddce2
charlesepps79/ch_3
/guest_list.py
678
4.40625
4
# 3-4. Guest List: If you could invite anyone, living or deceased, to # dinner, who would you invite? Make a list that includes at least # three people you'd like to invite to dinner. Then use your list to # print a message to each person inviting them to dinner. guests = ['Ted Bundy', 'Pedro Lopez', 'H.H. Holmes']...
c55f146450480b393d13581e44b3372c39a61532
colbydarrah/cis_202_book_examples
/CH7.23_graph_tick_labels.py
1,280
4.0625
4
# Colby Darrah # 3/23/2021 # 7-23. line graph pg 412 # Program uses Tick-Mark Labels on X-axis to display years and # on Y-axis to display sales in millions of dollars. # create alias for matplotlib.pyplot import matplotlib.pyplot as plt def main(): # Create lists with the X and Y coordinates of each da...
ff2e7c046f63987970c6aae0f6be317a12668597
KingTom1/StudyBySelf
/01学习/基础_DataFrame.py
4,084
3.609375
4
###########################DataFrame 学习################################### # DataFrame 一个表格型的数据结构,它含有一组有序的列,每列可以是不同的值类型 # DataFrame中的数据是以一个或多个二位块存放的,不是列表、字典或别的一维数据结构 import pandas as pd import numpy as np #初始化方式1 df=pd.DataFrame({'A':[1,2,3,4],'B':[5,6,7,8],'w':[1,1,1,1],'s':[1,1,1,1]}) print(df) #初始化方式2 s1=np.array([1...
86c7f13f14c09b7ff7ecfd162ca3bbdbce079f9f
EdytaBalcerzak/python-for-all
/04_chapter/indeksowanie_sekwencji.py
439
3.703125
4
#program wybiera losowo pozycje w lancuchu #prezentuje dostep swobodny do elementu sekwencji import random slowo = "kwiat" print("wartosc zmiennej 'slowo',to", slowo) dodac = len(slowo) odjac = -len(slowo) for i in range(10): pozycja = random.randrange(odjac, dodac) print("slowo [", pozycja,"]\t", slowo[pozycj...
a154c4d53be916f4876447245e004b5738532341
Samuel0413/JavaScipt_Exercise
/functions.py
264
3.765625
4
import sys def hail_friend(name="friend"): print("Hail, " + name + "!") def hail_input_name(): name = input("Please enter the name: ") print("Hail, " + name + "!") def add_numbers(num1, num2): return num1+num2 #hail_friend() #hail_input_name()
be72418f8617c1143143a9d1b8868364da62b076
ajn123/Python_Tutorial
/Python Version 2/Basics/Contains.py
839
4.125
4
def main(): a = [1,2,3,4,5] dict = {"bob":32,"aj":22,"joe":100} """ The "in" keyword is an operator you can use on a set to see in that element exists in the set. This is useful if you want to check if a certain element is in a set and dont want to loop through it and check with a while loop. """ prin...
453348227bba3e1ca7395993968e6b3591bdce71
hjlarry/practise-py
/standard_library/DataStructures/collections_ex/counter.py
944
3.6875
4
import collections print("一、 Counter构建") print(collections.Counter(["a", "b", "c", "a"])) print(collections.Counter(a=2, b=3)) print(collections.Counter({"a": 2, "b": 4})) print() c = collections.Counter() print("init:", c) c.update("abbad") print("seq:", c) c.update({"a": 1}) print("dict:", c) print() print("二、 Cou...
65c29b69bb85bea5a38a2920ac4f50c87d2eebf8
rafaamary/ExercicioPythonEstruturasDeSelecao
/EX7.py
963
4.21875
4
''' Faça um programa que dados três valores X, Y e Z, verifica se eles podem ser os comprimentos dos lados de um triângulo e, se forem, verificar se é um triângulo equilátero, isósceles ou escaleno. Caso eles não formem um triângulo, escreva uma mensagem. • Para verificar se as três medidas formam um triângulo, cada ...
17aa405cfc5507f9c23cb2f787f8ed12d6e7237d
nikolaj74-hub/lessons
/zada5.py
662
3.859375
4
# Создать (программно) текстовый файл, записать в него программно набор чисел, # разделенных пробелами. Программа должна подсчитывать сумму чисел в файле и выводить # ее на экран. f = open('zadacha5.txt', 'w', encoding='utf-8') s = input('введите чиcла через пробел:') j = [] f.write(s) f = open('zadacha5.txt', '...
e7758b5cbd353a7997862480609fead502c9e761
monda00/AtCoder
/Contest/ABC005/C.py
789
3.53125
4
def exist_takoyaki(customer_time, takoyaki_time): return takoyaki_time != -1 and takoyaki_time + allowable_time >= customer_time \ and customer_time >= takoyaki_time allowable_time = int(input()) takoyaki_num = int(input()) takoyaki_time_li = list(map(int, input().split())) customer_num = int(input()) cust...