blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
641003405cc28936693ac4ba623522af5d129e12
Putitamos28/CP3-Putita-Mosikarat
/Lec104_Putita_M.py
514
3.921875
4
class Customer: name = "" lastname = "" age = 0 def addCart(self): print("Added to ",self.name, self.lastname,"'s cart", ) customer1 = Customer() customer1.name = "Putita" customer1.lastname = "Mosikarat" customer1.age = 21 customer1.addCart() customer2 = Customer() customer2.name = "Dhi" cus...
d37bcd293b12c25641657cac90ce3b8605bd0723
himanshu2922t/FSDP_2019
/DAY-03/frequency.py
313
4.03125
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 6 09:06:01 2019 @author: Himanshu Rathore """ input_string = input("Enter a string: ") frequency_dict = {} for char in input_string: if char not in frequency_dict: frequency_dict[ char ] = 1 else: frequency_dict[ char ] += 1 print(frequency_di...
5204f30b0a8fcb2b3dc0da74f6e4190f07c85a9b
norlyakov/algorithms_battlefield
/arrays/move_zeroes.py
807
4.1875
4
""" Move Zeroes Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0] Note: You must do this in-place without making a copy of the array. Minimize the total number of operations. """ fro...
e713bb2ecafa1003d56c8c9879be65e4e4ac6e53
wenty2015/AdventOfCode
/day1_2.py
277
3.65625
4
file = open('day1_1.txt','r') str = file.read() i = 0 stairs = 0 length = len(str) while stairs >= 0 and i < length : if str[i] == '(': stairs += 1 else: stairs -= 1 i += 1 if i = length : print('never enter the basement') else: print(i)
16c9a095030cb2e7e4908360574a683b780d9289
KritoCC/Sword
/ex12.py
2,055
4.125
4
# 习题十二 # 前一题用 print() 打印问题,用input() 回答问题有点麻烦不是么? # input() 就是要用户输入内容的,何不把提示功能加进去省去写 print() 语句的麻烦。 age = input("How old are you? ") height = input("How tall are you? ") weight = input("How much do you weight? ") print("So, you're %s old, %s tall and %s heavy." % (age, height, weight)) # pydoc-文档生成工具 # 用途: # 是python自...
4ccae8bb1303c8c7c019a1f69f06665178984509
BerkeleyPlatte/competitiveCode
/generate_hashtag.py
759
3.953125
4
# The marketing team is spending way too much time typing in hashtags. # Let's help them with our own Hashtag Generator! # Here's the deal: # It must start with a hashtag (#). # All words must have their first letter capitalized. # If the final result is longer than 140 chars it must return false. # If the input or t...
b83bbd529e3269a7292acf2e67f1461935f008d9
Ahmed--Mohsen/leetcode
/binary_tree_paths.py
991
4.0625
4
""" Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / \ 2 3 \ 5 All root-to-leaf paths are: ["1->2->5", "1->3"] """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right =...
02de6055c0789a8cf1f0a9dcba500b7936578c24
enriquedcs/Algorithm
/Algorithm/Largest_sum_array.py
407
3.75
4
#Question 6 # Largest sum subarray # Algorith to find the sum of contiguos subarray def kadane_algorith(nums): max_global = nums[0] max_current = nums[0] for i in range (1,len(nums)): max_current = max(nums[i], max_current+nums[i]) if max_current > max_global: max_global = ma...
b682b259f73afe186bb338a85772f3d56df90c69
SemajDraw/leetcode_solutions
/tree/searching.py
4,547
4.03125
4
from typing import List class Node: def __init__(self, val): self.val = val self.left = None self.right = None class Tree: def __init__(self): self.head = None def buildTree(self, nodesVals: List[int]): if len(nodesVals) <= 0: return 'Enter a non em...
5c72abe94262c36e64ee9235c3a8e88d09a0cb65
Anupya/leetcode
/hard/q239 slidingWindowMax.py
839
3.578125
4
# You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. # Return the max sliding window. import bisect class Solution: ...
74c955e7e46fdfd87da388a1d770e0ffeec91304
colaso96/Hockey_Puck_Shooting_Robot_Capstone
/StepperMotor.py
1,598
3.65625
4
import random import math import time import numpy as np import RPi.GPIO as GPIO class StepperMotor: # Initializes a stepper motor given # int: direction - GPIO pin to control direction # int: step - GPIO pin to control the step def __init__(self, direction, step, delay): self.DI...
585b45e7a3ebe88843369bb913c274ba73e79ff0
jgerrish/nltk_ext
/pipelines/uniq.py
402
3.78125
4
# Module to return uniq elements given a list of elements # Stores every item seen in the stream, for large collections, # use the RedisUniq Redis-backed uniq module import itertools class Uniq(object): def __init__(self): self.items = set() def process(self, data): for s in data: ...
67150f37caa5d90147f3d722a6b9234b456e0ca7
JohnnyBarber/Computational-Finance
/project 1 Jiaqi Li/project_1_Jiaqi_Li.py
7,236
3.8125
4
# -*- coding: utf-8 -*- """ Created on Sat Jan 12 15:56:02 2019 @author: Jiaqi Li """ import numpy as np import matplotlib.pyplot as plt import math import random import time #1-------------------------------- #Set random number generators a = 7**5 b = 0 m = 2**31-1 #Creat a list to store random numbers with U[0,1...
cbd928cae24bbd74b46ba80f7f1bb564e9285c2c
hogitayden/nguyenhoanggiang-fundametal-c4e22
/Session1/homework/c2f_hws1.py
113
3.65625
4
C = input ("Enter the temperature in Celsius? ") F = 33.8 * float(C) F = round(F,2) print (C, "(C) = ", F, "(F)")
488b640c5492c2a98920b06bcaa2ce29d4bd17e8
jedzej/tietopythontraining-basic
/students/bec_lukasz/lesson_01_basics/previous_and_next.py
215
4.15625
4
# Read an integer: # a = int(input()) # Print a value: # print(a) a = int(input()) print('The next number for the number '+str(a)+' is '+str(a+1)) print('The previous number for the number '+str(a)+' is '+str(a-1))
19df2585aed584e260918eaf8fb3d3871d87b611
hackernogg/CS_ELTE_BC
/Python/1.BasicHelloW/main.py
129
3.90625
4
print("This line will be printed.") x = 1 if x == 1: print ("x is 1.") #----------------------------- print("hello, World!")
8e19f364bd8a3ba8361e329644bfd696088a3a54
karimitani/ECE364
/Prelab08/listmod.py
291
3.71875
4
import os import sys import math def find_median(l1,l2): median = 0 result=[] result=l1+l2 result = sorted(result) if len(result) % 2 == 0: median = math.floor((len(result) - 1)/2) else: median = (len(result) - 1)/2 return (result[median],result)
ce5c41bbab5769e487ed52103cf58f47ac26874d
PawarKishori/QSE
/chi_par.py
616
3.96875
4
import sqlite3 conn = sqlite3.connect('Treebank_English.db') def word1(conn): cursor = conn.cursor() x = input("enter the first word\n") y = input("enter the secone word\n") y="'"+y+"'" x = "'"+x+"'" cursor.execute('select t.sid,t.sentence from Tsentence t,Tword w,Tword k WHERE w.word='+x+' AND...
20aedf6083c255849137f71b5a707b1c9c85a6fd
yourapi/biz.data.processing
/types/nl/phone/_normalize.py
186
3.921875
4
import re def normalize(value): "Return a valid phonenumber with general separators removed. Keep letters to prevent false positives." return re.sub('[^0-9\+a-zA-Z]', '', value)
778aaa85c122c54c15f88e59d1c516d25c499448
ggsant/pyladies
/iniciante/Mundo 03/Exercícios Corrigidos/Exercício 092.py
929
3.75
4
""" EXERCÍCIO 092: Cadastro de Trabalhador em Python Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-os (com idade) em um dicionário. Se por acaso a CTPS for diferente de ZERO, o dicionário receberá também o ano de contratação e o salário. Calcule e acrescente, além da idade, com qu...
3c721c4f70657bf62919fbd1b7523e1354623391
Qiao-Liang/LeetCode
/LC50.py
1,269
3.5
4
class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ # if n == 0: # return 1 # else: # temp = self.myPow(x, n // 2) # if n % 2 == 0: # return temp * te...
77d202ed61efd04426966ce5375aaf0619a39cf6
aleksandrakoziel/AI01
/data.py
686
3.5
4
def read_data_from_file(file): # file structure to load # quadratic matrix size # empty line # first matrix A # empty line # second matrix B with open(file, mode='r', encoding='utf-8') as data: size = int(data.readline()) #matrix size - amount of localizations data.readli...
b68dbd3a129ed60b25038a658b4017c4957f1197
abdirashidabdi/LOGIN-SYSTEM-PRO
/tempCodeRunnerFile.py
2,136
4.28125
4
def navigate_user(): while True: user_input = input( "\nWelcome to our login system \nType login or register: ") if user_input == "register": return register_user() elif user_input == "login": return login_user() elif user_input == "": ...
ff95c49c7d95ff19f9e30ed7761d16dbaa03d957
daphnecarwin/AllProjectsGWC
/DictionaryAttack/dictionaryattack.py
1,264
4.25
4
#Opens a file. You can now look at each line in the file individually with a statement like "for line in f: f = open("dictionary.txt","r") print("Can your password survive a dictionary attack?") #Take input from the keyboard, storing in the variable test_password #NOTE - You will have to use .strip() to strip whitesp...
b2deb4f80e340b0cca3431717f67b056b502102a
JoshuaUrrutia/agave-cli
/bin/libs/python/richtext.py
1,215
3.53125
4
#!/usr/bin/env python # richtext.py # # A Python >=2.7 command line utility for converting json responses into a rich format # import sys debug = False def print_table(table): zip_table = zip(*table) widths = [max(len(value) for value in row) for row in zip_table] for row in table: result = "| ...
ee76231252ac3f15432c83daec73d45ea74e5346
joaquimrsn/Exercios-python
/Estruturas de repetição/Nome_Senha.py
230
4.125
4
while True: nome = input("Digite seu nome de usuário!") senha = input("Sigite a senha!") if (senha == nome): print("Sua senha não pode ser igual ao nome de usuário, tente novamente!") else: break
a2ce2576306d9e70b77836e5ef890a994fb3a21d
raldenprog/python_tricks
/patterns/command.py
4,397
3.890625
4
""" https://refactoring.guru/ru/design-patterns/command Команда — это поведенческий паттерн проектирования, который превращает запросы в объекты, позволяя передавать их как аргументы при вызове методов, ставить запросы в очередь, логировать их, а также поддерживать отмену операций. """ from __future__ import annotation...
2a4aa06f3cc2943d0be64137af2970798a4e93bf
TrellixVulnTeam/Demo_933I
/leetcode/693.Binary Number with Alternating Bits.py
1,428
3.78125
4
# Given a positive integer, check whether it has alternating bits: namely, if tw # o adjacent bits will always have different values. # # Example 1: # # Input: 5 # Output: True # Explanation: # The binary representation of 5 is: 101 # # # # Example 2: # # Input: 7 # Output: False # Explanation: # The bin...
c755411c24e86800ba02c06094c12ffeb43d6f7e
huangqiank/Algorithm
/leetcode/binarySearch/first_bad_version.py
1,055
4.03125
4
##You are a product manager and currently leading a team to develop a new product. ##Unfortunately, the latest version of your product fails the quality check. ##Since each version is developed based on the previous version, ##all the versions after a bad version are also bad. ##Suppose you have n versions [1, 2, ..., ...
e1b9954b4820bb8969a6898d5bd01f226df1ee87
Gambrinius/Python_Course
/week5/lost_card.py
122
3.875
4
n = int(input()) sum_ = sum(range(n+1)) for i in range(1, n): cur_num = int(input()) sum_ -= cur_num print(sum_)
9e1b7a7e24a19561f305f5b2a7812f78d0b79f78
rexfa/helloPython
/InterestPrepayment.py
612
3.703125
4
#计算预付利息的实际年利率,名义本金,实际利息 def interestPrepayment(namedPrincipal ,interest): print('名义利率',interest/namedPrincipal) monthlyRepayment = namedPrincipal/12 actualLoan = namedPrincipal - interest print('实际年利率',monthlyInterest(monthlyRepayment,actualLoan)) #每月利率,每月还款,名义本金 ,实际利息 def monthlyInterest(monthlyRepay...
5a108cb7fb1ff0426c5e21786f4e9bdf90d8a1e2
gdh756462786/Leetcode_by_python
/ArraySum/submatrix-sum.py
1,126
3.515625
4
# coding: utf-8 ''' 给定一个整数矩阵,请找出一个子矩阵, 使得其数字之和等于0.输出答案时,请返回左上数字和右下数字的坐标。 样例 给定矩阵 [ [1 ,5 ,7], [3 ,7 ,-8], [4 ,-8 ,9], ] 返回 [(1,1), (2,2)] ''' class Solution: # @param {int[][]} matrix an integer matrix # @return {int[][]} the coordinate of the left-up and right-down number def submatrixSum(self, matri...
b40fe1e242f9ff36305af5c2b29f0ac85e6227a5
szama7/python_practice
/alarms/ToplistOfUnits.py
377
3.53125
4
import ListSorting from collections import Counter ListSorting.store_blocks() ListSorting.sort_list() computer_units = [] for i in range(0, len(ListSorting.threestar)): computer_units.append(ListSorting.threestar[i][0].split()[2]) for i in range(0, len(ListSorting.twostar)): computer_units.append(ListSorting...
eeb81a43267112b37d8d1f6cd0874af04767233a
Patacij/Calculator
/list_dict.py
1,520
3.796875
4
print ("Welcome to my TODO program.") to_do_tasks = [] done_task = [] tasks = [] while True: action = raw_input('Select add new task or edit existing tasks (new/edit)') if action == 'new': task_name = raw_input("Please enter new task: ") task = { 'task_name': task_name, ...
e12b130c2cb9738aa69b5cb351be36bcb933d381
ArsenalGang/dzdykes.github.io
/Solutions/gcd.py
567
3.53125
4
def GCD(x,y): if x > y: return False if x%y == 0: return y else: result = 1 for i in range(int(y/2)): if x%(i+1) == 0 and y%(i+1) ==0: result = i+1 return result def LCM(x,y): if x > y: return False if x%y == 0: retu...
ff0e4b5120733be9cb2f28329f7eb806e3009e19
rajlath/rkl_codes
/LeetCodeContests/56/string_compression.py
1,954
4.0625
4
''' 443. String Compression My SubmissionsBack to Contest Difficulty: Easy Given an array of characters, compress it in-place. The length after compression must always be smaller than or equal to the original array. Every element of the array should be a character (not int) of length 1. After you are done modifying th...
1576a986be9b3792fd0f19913b672833b285a4e5
sibarras/games
/snake_game.py
6,141
3.890625
4
from random import randint from time import sleep import keyboard # deseo eliminar esta libreria en un futuro from raspberrypi import RPiSimulator class Snake: def __init__(self, limits=tuple): self.xf, self.yf = limits self.mouth = randint(0, self.xf), randint(0, self.yf) self.body = [sel...
bea4f2b02bc58f97b3823942d0f5f4132a41bfbe
Anirban2404/LeetCodePractice
/110_isBalanced.py
2,803
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 31 09:49:05 2019 @author: anirban-mac """ """ 110. Balanced Binary Tree Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the depth of the two subtrees o...
5ddde85b31c38653430c512bc2074610cd96c82c
SergeiMerson/Experis
/!Projects/MP_Library/registers.py
2,353
3.796875
4
import basics class Register: def __init__(self): self.register = {} def get_items(self): return (val for _, val in self.register.items()) def get_by_key(self, key): try: return self.register[key] except KeyError: print('There is no s...
8b7d6a2d1d9e4f049abcbe950c1306f742e0a3fc
yaolizheng/leetcode
/73/set_zero.py
603
3.546875
4
def set_zero(m): r = len(m) c = len(m[0]) for i in range(r): for j in range(c): if m[i][j] == 0: m[0][j] = 's' m[i][0] = 's' for i in range(r): if m[i][0] == 's': for j in range(c): if m[i][j] != 's': ...
8847a9eeb9cf40e07948726b816b310d877c3116
rafaelperazzo/programacao-web
/moodledata/vpl_data/83/usersdata/235/44011/submittedfiles/dec2bin.py
145
3.90625
4
# -*- coding: utf-8 -*- n=int(input('digite o numero:')) i=0 s=0 while n>0: M=n%2 F=(M*(10**i)) s=s+F n=n//2 i=i+1 print(s)
76cd561c5177147f91c284b3f4b106164b3b75b3
xbtlin/Learn-Python-the-Hard-Way-
/exercises/ex13-raw_input.py
189
3.59375
4
from sys import argv script, first_name, last_name = argv middle_name = raw_input("What is your middle name? ") print "Your full name is %s %s %s." % (first_name, middle_name, last_name)
31e88cbc8c7b925c7befc990eebe2eeec75197af
AllenLiuX/Application-of-Python-UCLA-PIC16
/hw/hw4.py
3,341
3.625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ @author: Wenxuan Liu 805152602 """ import re """Use regex to seperately match the syntax of int, float, and list, and return the type if matched, otherwise return string.""" def mytype(v): """It performs the same action as type(), and can recognize integers, ...
6ceef081d9ddb33fe2a8ad60e48fd9af978c4f4a
raghavp96/autoneo
/autoneo/exporter.py
1,413
3.5625
4
import sqlite3 import csv def handle_sqlite3(db_path, query_file_path, csv_file_path): """ Handle the data export from a SQLite 3 DB to CSV """ connection = sqlite3.connect(db_path) cursor = connection.cursor() query_string = __query_file_to_string(query_file_path) with open(csv_file_path...
572531f6f1723b2c2ed19808dfc7968a8c3ad042
Eli-jah/a-byte-of-python
/io_using_file.py
612
3.71875
4
# encoding=utf-8 poem = '''\ Programming is fun When the work is done If you wanna make your work also fun Use Python! ''' # Open file for 'w'riting f = open('poem.txt', 'w') # Write text into file f.write(poem) # Close the file f.close() # If no mode is specified # The 'r'ead mode is assumed by default f = ope...
5055468924fa40be02902451f8716c95c3eca4ae
dilynfullerton/tr-A_dependence_plots
/src/LegendSize.py
2,909
3.5
4
"""LegendSize.py Class definition for LegendSize, which specifies how a legend should be sized for matplotlib plots """ from __future__ import division from math import ceil class LegendSize: """A class to store the constants and methods for generating a nice legend outside the subplot area (matplotlib) "...
89e81ef50ea85213441253f1f47bc6df343a8bf6
AzharMithani/Handwritten-Digit-Recognition-With-Deep-Learning
/train.py
1,234
3.71875
4
#importing required modules from sklearn.externals import joblib from sklearn import datasets import numpy as np #for creating Neural Network I am using MLPClassifier from sklearn from sklearn.neural_network.multilayer_perceptron import MLPClassifier #getting MNIST of size 70k images dataset = datasets.fetch_mldat...
f3307c60d80b06b0d0e1c5bea6c9c8ab2c43e7a7
ChaosJohn/c9.io-playground
/py2/default_argument_values.py
810
3.71875
4
"""Default Argument Values.""" def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): """Ask Prompt""" while True: answer = raw_input(prompt) if answer in ('y', 'ye', 'yes'): return True if answer in ('n', 'no', 'nop', 'nope'): return False retries...
5c45181788c5e511b8a545ce89d0b3b46ad875d3
bhanu-python/Python-Data
/milestone_project1/test.py
109
3.828125
4
s="hello" pos=1 mylist=["My","Name","is"] print(mylist) mylist[pos]=s #mylist.insert(pos,s) print(mylist)
2ae076df49d9aeb8f2c2f35ccf3e9596465b7c0f
TingliangZhang/VR_Robot
/Python/Practice/ch01/1.py
109
3.734375
4
import random for x in range(10): print("hello\n") print("hhh ",random.choice(range(10))) input() #233
c044f2ee7e8c5f9ca76c57f065bf049fe29d1b28
ddc899/cmpt145
/Code Examples/Chapter 01/coupon-collector.py
1,455
4.15625
4
""" CMPT 145 Computing with Python Lists The Coupon Collector Problem Suppose there are n coupons to collect, and coupons are obtained randomly (with equal probability), with repeats allowed (replacement). How many coupons need to be obtained before all coupons have been seen at least once? (Not answered: how many o...
462f37a1890707acc8e223b8b1f30ba949c47e5d
noshaikh/Graphs
/projects/graph/src/graph.py
6,390
3.90625
4
""" Simple graph implementation compatible with BokehGraph class. """ import random class Queue: def __init__(self): self.queue = [] def enqueue(self, value): self.queue.append(value) def dequeue(self): if (self.size()) > 0: return self.queue.pop(0) else: ...
b7bbd087f56eb93a4012cee0a3151065ffbd89e4
LwandoG/LifeChoicesOnline
/main.py
6,418
4.28125
4
import getpass import user import datetime # This is the local sign in function. It is used to print the appropriate message based on the result of the sign in # function from the user module. def sign_in(user_name): if user.sign_in(user_name): print("Signed in successfully. Enjoy your day.") else: ...
9b936388a54c9b309d4a24b05cf0aa91e1134a55
Alibi14/thinkpython-solutions
/12.1.py
397
3.765625
4
def make_histogram(s): hist = {} for x in s: hist[x] = hist.get(x, 0) + 1 return hist def most_frequent(s): d = make_histogram(s) t = [] for x, freq in d.items(): t.append((freq, x)) t.sort(reverse=True) res = [] for freq, x in t: ...
25981a052a1533bf8c9c5a79ad81239d4b32e997
nicob825/Bruno_Nico
/Lesson_04/4.2/average4.3.py
256
4.1875
4
num1=int(input("Enter the first number:")) num2=int(input("Enter the second number:")) num3=int(input("Enter the third number:")) def AVG(): return (num1+num2+num3)/3 def calcAVG(): print("The average of your numbers is",AVG()) AVG() calcAVG()
4b78eb3213cf2949a151a2696a56fd2f5b2fd8a6
craig-gundacker/salmon-run-sim
/Salmon.py
2,231
3.78125
4
import turtle import random from Coast import* class Salmon: def __init__(self): self.turtle = turtle.Turtle() self.turtle.speed(0) self.turtle.up() self.turtle.shape("fish.gif") self.turtle.turtlesize(.2, .2, .2) self.turtle.color("blue") self....
772bd61be5647005ebba9bbf379d4f656c406b31
GustafGroning/python_time_tracker
/main.py
1,894
3.640625
4
import time import datetime import stats as s import sys import json from datetime import date def start_up(): print("Hi! What would you like to do? \n") user_choice() def user_choice(): command = input("work on a task - type \"task\"\ncheck your stats - type \"stats\" \n \n ") if command == "task": ...
e4edd4801db285d1381245e7b20c953fa6272a26
ColeRichardson/CSC148
/labs/lab 04/tournament.py
1,924
4.125
4
class Tournament: """A sports tournament. === Attributes === teams: The names of the teams in this tournament. team_stats: The history of each team in this tournament. Each key is a team name, and each value stores the number of games played and the number won. === Sample u...
ef925095ade10b5f7d8350ed0a07777300eccc13
HioLeong/IrnBru
/IrnBru/extraction/wordoperations.py
887
3.53125
4
"""Word Operations""" """ Provides basic operations with texts such as tokenizing and splitting articles to arbitrary lengths, filtering and removing characters """ import nltk from nltk import word_tokenize from nltk import pos_tag from nltk import sent_tokenize from nltk.corpus import stopwords import re d...
d7de75ba4773cf4f33c846e471c37d85bc139a10
plantdink/code_in_place
/welcome_to_python/agreement_bot.py
536
4.5
4
""" Write a program which asks the user what their favorite animal is, and then always responds with "My favorite animal is also ___!" (the blank should be filled in with the user-inputted animal, of course). Here's a sample run of the program (user input is in bold italics): $ python agreement_bot.py What's your fav...
c5f1e62e454be97cfaf22b02b30f7a014caba188
anshi9061/Python
/dict.py
710
4.03125
4
#dictionary #1 mydict={"fruit":"apple","color":"red","seed":"yes"} print(mydict) #2 thisdict={"vegetable":"onion"} mydict.update(thisdict) print(mydict) #3 dict={"a":100,"b":200} x=input("enter the key:") if x in dict: print("key present") else: print("not present") #4 mydict.pop("fruit") ...
b8d4768c0283b48310377fd6a2d44e0cba580c45
ziyadalvi/PythonBook
/6The Dynamic Typing Interlude/2Types Live with Objects, Not Variables.py
600
4.4375
4
#Types Live with Objects, Not Variables a = 3 # It's an integer a = 'spam' # Now it's a string a = 1.23 # Now it's a floating point """Names have no types so we are not changing the type here, but we simply have made variable refer to another object. Objects, on the other hand, know what type they are—each object co...
faeb005db2d9a01aa234fef63673d7baf3ffbf7f
piotrbla/PyChessAnalizer
/board.py
918
3.890625
4
class Field: def __init__(self, r, c): self.r = r self.c = c self.letter = chr(c + ord('A') - 1) class Board: def __init__(self): self.fields = [] for r in range(1, 9): fields_row = [] for c in range(1, 9): fields_row.append(Field...
fecaddbbe09b818173b95ed6021cfcd1de0dfb74
amenson1983/Python_couses
/Chapter 3 (11).py
310
3.890625
4
book = int(input("How many books bought? :")) score = 0 if book<=0: score = 0 elif book>0 and book<2: score = 0 elif book>=2 and book<4: score = 5 elif book>=4 and book<6: score = 15 elif book>=6 and book<8: score = 30 elif book>=8: score = 60 print("Your score is: ", score, "points.")
d7abe765304e2baf83f46f6e6f75a3ce9dc2a4a2
intfloat/AlgoSolutions
/hackerrank/Practice/python/NestedList.py
448
3.609375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT from sys import stdin N = int(stdin.readline().strip()) students = [] for _ in xrange(N): name = stdin.readline().strip() score = float(stdin.readline().strip()) students.append((score, name)) score = sorted(list(set([e[0] for e in stud...
21007d05f012078a6b32149ef90e11319702953e
joncatanio/housing-classifier
/src/kc_model.py
2,136
3.953125
4
# Description: Kings County (Seattle area) linear regression model to predict # the price of a unit given a number of features. # # Model ID: 'KINGS_COUNTY' # Model Features: # 'bedrooms' - number of bedrooms # 'bathrooms' - number of bathrooms # 'sqft_living' - square footage of the living space # 's...
bcff14a0fc7e9a6fa5d3750e08b2ce7db4660179
benbendaisy/CommunicationCodes
/python_module/examples/340_Longest_Substring_with_At_Most_K_Distinct_Characters.py
1,188
3.640625
4
from collections import defaultdict class Solution: """ Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters. Example 1: Input: s = "eceba", k = 2 Output: 3 Explanation: The substring is "ec...
f2b3b9dc851d41a0aef5f6ad56e389b3f843b994
chenshu/sorting-algorithms
/insertion.py
644
3.921875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from random import randint def prepare(): cnt = 10 return [randint(0, cnt) for _ in range(cnt)] def swap(arr, i, j): arr[i], arr[j] = arr[j], arr[i] # compare avg O(N^2) best O(N) worst O(N^2) # swap avg O(N^2) best O(0) worst O(N^2) def insertion_sort(arr):...
92339a15cd35bc5e5e2b05f5a34f3a2b231b79cf
zhhiyuan/Cryptography
/Vigenere/1.py
3,481
3.9375
4
''' 实现维吉尼亚密码,用键盘接收明文和密钥,屏幕打印密文和解密后的明文 ''' def get_new_key(key,length): ''' 统一英文和密钥的长度 :param key: :param length: :return: ''' if len(key) == length: return key elif len(key) > length: #如果密钥过长,缩减密钥长度 return key[:length] else: #如果密钥过短,扩大密钥长度 round = int(le...
dd9a932f54249b50056801cdd3012354e9796015
nandoken/CIS-122
/labs/lab4.py
1,998
4.5625
5
__author__ = 'Fernando Ames' # This program asks the user to enter a positive natural number and find whether it is # an even or odd number after that it finds the factorial of that number # Input Variable: num # Output Variable: factorial, number # Module introduction() # Set num = input("Please enter a positive n...
18d26a9833507daa03d5cbc2d57f8b398b21da75
ZoranPandovski/al-go-rithms
/strings/string_search/all_substrings_occurances/python/all_substrings_occurances.py
4,737
3.828125
4
#!/bin/python3 import sys, string, re from random import * from timeit import default_timer as timer from collections import * def randstr(N,alphabet=string.ascii_lowercase): l=len(alphabet) return "".join( alphabet[randint(0,l-1)] for _ in range(N)) def timefunc(func, *args, **kwargs): """Time a function...
67dd07b7ffa31b09e4e7a667464da4a121741572
KulataevKanat/PythonData
/structures/oop/object/str.py
1,110
3.828125
4
class Car: def __init__(self, id, mark, color, model, dateOfManufacture) -> None: self.id = id self.mark = mark self.color = color self.model = model self.dateOfManufacture = dateOfManufacture def display_info(self): print(self.__str__) def __str__(self) ->...
eda80c624f36171e5b67419e16aad35beb683e16
AlesyaKovaleva/IT-Academy-tasks
/tasks_3/list_reverse_max_0_1.py
382
3.90625
4
""" Задача 0 Дан список А1..AN. Вывести элементы списка в обратном порядке. """ list_number = [1, 2, 3, 4, 5, 6] list_number.reverse() print(list_number) """ Задача 1 Исключить из списка А1..AN максимальный элемент. """ list_number.remove(max(list_number)) print(list_number)
f76260ff6ecddfef52ba3edc87235f7cacafeb21
heathersky/ising
/python_with_c/annealing.py
391
3.546875
4
def T_anneal(T, step, num_steps, num_burnin): #implement annealing code here T_a = T T_0 = T_a+1 m = -T_0/num_burnin T_step = m*step+T_0 return float(max(T_step,T_a)) def B_anneal(B, step, num_steps, num_burnin): #implement annealing code here B_a = B B_0 = B_a+1 s = -B_...
3928327ae11bb3b5f2397dec1d2d77ecfdce78ad
cmiddlet/FinalAssignment
/selectimage.py
1,544
3.59375
4
import requests import geojson def select_image(url, key, point, image_type, file_name): """Downloads an image matching the selected coordinates. Args: url (str): The source url of the image key (str): Authorisation key for the website point (lst): Decimal coordinates of the point for w...
63983b41e167860db1459d814ecfb4d31f3a9a8a
XiangyuDing/Beginning-Python
/Beginning/python3_cookbook/ch02/14-joins.py
1,057
3.9375
4
# 2.14 合并拼接字符串 parts = ['Is','Chicago','Not','Chicago?'] print(' '.join(parts)) print(','.join(parts)) print(''.join(parts)) a = 'Is Chicago' b = 'Not Chicago?' print(a + ' ' + b) print('{} {}'.format(a,b)) print(a + ' ' + b) a = 'Hello' 'World' print(a) data = ['ACME',50,91.1] print(','.join(str(d) for d in data)) #...
cf9fbffe54f26b940fddb7be0e9839f7be2f3168
chibiboss/Python-challanges
/Level_1/level1_ex3.py
512
3.96875
4
""" Define a class which has at least two methods: getString: to get a string from console input printString: to print the string in upper case. Hint Use __init__ method to construct some parameters """ class Palabra: def __init__(self, letras): self.letras = letras def getString(self): texto = input("int...
763d87e47131d4e6043f7122f85ec391bc55917d
AbhishekTiwari0812/python_codes
/Spiral.py
694
3.640625
4
def R(i): global Size if i==Size: return else: global row global column for p in range(i): print A[row][column], column+=1 def U(i): global row global column for p in range(i): print A[row][column], row-=1 def L(i): global row global column for p in range(i): print A[ro...
6c3798e4d88b8910cb8f4e166bf986281d384d30
gabriel-valenga/CursoEmVideoPython
/ex111.py
242
3.625
4
from utilidadesCeV import moeda valor = float(input('Digite um valor:')) aumento = float(input('Digite um valor para aumento:')) reducao = float(input('Digite um valor para redução:')) print(moeda.resumoValorMoeda(valor, aumento, reducao))
dd6fc46a8698e2f0a97904435be642f3850d0e2e
southpawgeek/perlweeklychallenge-club
/challenge-182/ealvar3z/python/ch-1.py
673
4.5625
5
#!/usr/bin/env python3 """ Created Thu Oct 13 07:47:17 PM EDT 2022 @author: E. Alvarez You are given a list of integers. Write a script to find the index of the first biggest number in the list. Example Input: @n = (5, 2, 9, 1, 7, 6) Output: 2 (as 3rd element in the list is the biggest number) Input: @n = (4, 2, 3...
ef658927b0d5cf2a4db44064a36d4c185eb07ff0
khanak077/Number-Guessing
/number guessing.py
1,488
4.03125
4
n = int(input("Enter no. from 1 to 10: ")) x = 8 for i in range(3): if (n != x): if (i == 1): print("The no. entered is wrong. Two chance left") n = int(input("Next chance: ")) elif (i == 2): print("The no. entered is wrong. One chance left") ...
b42ac0432125d8ce7d88f379355ce74b2bf9dd46
ornichola/learning-new
/pythontutor-ru/07_lists/06_maximal_element.py
558
3.875
4
""" http://pythontutor.ru/lessons/lists/problems/maximal_element/ Дан список чисел. Выведите значение наибольшего элемента в списке, а затем индекс этого элемента в списке. Если наибольших элементов несколько, выведите индекс первого из них. """ _l = input().split() l = [int(i) for i in _l] maximum = l[0] for i in ran...
92c926f6ef8bed7bf75ffef7867a390c70abffff
felicitia/HiPHarness
/data-processing/merge_alg.py
1,125
3.65625
4
from csv import writer from csv import reader import os input_dir = '/Users/yixue/Documents/Research/LessIsMore/R/实验' def add_column_in_csv(input_file, output_file, alg): # Open the input_file in read mode and output_file in write mode with open(input_file, 'r') as read_obj, \ open(output_file, 'a...
bcefd380bd94d436004b23ffe3faf674b8810c1b
cdbradley/py-numerical-programs
/7.Gambling_game/bradley_homework7.py
2,347
4.25
4
#Colt Bradley #2.2.16 #Homework 7 #import random import random as r #Interact with the user, explain what is going on. print "Welcome to the Casino! We've a special on the martingale" print "betting system, want to play? I see you have $20, buy in" print "is $2." ans = " " #Determine starting values fo...
5a699576ed252fa12169855c6f81a4a1a95f117d
AlejandroZapett/serieEjerciciosPython
/7_vocal.py
293
3.921875
4
import argparse def Vocal(letra): return letra+" es una vocal" if letra in ['a', 'e', 'i', 'o', 'u'] else "lo que ingresaste no es una vocal" parser = argparse.ArgumentParser() parser.add_argument("-l", "--letra", help="Ingresa una letra") args = parser.parse_args() print(Vocal(args.letra))
285c38f82620a0b431dcc5b19411a9ea9155f893
Shashi-Chaurasia/Python_array_practice
/append_item.py
706
3.8125
4
# from array import* # list = [2,4,6,8,3,5] # arr = array('i' , []) # arr.fromlist(list) # print(str(arr)) # from array import * # array_num = array('i', [1, 3, 5, 7, 9]) # print("Original array: "+str(array_num)) # print("Insert new value 4 before 3:") # array_num.pop(2) # print("New array: "+str(array_num)) de...
fb2d7edddceb9abbc0a2d4e9151b6ff215901cc6
daniel-reich/ubiquitous-fiesta
/YwXwxa6xmoonFRKQJ_3.py
423
3.5625
4
def josephus(n): people = [i for i in range(n)] index = 1 if n < 1: return False elif n == 1: return 0 else: while len(people) != 1: if people[index] == people[-1]: people.pop(index) index = 1 elif people[index] == people[-2]: people.pop(index) index = ...
5f60fa3d4c60aea15ec3095aac9d927a5f1de13a
bgoonz/UsefulResourceRepo2.0
/_Job-Search/InterviewPractice-master/InterviewPractice-master/Python/workSchedule.py
725
3.671875
4
def findSchedules(workHours, dayHours, pattern): # Write your code here current = [] remainingList = [] for i in pattern: for s in i: if s.isdigit(): current.append(int(s)) else: remainingList.append(s) remaining = len(remainingList)...
fea7e6e238f196d6c721654579cb55be269bdd79
Misterion777/NetworkProgramming
/MailClient/main.py
2,115
3.546875
4
from MailClient.mail import * import getpass GOOGLE_PORT = 587 YANDEX_PORT = 465 def print_help(): print("Available commands:") print("SEND 'msg' <recipient> - send message to recipient") print("SHOW <n> - show n last messages") print("HELP - get list of commands") print("EXIT - close connection a...
001e8c32ba8f889d49a332f02653c6cd2675a4e6
nikodemusk/PythonPrimeNumberTools
/primetools.py
3,560
3.9375
4
from math import sqrt def factorize(myNumber, checkPowers = True): # All the comments will be translated to English in the near future # Kommer att innehålla primfaktorerna till myNumber # Om powers = True, så innehåller den alla förekomster # av respektive enskild faktor (fullständig faktorisering). # Om...
055fa4e5ab25bc1b8acbc59c36415ba9bd50cb18
Mikhaelius/phyton
/calc.py
848
4.21875
4
#simple calc def operateCalc(): first = '' second = '' operator = "" while first == '': try: first = int(input("Enter first Number.")) except ValueError: first = '' while second == '': try: second = int(input("Enter first Number.")) except ValueError: second = '' ...
b1bae8421f1085f70bd33ad7e9098543c3ecf1eb
codenewac/python
/pythonbegin/learn_python/favorite_places6_9.py
372
3.53125
4
favorite_places={ 'newton':['beijing','paris','london'], 'bohr':['shanghai','berlin','newyork'], 'enstein':['Munich','Switzerland','beijing'] } for name,favorite_place in favorite_places.items(): print('\n'+name.title()+' love these cities:') for favorite_place_1 in favorite_place: print("\t...
2e07d2410daf177f45664f270591aef4323392fb
codic96/Array-Python-Code
/array1.py
248
4.0625
4
#Python 3 code to find sum #of elements in given array #driver function arr = [] #input values to list arr = [12,3,4,15] #sum() is an inbuilt function in Python #the value ans = sum(arr) #display sum print('Sum of the array is',ans)
fc5c91e8b0739c3a242d8691964aa05d6d19a885
JinSeonGyeong/202003_ai
/진선경/pre_python_05.py
227
3.8125
4
"""5. N을 입력 받은 뒤, 구구단 N단을 출력하는 프로그램을 작성하시오(format 활용)""" a = int(input("구구단의 아무단을 입력하세요.")) for i in range(1, 10): print(f"{a} X {i} = {a*i}")
04b0460162218b06670b4f6b4c14f1421cb6756b
Mariamjaludi/algorithms-practice
/python/frogJump.py
788
3.734375
4
def canCross(stones): for i in range(3, len(stones)): if stones[i] > stones[i - 1] * 2: return False lastStone = stones[-1] positions = [] # stack jumps = [] # stack stonePositions = {} for stone in stones: stonePositions[stone] = True positions.append(0) ju...
1fe4b7582110ad80152dd6d4c469e55918b96aff
Djamal1/PythonProg
/Python1/l06/days.py
1,293
3.765625
4
import random player1 = {"Счёт": 1000} player2 = {"Счёт": 1000} player1["Имя"] = input("Введите имя первого игрока: ") player2["Имя"] = input("Введите имя второго игрока: ") while True: player1["Ставка"] = int(input("Введите ставку: ")) player2["Ставка"] = int(input("Введите ставку: ")) player1["Брос...
6b2db50e9d673306c03859ce4d610ce51d8f4ef4
nicosalaz/pythonProject
/s11/pandas_some.py
554
3.796875
4
import numpy as np import pandas as pd # leemos el archivo de datos csv titanic = pd.read_csv("titanic.csv") age_sex = titanic[["Age", "Sex"]] print(age_sex) # obtenemos solo los pasajeros mayores de 35 años above_35 = titanic[titanic["Age"] > 35] print(above_35) # visualizamos solo los 10 primeros... print(above_3...
617afcd0aca2d707adbfe45760b5b4202aec6045
Astony/Homeworks
/homework7/task01/find_occurrences.py
704
4.125
4
from typing import Any def find_occurrences(item: dict, required_element: Any) -> int: """ The function gives access for all values in nested structure and allows count the quantity of the required element. """ counter = 0 if item == required_element: counter += 1 elif ...
b2f6bf7f21a4e60815d400795cf0916352c6bb26
avishekbasak/Algorithm
/ds_project_2/problem_2.py
3,823
4.125
4
import os from collections import deque # Folder structure can be comparable to a tree like structure where parent directory is like the root node # So i have used BFS for traversing the complete folder structure # I have created Queue class for the queue that is used in BFS. Every path that i Encounter in the queue, ...
95f45196fc5244f6635900cee0d02ba49d9255b1
schahal/sample
/samplepkg/samplepkg.py
389
3.96875
4
def supercharge(num): """ Supercharges a number by multiplying it with "the answer to life, the universe and everything" Args: num (int): some number Returns: int """ if not isinstance(num, int): raise TypeError("Please provide an int argument.") ANSWER_TO_ULTI...