blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
11c4d5323069e9508fda5693123e227fe17e78d0
sahasatvik/assignments
/CS2201/problemset01/problem03.py
695
4.5625
5
#!/usr/bin/env python3 """ Consider three strings str1 = ‘123’, str2 = ‘234’ and str3 = ‘456’ and print the sum, product and average of the numbers in the strings. """ str1 = "123" str2 = "234" str3 = "456" def sum_digits(s): total = 0 for digit in s: total += int(digit) return total def prod_di...
77a391438b547b91ed225b0c7639189166f89713
chavhanpunamchand/PythonPractice
/Number_Series/Notes_practice/Star_Pattern2.py
231
4.125
4
n=int(input("Enter the number of row:")) for i in range (1,n+1): for j in range(1,i+1): print("*",end=" ") print() for a in range(1,n+1): for b in range(1,n+1-a): print("*",end=" ") print()
4d10f15cd43125bd7b93ad519f6a89655fc2d177
amaeva911/learn_python_14
/week 2/web/weather.py
1,334
3.515625
4
import requests def weather_by_city(city_name): weather_url = 'http://api.worldweatheronline.com/premium/v1/weather.ashx' params = { "key": "c319fbdb846845a58c8134926192809", "q": city_name, "format": "json", "num_of_days": "1", "lang": "ru" } try: r...
4f894f14232c1f4c87e772b7a8dc6e9ac11be3c1
Crown0815/ESB-simulations
/polygon.py
216
3.71875
4
from math import * small_radius = 1.3 side_length = 2 * small_radius number_of_sides = 4 radius = side_length / (2*(sin(pi / number_of_sides))) print(radius+small_radius) print((radius+small_radius)/small_radius)
7f1e1c5a3f0a2e2614b33284fd6dde14fc83294e
cedie1/Python_guanabara_100-exerc-cios-
/ex4.py
416
4.03125
4
#dissecando variavel #Resolução: n1 = (input("Digite algo: ")) print("O tipo primitivo desse valor é",type(n1)) print("Só tem espaços ? ", n1.isspace()) print("É um número ? ", n1.isnumeric()) print("É alfabetico ? ", n1.isalpha()) print("É alfanúmerico", n1.isalnum()) print("Só tem maiúsculas ?",n1.isupper()) print(...
d43c28b0f84d8e5843f1ec639d4f091c126f5468
raffyenriquez/CodingPractice
/codefights/Arcade/Intro/adjacentElementsProduct.py
192
3.640625
4
def adjacentElementsProduct(inputArray): """returns the product of the pair of adjacent elements with the largest product""" return max(x*y for x,y in zip(inputArray, inputArray[1:]))
0dd20076a088a1758102133f0233661d2ce4afe0
wwlorey/stylesheet-stealer
/parser.py
4,847
3.609375
4
import sys import os.path # Returns an empty string if char is a space, returns space (' ') otherwise def insertSpaceCheck(char): if char is ' ': return '' else: return ' ' # Read command line arguments if len(sys.argv) == 3: # All expected arguments are present fileInName = sys.argv[1] ...
32f79970476e37641d3af22bc777c6da46338941
bud-welsh/FourHourPython
/stringPractice.py
777
4
4
print("Good Times") # A regular string print("A\nnew\nline") # A new line print("\"Escaping quotes\"") phrase = "This string comes from the variable \"phrase\"." print(phrase) print(phrase + "\nThis string comes from concatenation.") print(phrase.lower()) # Make phrase all lower case letters print(phrase.upper()) #...
cedf9ef191f6c9315bbdde0700321bdddad929a5
henryscala/leetcode
/py/p25_reverse_k_group.py
2,380
3.765625
4
# problem 25 of leetcode # Reverse Nodes in k-Group # Given this linked list: 1->2->3->4->5 # For k = 2, you should return: 2->1->4->3->5 # For k = 3, you should return: 3->2->1->4->5 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = No...
eba92b0ed7d5e31c1e5c1c095c7634d575381061
codershona/python-Programming-Language-Learning
/Python Operator/operator.py
1,126
4.59375
5
# Python Operators # Operators are used to perform operations on variables and values. # Python divides the operators in the following groups: # Arithmetic operators # Assignment operators # Comparison operators # Logical operators # Identity operators # Membership operators # Bitwise operators # Python Arithmetic Op...
502260d0f40b827aaf48ede5a205d81c8d9a8910
palanuj402/Py_lab
/File/q16.py
322
4.625
5
#Write a python program to check whether the string is Palindrome or not. def check(s): if s==s[::-1]: return True else: return False s=input("Enter a string to check pallindrome: ") c=check(s) if c is True: print(s,"is Pallindrome") else: print(s,"is NOT a Pallindrome") ...
8b37718000fa70a91814884105e24eb9e72f69a8
caowens/Blackjack
/blackjack_final.py
1,214
4
4
# DO NOT REMOVE from deck import print_card, draw_card, print_header, draw_starting_hand, print_end_turn_status, print_end_game_status # User turn # draw a starting hand for the user and store it into a variable user_hand = draw_starting_hand("YOUR") # allow the user to see hand value and decide to hit or stand respo...
85380438fd80cc9a8a3c45f1996e1bff043e7923
Insookim0702/python_Algorithm
/책/DFSBFS/me음료수얼려먹기3.py
410
3.578125
4
n,m = 3,3 graph= [[0,0,1],[0,1,0],[1,0,1]] result = 0 def dfs(x,y): if x <= -1 or x >=n or y <= -1 or y >=m: return False if graph[x][y] == 0: graph[x][y] = 1 dfs(x+1, y) dfs(x-1, y) dfs(x, y+1) dfs(x, y-1) return True return False for i in range(n): ...
e1e77285d533abb2e3b93200a64749b0bf93012a
daniel-reich/turbo-robot
/88RHBqSA84yT3fdLM_10.py
1,216
4.125
4
""" Create a function that takes a single word string and does the following: 1. Concatenates `inator` to the end if the word ends with a consonant, otherwise, concatenate `-inator` instead. 2. Adds the word length of the original word to the end, supplied with "000". The examples should make this clear. ###...
f37d3b616846f6283f2b8821b1f6ea141b1ed4d2
Mostofa-Najmus-Sakib/Applied-Algorithm
/Leetcode/Python Solutions/Matrix/SetMatrixZeroes.py
1,213
3.859375
4
""" LeetCode Problem: 73. Set Matrix Zeroes Link: https://leetcode.com/problems/set-matrix-zeroes/ Language: Python Written by: Mostofa Adib Shakib Time Complexity: O(M*N) Space Complexity: O(M*N) M: Number of rows N: Number of columns """ class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: ...
a7384a2e25f3745462f7f0e9ff32589bdd0693a4
Buthjaga/pdsnd_github
/bikeshare.py
7,329
4.25
4
from sys import exit import calendar import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv'} #Took out washington because it's missing the Gender and Year columns thus causing errors def get_filters(): """ Asks ...
4841d95fdd984b88a29c3ccb579c8c048e934d45
xjr7670/corePython
/2-15b.py
345
3.875
4
#!/usr/bin/env python a = int(raw_input("Please input num 1: ")) b = int(raw_input("Please input num 2: ")) c = int(raw_input("Please input num 3: ")) if a > b > c: print a, b, c elif a > c > b: print a, c, b elif b > a > c: print b, a, c elif b > c > a: print b, c, a elif c > a > b: print c, a, b...
35f261c70dbe3a6995a0aa8705a588baa6bd8b13
JavasMiddi/PythonTasks
/GradeCals.py
147
3.875
4
mark = int(input("Please input a mark: ")) if mark > 85: print("Distinction!") elif 65 < mark < 85: print("Pass!") else: print("Fail!")
ee95a2687f8685de55d662df75c9bfd75b49ed11
BIAOXYZ/variousCodes
/_CodeTopics/CodeForces/problemset/4A/4A.py
203
4
4
weight = raw_input() remainder = int(weight) % 2 if int(weight) < 3: print "NO" elif remainder: print "NO" else: print "YES" """ https://codeforces.com/problemset/submission/4/94371519 """
3db370ca624b4616e1278e4ad2cb15ae45ac3b08
borislavstoychev/Soft_Uni
/soft_uni_OOP/Attributes and Methods/lab/integer_2.py
1,218
3.875
4
class Integer: def __init__(self, value: int): self.value = value @staticmethod def from_float(value): if not isinstance(value, float): return "value is not a float" return Integer(int(value)) @staticmethod def from_roman(value): rom_val = {'I': 1, 'V':...
9025ab5e1f0780171ad5caa2d6021b0ffecdfb80
nickbent1/PythonCasino
/Slotmachine.py
4,458
3.859375
4
# Please make sure this file name is "Slotmachine.py" (with a capital S) # Please make sure you have Casino.py print("You have 20 coins.", "\n","1 coin = 1 spin", "\n", "Match 3 symbols in a row in order to win!", "\n", "[ 777 ] = 15x ","\n","[ Win ] = 2x","\n","[ BAR ] = 3x","\n","[ BANKRUPT ] = LOSE","\n","[ (8) ...
d980a4d6c7a610e4506661fbfcf4d50ff6fc1a81
ThayseSantos/security-tools-with-python
/ComparadorHash/ch.py
601
3.53125
4
import hashlib arquivo1 = 'primeiro.txt' arquivo2 = 'segundo.txt' #ripemd160 = algoritmo de hash hash1 = hashlib.new('ripemd160') hash1.update(open(arquivo1, 'rb').read()) hash2 = hashlib.new('ripemd160') hash2.update(open(arquivo2, 'rb').read()) #comparação: if hash1.digest() != hash2.digest(): print('Hashs Di...
ae4fd272273c34efead67b5110db09548a21c8fa
sabergjy/Leetcode_Programing
/36.有效的数独.py
795
3.765625
4
class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: col = defaultdict(set) #表示建立一个字典(哈希结构),其value是一个集合 ,也可以放一个列表,一样的 row = defaultdict(set) sqrt = defaultdict(set) for i in range(len(board)): for j in range(len(board[0])): if board[...
4f71562f177993c4397ff1b89f16b1b00464d608
andreztz/estrutura_de_dados
/queue.py
2,070
4.3125
4
''' Fila (=queue) FIFO (=First_In-First_Out) significa primeiro a entrar, primeiro a sair. É uma estrura de dados implementada para gerar fila de espera. Em uma fila do tipo FIFO os elementos vão sendo colocadosna fila e retirados (ou processados) por ordem de chegada. A idéia fundamental da fila é que só podemo...
26f7a004bef968a024ea37136cb2a1c8860674c7
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/mdlsan019/question2.py
2,176
4.28125
4
'''SANELE MDLALOSE MDLSAN019 Vectors: additional, dot products and normalization Assignment6,Question2 21 April 2014''' from math import * A=input("Enter vector A:\n") #Get vector values A=A.split() B=input("Enter vector B:\n") B=B.split() A_add_B=[' ', ' ', ' '] #Create a list of three ...
58f40c1bd905abf5f69cb094603422f3cfe132a1
ravenac95/testvirtstrapdocs
/tests/tools/data.py
521
3.59375
4
""" Various Data Test Tools """ import random NUMBER = "0123456789" SYMBOL = """!@#$%^&*()_+=-[]\;',./{}|:"<>?~`""" ALPHA_LOWER = "abcdefghijklmnopqrstuvwxyz" ALPHA_UPPER = ALPHA_LOWER.upper() ALL_ALPHA = ALPHA_LOWER + ALPHA_UPPER ALPHA_NUMERIC = ALL_ALPHA + NUMBER ALL_CHARS = SYMBOL + ALPHA_NUMERIC def random_string...
f78e9e7476ff7a34765f10df6752b8d2c5183d97
EmersonElectricCo/lowball
/lowball/models/provider_models/auth_db.py
2,136
3.828125
4
from abc import ABC, abstractmethod class AuthDatabase(ABC): """Base class for user-defined Auth Database classes. The data that is passed into the init is determined by the developer and the config that is passed into the init. """ def __init__(self, **kwargs): pass @abstractmethod ...
d697e5d9e9b5f444e4ce29da002257f237a2d6ed
Aaron44201/Assignment
/Money counting.py
588
3.90625
4
#Aaron Bentley #19/09/14 #money counting amount = int(input("Please input your amount of money: ")) twenty = amount // 20 remainder = amount % 20 ten = remainder // 10 remainder2 = remainder % 10 five = remainder2 // 5 remainder3 = remainder2 % 5 two = remainder3 // 2 remainder4 = remainder3 % 2 one = r...
827c4be6a60e7aa3cfa56c1b4eb568aebe54413e
johnwanjema/python
/hello.py
989
4.25
4
# importing date class from datetime module from datetime import date # creating the date object of today's date todays_date = date.today() print("Hello Python") # List is the most basic Data Structure in python. # List is a mutable data structure i.e items can be added to list later after the list creation. # cre...
33789f992f4c9ca852c871a6d5c172f88e2c46c3
JANSSOC/python-challenge
/pypoll/maindevlopment.py
2,576
3.6875
4
import os import csv Filepath = os.path.join('..','..','..','UNCCHAR201811DATA3','02-Homework','03-Python','Instructions','PyPoll','Resources','election_data.csv') #print(Filepath) #C:/Users/cjans/documents/Bootcamp/HW2VBA/python-challenge/pypoll/.git/ #Filepath = '..\..\..\UNCCHAR201811DATA3\02-Homework\03-Python\Inst...
de05add23302fc384fdbf1aafbe8bf5f5eb509fa
natacadiz/Nata
/Ejercicios Unidad 1/1.8.py
323
3.703125
4
# Escribir el programa del ejercicio 1.7 usando solamente dos variables diferentes. #2+3+4 suma = int(input()) suma += int(input()) #suma = suma + int(input()) suma += int(input()) #suma = suma + int(input()) + int(input()) print (suma) #colocamos el nombre de la variable principal y nos imprime la operacion de las t...
ad5f3d41a24b117f7926c3a191f6418a31d17006
05suraj/my-python-tutorial
/map_fil.py
443
3.875
4
# def addtion(n): # return n+n # number=(1,2,3,4,5,6) # result=map(addtion,number) # print(list(result)) # todo------that is lamda in in line fun----- # number = (1, 2, 3, 4, 5, 6) # result=map(lambda x:x+x,number) # print(list(result)) number1 = [1, 2, 3, 4] number2 = [5, 6, 7, 8] result = map(lambda x, y: x*y...
1a806319d41a3c5642466858e791becc34e07ac7
daressatyam/PYTHON-WITH-DATA-STRUCTURE
/week 3/matrixflip.py
190
3.515625
4
def matrixflip(m,d): tempm = m.copy() if d=='h': for i in range(0,len(tempm),1): tempm[i].reverse() elif d=='v': tempm.reverse() return(tempm)
eba0e2c33e10cbadcb222b911afa203fef6e3859
dragos-vacariu/Python-Exercises
/Exercises/zipping, combining multiple lists and tuples together.py
306
4.34375
4
#Zipping (combining) list together. Lst1 = ["Dragos", "Alan", "Robin"] Lst2 = ["Blake", "Walker", "Williams"] names = zip(Lst1,Lst2) #names will be a new list, a 2D list I might say, containing all the elements in #Lst1 and Lst2 combined. #Iterating names: for a,b in names: print("Name = ", a, b)
135f701576a50cb261bdddd7a2d5695792c3d20f
OhadAvnery/do_you_mind
/doyoumind/utils/reader_utils.py
1,266
4.0625
4
import struct def unpack_format(file, fmt): ''' Unpacks the format from the file using struct.unpack, to the correct number of bytes, and returns the result. :param file: the file to read from :type file: Path :param fmt: the format to read :type fmt: str :returns: the result of the re...
30dbb1b12318f7693f8281df31a28390e53cc8a2
stevenyan7/mario-game
/My_Mario_Version_2.py
7,227
3.953125
4
#Assignment 5 - My_Mario_Version_2.py # ##The goal of our Assignment 5 is to allow the player (user) to play our game by moving Mario ##around the maze. #There are also rewards and exploding obstacles in the maze! # #Chu Yan #Yaben Yang #April 8, 2016 import random def playGame(score,MPosition, rewardin...
ef0c1ea9df08aece100e344ad05646ccba342526
sbhotika/15112-term-project
/ui_main.py
14,696
3.609375
4
# events-example0.py # copied from https://www.cs.cmu.edu/~112/notes/events-example0.py # Super Maze! from Shubhangi Bhotika + sbhotika # all algorithms were based on those found at: # https://en.wikipedia.org/wiki/Maze_generation_algorithm # the images were found on the Google # the buttons were drawn using this...
df0d9ec77a96d471c4ff47bef12ee6181e308649
jemand2001/adventofcode2020
/day_10.py
1,261
3.578125
4
from utils import run, test, cached from typing import List, Tuple from collections import Counter examples = ("""16 10 15 5 1 11 7 19 6 12 4""", """28 33 18 42 31 14 46 20 48 47 24 23 49 45 19 38 39 11 1 32 25 35 8 17 7 9 4 2 34 10 3""") # @test(examples=examples) @run() def day_10_1(adapters: List[int]): adapte...
e46c7fb3bdf740fe741c7e5580bfd85d17ee5bb0
nekapoor7/Python-and-Django
/GREEKSFORGREEKS/List/swap_position.py
274
4.09375
4
#Python3 program to swap elements # at given positions def swapElement(list,pos1,pos2): list[pos1],list[pos2] = list[pos2] , list[pos1] return list1 list1 = list(map(int,input().split())) pos1 = int(input()) pos2 = int(input()) print(swapElement(list1,pos1,pos2))
0c0218b74a9eda64b228f046a5afbddabffdaede
mkabajah/Recursive_Univirsal_Diff
/Recursive_Univirsal_Diff.py
9,812
3.703125
4
""" @copyright: This code related to Eng.Mohammad Kabajah email: Kabajah.mohammad@gmail.com @author: Mohammad Kabajah @Contact: Kabajah.mohammad@gmail.com @date: Nov 24, 2014 @Purpose: Getting the Deep Difference of dictionaries, iterables, strings and other objec...
7a7427f6e72389b41ef3e0e05963e397c4dbe73f
atul0058/Python_Data_Structures
/week4.py
2,296
4.34375
4
atul='string' print(atul[1]) print("-----") for i in atul: print(i) print("-----") atul1="after three hours you will hop in a bus which will be going to Amsterdam" x=atul1.split() #this returns a list. Always remember, the split funciton gives you a string print(x) print("-----") #line.rstrip vs...
6a9b52f819c13ae1a4fbeb2848b0afac94873a71
gokou00/python_programming_challenges
/coderbyte/MaxSubarray.py
261
3.75
4
def MaxSubarray(arr): max_ending_here = max_so_far = arr[0] for x in arr[1:]: max_ending_here = max(x, max_ending_here + x) max_so_far = max(max_so_far, max_ending_here) return max_so_far print(MaxSubarray( [-2, 5, -1, 7, -3]))
170391e61e272dfffab2f52e12c625a5a87ccfdc
jagannath/bacterialoperons
/gen_fgoc_calc.py
15,835
3.828125
4
#! usr/bin/python # Script calculates the gen-fgoc score for every organisms. The accession number of the organisms is passed and it calculates the gen-fgoc score. The gen-fgoc score is the 2 * number of conserved adjacent gene pairs (correct direction) / # gene_pairs (ecoli) + # gene_pairs (orgX). This can be normali...
a17afce3ff4d127a615411bf093bf59fcfa98c9a
makramjandar/Test_Code
/Problems/compressString.py
1,758
3.734375
4
#!/usr/local/bin/python3 def main(): # Test suite tests = [None, '', 'AABBCC', 'AAABCCDDDD'] results = [None, '', 'AABBCC', 'A3BCCD4'] for i in range(len(tests)): temp_result = compress_string(tests[i]) if temp_result == results[i]: print('PASS: {} returned {}'.format(tes...
7961eb265bee00c41add25f83adc17ee67aa45f8
doug460/UAV_DL
/UAV_control/Environment.py
6,971
3.609375
4
''' Created on Feb 20, 2018 @author: dabrown ''' import GlobalVariables as vars from UAV import UAV from Target import Target import random import math import numpy as np class Environement(object): ''' This is the environment for the game world Basically this class will control the world of a UAV tracki...
f086b8d4f5e1c9e6ea62995a5572ba4a155c07df
Powergears/Python-Repository
/erste-pythonchallenge.py
156
3.890625
4
text = input("Please write a first number: ") text2 = input("Please write a second number: ") text3 = text * text2 print("%s*%d=%r") % (text, text2, text3)
5ac53654244fe241084ee01629a1c5448091e6f3
cudjoeab/Object-Oriented_Programming-3
/01-Reinforcing_OOP/reinforce.py
697
3.5
4
class Task: def __init__(self, description, due_date): self.description = description self.due_date = due_date def __str__(self): return f'{self.description} due: {self.due_date}' def __repr__(self): return self.__str__ class TodoList: def __init__(self): ...
90db8db2c1d2b1f68c56c4449b4c65a612723e22
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/leap/c213610e0b9b4c54954dc991b63da0ad.py
322
3.71875
4
def div_by_4(year): return not year % 4 def div_by_100(year): return not year % 100 def div_by_400(year): return not year % 400 def is_leap_year(year): if div_by_100(year) and not div_by_400(year): return False elif div_by_4(year): return True else: return False...
84814f34bc22f7945563bdfff04690abe34ed9cb
Pepper-Targaryen/PythonStudy
/learnML/day003.py
807
3.640625
4
import pandas as pd import numpy as np dataset = pd.read_csv('dataset/50_Startups.csv') X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, -1].values # Encode categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder = LabelEncoder() X[:, 3] = labelencoder.fit_transform(X[:, 3]) one...
e32750f662b94ea2665f5f4743a2b896114a8ca0
jas7553/project-euler
/problem_20.py
180
3.765625
4
'''Jason A Smith''' def factorial(number): if number == 1: return 1 else: return number * factorial(number - 1) print(sum([int(i) for i in str(factorial(100))]))
562da3552e9669563d24001af8a889338681fd85
Seemasikander116/ASSIGNMENT-1-2-AND-3
/ASSIGNMENT 1.py
1,405
4.375
4
#!/usr/bin/env python # coding: utf-8 # Seema Sikander # seemasikander116@gmail.com # Assignment #1 # PY04134 # In[4]: ##1. Write python program to print the following string in a specific format. a="Twinkle" b="twinkle" c="little" d="star" e="wonder" f="diamond" g="world" print(a, b,c, d+",") print(" How I ",e...
9f596b9995f248bab6c5f195e732f039855fff3f
WellJay/learn-python3
/3.advanced/3.ListComprehensions.py
1,827
4.1875
4
''' 列表生成式 列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。 举个例子,要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用list(range(1, 11)): list(range(1, 11)) 但如果要生成[1x1, 2x2, 3x3, ..., 10x10]怎么做?方法一是循环: L = [] for x in range(1, 11): L.append(x * x) 但是循环太繁琐,而列表生成式则可以用一行语句代替循环生成上面的lis...
5047d214a8c793393a651903eb38d43f0302b751
CodeHemP/CAREER-TRACK-Data-Scientist-with-Python
/09_Introduction to Data Visualization with Seaborn/03_Visualizing a Categorical and a Quantitative Variable/01_Count plots.py
1,569
4.3125
4
''' 01 - Count plots In this exercise, we'll return to exploring our dataset that contains the responses to a survey sent out to young people. We might suspect that young people spend a lot of time on the internet, but how much do they report using the internet each day? Let's use a count plot to break down the...
4cb4e8d3373c086518bd6c83921f240b852fa4cb
RivasCVA/AlgoShell
/mvp/AlgoShell/solutions/sales_path.py
543
3.75
4
def get_cheapest_cost(rootNode): return getMinSalesPath(rootNode) def getMinSalesPath(node): if not node.children: return node.cost childSums = [getMinSalesPath(child) for child in node.children] return node.cost + min(childSums) # NOTE: This Node class should be kept commented for the user to...
95a9901d417313b455dce96f188d841f2a3b0b11
ishauchuk/crash_course
/3.3.py
215
4
4
cars = ['Ferrari', 'Lamborghini', 'Buggati', 'McLaren'] print(f'My favorite auto is {cars[0]}.') print(f"{cars[1]} is named cars bull's names.") print(f"{cars[-1]} is one cars's company from my list outside Italy.")
868fc123255830d3a1dc03a2be09530320baab50
happyrabbit456/hellopython
/src/withs.py
1,199
3.796875
4
def m2(): f = open("output.txt", "w") try: f.write("python之禅") except IOError: print("oops error") finally: f.close() # 一种更加简洁、优雅的方式就是用 with 关键字。 # open 方法的返回值赋值给变量 f,当离开 with 代码块的时候, # 系统会自动调用 f.close() 方法, # with 的作用和使用 try/finally 语句是一样的。 def m3(): with open("output.txt...
158e339371c3b0c796f9f2b63071b19e8b4ab15e
JeffreyLinWeiYou/flask_project
/flaskproject/blog_simple/app/app.py
11,294
3.734375
4
''' 學習http://charlesleifer.com/blog/how-to-make-a-flask-blog-in-one-hour-or-less/ 簡單的網誌配置 使用sqlite資料庫 需要的庫 Flask, a lightweight web framework. Peewee, for storing entries in the database and executing queries. pygments, syntax highlighting with support for a ton of different languages. markdown, formatting fo...
d662b53e82fb0084779167e13cef30f7ce2f0498
Annal-L/pythonProject
/Operators.py
3,311
4.28125
4
# Arithmetic operations n1 = int(input('Enter First number: ')) n2 = int(input('Enter Second number ')) add = n1 + n2 sub = n1 - n2 mul = n1 * n2 div = n1 / n2 floor_div = n1 // n2 power = n1 ** n2 modulus = n1 % n2 print('Addition of ',n1 ,'and' ,n2 ,'is :',add) print('Subtraction of ',n1 ,'and' ,n2 ,'is :',sub) print...
c3c9ed77ec3715181eba74def5fd45e35db9aabd
chanyoonzhu/leetcode-python
/1597-Build_Binary_Expression_Tree_From_Infix_Expression.py
1,180
3.875
4
# Definition for a binary tree node. # class Node(object): # def __init__(self, val=" ", left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: """ - stack (two stacks) - similar questions: Basic calculator III """ def expTree(sel...
da6e85ccae9de50f9e5de364e9b6a3761b73c93f
StephanieMaia15/Python
/desafio048_impares_multiplos_3.py
306
3.765625
4
#verificando quais numeros sao impares em uma lista de um ate 500 e realizando a soma deles soma = 0 cont = 0 for c in range(1, 501, 2):# 2 = pulando de dois em dois if c % 3 == 0: soma += c cont += 1 print('\33[0:44mA soma dos {} valores multiplos por 3 é: {}\33[m'.format(cont, soma))
25a4d3bceb5d593fda81e219b206cc4393edd4ff
tushsoni/PYTHON-BEGINNERS-TO-ADVANCED
/PYTHON COURSE/40 - Chapter-3_Exercise-4.py
879
4.25
4
# **************************************** CHAPTER-3_EXERCISE-4 ******************************************** # # QUESTION 2 OF THREE # QUESTION 2 : Ask user to input a number containing more than one digit , example-1256 , calculate 1+2+5+6 and print # Algorithm use to ...
f8d4a8e36b776e9607ab343451df6b200a6ebd55
vlanunez/IS211_Assignment4
/sort_compare.py
2,284
3.65625
4
#!/usr/bin/env python # coding: utf-8 # In[8]: import time import random def insertion_sort(a_list): start_time = time.time() for index in range(1, len(a_list)): current_value = a_list[index] position = index while position > 0 and a_list[position - 1] > current_value: ...
62e05dbee2729ec2ed6021689836e0f209f7451b
Eemann33/Python-Data-Structures
/stack.py
1,056
4.375
4
'''Creating a Stack in Python by using a list''' class Stack: def __init__(self): self.items = [] def push(self,item): '''Appends item to end of list''' self.items.append(item) def pop(self): '''Returns and removes items at front of the Stack''' self.items.pop() ...
353f91ae3eb863495d124bef1a384fae127b0580
Iamnahin/Games
/pong_game.py
3,017
3.734375
4
import turtle wn=turtle.Screen() wn.title("Pong game by Nahin") wn.bgcolor("black") wn.setup(width=800,height=600) wn.tracer(0) score_left=0 score_right=0 #Left paddle left_paddle=turtle.Turtle() left_paddle.speed(0) left_paddle.shape("square") left_paddle.color("white") left_paddle.shapesize(stretch_wid= 5,stretc...
6ddf8529b09adab966ca963e656b217c273e1164
starkblaze01/Algorithms-Cheatsheet-Resources
/Python/Sorting Algorithms/pancake_sort.py
696
4.0625
4
#pancake sort implementation in python def flip(arr, i): start = 0 while start < i: temp = arr[start] arr[start] = arr[i] arr[i] = temp start += 1 i -= 1 def findMax(arr, n): maxi = 0 for i in range(0,n): if arr[i] > arr[maxi]: maxi = i r...
fbfa489bc2cf6479be7b9917d62868b4f60ac3ed
Shubhankar-wdsn/Hackerrank-Python
/Utopian Tree.py
592
3.71875
4
#!/bin/python3 import math import os import random import re import sys # Complete the utopianTree function below. def utopianTree(n): tall = 1 i = 0 while i < n: if i % 2 != 0: tall = (tall + 1) elif i % 2 == 0: tall = (tall*2) i = i+1 ...
1a341e8a49507502a2c98421782cd9be3627b0ee
rabbitxyt/leetcode
/657_Judge_Route_Circle.py
674
3.890625
4
# Initially, there is a Robot at position (0, 0). # Given a sequence of its moves, judge if this robot makes a circle, # which means it moves back to the original place. class Solution(object): def judgeCircle(self, moves): """ :type moves: str :rtype: bool """ p = [0,0] ...
df5bf9f301d2b8c7401fdb046853b73660a3fa29
Ri-Hong/CCC-Solutions
/CCC '04/CCC '04 J3 - Smile with Similes.py
898
3.984375
4
''' Author: Ri Hong Date AC'd: Feb 1, 2020 Problem: https://dmoj.ca/problem/ccc04j3 ''' #Explanation ''' Get each adjective and store them in an adjective list Get each noun and store them in an noun list Loop through each element of the adjective list. For each element of the adjective list, loop through all the ele...
842b5223f6125d9f1f0c4b8e5880c18c653fc810
AmritaDeb/Automation_Repo
/PythonBasics/py_programas/Assignment_13_12_18/Fibonacii_Yield.py
261
3.859375
4
class Fibonacii_Yield: def fibonacii(self,n): a, b = 0, 1 while n > 1: yield a a, b = b, a + b ob=Fibonacii_Yield() m=ob.fibonacii(2) i=(iter(m)) print(i) for x in range(6): print(next(i)) raise StopIteration
2fbeb9fa5838b26ddcc3aa8402f70b7d7bd1b1f7
aimdarx/data-structures-and-algorithms
/solutions/Trees and Graphs/Binary Trees/construct_binary_tree_from_preorder_and_inorder_traversal.py
5,056
4.15625
4
""" Construct Binary Tree from Preorder and Inorder Traversal: Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree. Example 1: Input: preorder = [3,9,20,15,7], inorder = ...
41b5ee9a68fb16f0e5a406218bd1987264744680
Alonsovau/sketches
/chapter8/st8.py
2,057
4.03125
4
# 子类中扩展property class Person: def __init__(self, name): self.name = name @property def name(self): return self._name @name.setter def name(self, value): if not isinstance(value, str): raise TypeError('Expected a string') self._name = value @name.del...
21f2aae2b9f7b12ccc84e0c679a3a8cb95f38be4
timolegros/StoreProductOrganizer
/V1.py
8,632
4.15625
4
def onShelves(): """This function opens the onshelves.txt file and appends the information to a list. The product # and ammount in stock is appended to a list. Then the function converts this information into int format and filters the products to find those that actually need to be ordered. These are appen...
abdf84ab8f870517c4e04544c2a2696fa7213380
yorickcleerbout/Advent-Of-Code-2020
/Day_02/Day_02.py
820
3.859375
4
import re def check_pass(password): p = re.search('(\d+)-(\d+) ([a-z]): (.*)', password) count = p[4].count(p[3]) if int(p[1]) <= count <= int(p[2]): return True else: return False def check_pass_2(password): p = re.search('(\d+)-(\d+) ([a-z]): (.*)', password) ...
cf139df6d0e54d901e7350087dac0a3e727eeccc
xyuuzz/belajar-python
/no 1-9/4.slicing_string.py
1,498
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 12 11:09:16 2021 @author: xyuuz """ # Slicing adalah sebuah metode memecah value dari tipe data yang bersifat itterable # cara memecahnya pun mudah, yaitu dengan menggunakan rumus : # [i.awal:i.akhir:jarak] # ingat, indeks awal dimulai dari 0 # c...
ca0cdde561e243579594d11f9cacc3ecb027edf4
nikitiwari/Learning_Python
/sum_nrecurson.py
194
4.125
4
print "Sum of n natural numbers using recursion" n = (int)(raw_input("Enter a number :")) def sum_n( x) : if x == 1 : return 1 else : return (x+sum_n(x-1)) print sum_n(n)
0974cd89d6cdaada3d6621ee22eff0a2bc1cdb6f
goncalo-reis/CS50-Harvard-Online-Course
/pset7/houses/roster.py
591
3.734375
4
from cs50 import SQL import sys # Check number of arguments if len(sys.argv) != 2: print("Wrong number of arguments.") exit(1) # Execute db = SQL("sqlite:///students.db") list_results = db.execute("SELECT first, middle, last, birth FROM students WHERE house = ? ORDER BY last, first", sys.argv[1]) # Print the...
37e512e8bcfbe4aadb2485049edf1b1f85a06a46
djmar33/python_work
/ex/ex7/rollercoaster.py
292
4.09375
4
#7.1.2使用int()获取数值输入 height = input("你的身高多少?") #将字符串转换为数值; height = int(height) #将用户提供信息进行判断; if height >= 36: print("你身高适合玩过山车呀!") else: print("你身高还不适合玩过山车哦~")
b368340827aa8168d5e871f3048cce533ca3b33f
adityaranjan65/COURSERA-DSA
/week3_greedy_algorithms/6_maximum_number_of_prizes/different_summands.py
536
3.984375
4
# Uses python3 import sys def get_max_pairwise_sum(n): pairs = list() pairs.append(1) temp = 2 while n != 0: if n > (temp * 2): pairs.append(temp) n -= temp temp += 1 else: pairs.append(n) break print(len(pairs)) for x ...
614467a00ad63b92b5ce7ccc818018be4fb08372
lalapapauhuh/Python
/CursoEmVideo/pythonProject/ex036.py
811
3.796875
4
#aprovando emprestimo from time import sleep cores = {'limpar': '\033[m', 'verde': '\033[32m', 'vermelho': '\033[31m', 'pretob': '\033[7;30m' } casa = float(input('Qual o valor da casa? R$ ')) salario = float(input('Qual valor do seu salário? R$ ')) anos = int(input('Em quantos anos...
e29946eb9ac767710576cc04bfd44f20fa5e14e8
TravelSir/leetcode_solutions
/1-100/20. Valid Parentheses.py
1,421
3.921875
4
""" 解题思路: 首先一个有效括号肯定是有一个左括号和一个右括号,且左括号在右括号左边 但假如在一对括号里包含了其他的括号,那为了保证有效,那肯定这对括号里的括号也肯定满足要求。 那么其实从小我们的数字基础就告诉我们,括号是按就近原则的。 那么转换到这道题里 我们可以用栈的方式,每一个左括号都入栈,当有右括号时,判断栈是否为空或栈末元素是否与右括号为同一类型括号,栈为空或不满足同一类型则一定为无效字符串,满足即可出栈继续判断 最后再判断一下栈是否为空,不为空则还有左括号未找到对应右括号,也无效 这里我们把括号转化为数字,方便判断,左括号都大于0,右括号都小于0。相同类型的左右括号之和为0 """ class Solution:...
c05b579a878ee242aa0e59edb5a2dadd8002d1a7
MLlounge/ML-Project
/Basic Project/DNN - Train Mathematical Expression(lnx)/DNN - Train Mathematical Expression(lnx).py
3,230
3.796875
4
# you can watch more on ' www.mllounge.com ' # DNN model to learn ln(x) from keras.models import Sequential from keras.layers import Dense, Dropout from keras.optimizers import Adam import numpy as np import matplotlib.pyplot as plt class Data: # Create data def __init__(self): self.y = 0 # y val...
6c71fc6a94b50b5802a542d7f4debb7ecfc341ff
kanybek740/Chapter1_Part2_Task26
/task26.py
251
3.828125
4
numbers = input('vvedi chislo: ') num = list(numbers.split(',')) chetnye = [] nechetnye = [] for number in (num): if int(number) % 2 == 0: chetnye.append(num) else: nechetnye.append(num) print(len(chetnye), len(nechetnye))
d465097fab5dea1dfcac47522c9925a07880b513
drakenmang/EjerciciosJava
/Python/EjercicioindependienteWhile.py
469
3.828125
4
print("Confirme su contraseña (2) ") pw=(input("escriba su contraseña: ")) lim = 3 print("Tiene " + str(lim) + " intentos para confirmar su contraseña ") pw2=(input("Escriba de nuevo su contraseña ")) contador=1 while pw != pw2 and contador < limite: print("Las contraseñas no coinciden. Hagalo de nuev...
c5ea44e23d92e25b59415877b0aababde4572478
Ravi5ingh/ibm-recommendation-engine
/investigations.py
812
3.515625
4
import utility.util as ut def get_article_id_frequency(articles): """ Get the frequency with which each article Id appears :param articles: The articles data :return: The frequency mapping """ print('Scanning articles for dupes...') total = ut.row_count(articles) article_frequency_mapp...
f641da7814a84894ea0fceed0c74c0ea239fb5b5
jaredjamieson/personal
/python/FileFunctions/Lab 9 -Jamieson Cardaropoli.py
4,860
3.859375
4
#Lab 9 Jamieson & Cardaropoli #Imports import random import csv #Takes filename and prints one line at a time def display_file(filename): userfile = open(filename, 'r') for line in userfile: print(int(line)) userfile.close() #Takes filename and n, prints top n lines def display_head(filename, n): ...
011cd3e018c479f412aa87c312c972ba541cdef2
jibinwu/test
/testHome/use_random.py
190
3.53125
4
import random ll=[] # result=random.randrange(1,3)#不包括3 for i in range(10): result=random.randint(1,1000)#包括3 ll.append(result) ll.sort(reverse=True) sorted(ll) print(ll)
e09ec11b9800ac7942edfc145d5f2e22f0e47ace
iamish08/Py-Program
/commonwords.py
523
3.984375
4
#to count the 10 most common word in a given text file #create a text file before execution import string fname=input('Enter filename:') fhand=open(fname) counts=dict() for line in fhand: line=line.translate(str.maketrans(","," ",string.punctuation)) line=line.lower() words=line.split() for word in words: if word i...
7cb11f1c98515b496a983359c8034a1693377bc7
mukundajmera/competitiveprogramming
/Deque/Insertion in deque.py
565
3.75
4
# User function Template for python3 def deque_Init(arr, n): # code here dq = deque() for i in range(len(arr)): dq.append(arr[i]) return dq # { # Driver Code Starts # Initial Template for Python 3 # contributed by RavinderSinghPB if __name__ == '__main__': from collections import deque...
41df1d5f9ebe3e09be81e304b9a9db99cf7f1fb0
CapSOSkw/My_leetcode
/中文leetcode/简单/1460. 通过翻转子数组使两个数组相等.py
1,451
3.640625
4
''' 给你两个长度相同的整数数组 target 和 arr 。 每一步中,你可以选择 arr 的任意 非空子数组 并将它翻转。你可以执行此过程任意次。 如果你能让 arr 变得与 target 相同,返回 True;否则,返回 False 。 示例 1: 输入:target = [1,2,3,4], arr = [2,4,1,3] 输出:true 解释:你可以按照如下步骤使 arr 变成 target: 1- 翻转子数组 [2,4,1] ,arr 变成 [1,4,2,3] 2- 翻转子数组 [4,2] ,arr 变成 [1,2,4,3] 3- 翻转子数组 [4,3] ,arr 变成 [1,2,3,4] 上述方法并不是唯一的...
a04a577606937fccf49694038adc1e27f6376c03
rayjustinhuang/ProjectEuler
/Problem 3.py
1,289
4.09375
4
#Define prime factorization function def primefactorize(number): factors = [] for i in range(1,int(number**(.5)+1)): if number%i != 0 or i == 1: continue else: number = number/i factors.append(i) return factors #n = input("Enter the integer...
a612cb6fcb41516596882e54d3beeb57d1b27e24
davidlyness/Advent-of-Code-2017
/21/21a.py
2,804
4.0625
4
# coding=utf-8 """Advent of Code 2017, Day 21, Part 1""" def convert_string_to_grid(grid_string): """ Convert the string representation of the grid to a 2D array. :param grid_string: input string :return: 2D representation of the grid """ return list(map(list, grid_string.split("/"))) def co...
df04100da24ce78fc094488edcb25452f3d389c3
nicholasgdml/exercicioscursoemvideo-python
/ex_python_mundo1/ex007.py
170
3.828125
4
print('Digite suas notas escolares') nota1 = float(input('Nota1: ')) nota2 = float(input('Nota2: ')) media = (nota1 + nota2) / 2 print('A sua média é {}'.format(media))
9ed6979a4b6cf2549f952b81e5fca48833017dae
YuZhangIsCoding/Algorithms_python
/Classic_problems/searchMatrix.py
7,287
3.65625
4
class sol(object): def searchMatrix(self, matrix, target): ''' Search the target value in an m*n matrix. The integers in each row are sorted from left to right The first integer is larger than the last integer of previous row. Use global binary search. 66 ms, 12.73%....
705211c543585794c977facbef6c6406f9588d5d
amandanagai/bootcamp_prep
/codewars_rotated_word.py
654
4
4
def num_clockwise_rotated(str1, str2): count = 0 if str1 == str2: return count else: while count < len(str1)-1: str1 = "".join([str1[x] for x in range(1, len(str1))])+str1[0] count += 1 if str1 == str2: return count num_clockwise_rotated("coffee", "eecoff") def nu...
beeea39f7304a2bae86ad21f68cf1ff94cb7c21f
caoxin1988/leetcode
/python/206_Reverse_Linked_List/reverse.py
1,030
3.9375
4
class LinkNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverse(self, head): if head is None or head.next is None: return head ptr = head prev = None while ptr: next_ptr = ptr.next ...
4aea2662412f205c0c1159bbf50a0d91c22e0e3b
KhMassri/DTNWorkspace
/Parser/src/test.py
1,158
3.71875
4
from numpy.random import rand ''' how to build aniterator''' class it: def __init__(self): #start at -1 so that we get 0 when we add 1 below. self.count = -1 #the __iter__ method will be called once by the for loop. #the rest of the magic happens on the object returned by this method. ...
ec260fab891501b13de54196637729a47793a15c
davidpablos25/TareasBecasDigitaliza
/Calculadora.py
2,114
4
4
import math def suma(a,b): return a + b def resta (a,b): return a - b def multiplicacion(a,b): return a*b def division(a,b): return a/b def potencia(x,y): return pow(x, y) def raiz(x): return math.sqrt(x) def logarit(x): return math.log10(x) def menu(): pr...
e30697fdfa7f330e1f3cac2a650e7499dc4161ab
AmandaCasagrande/Entra21
/Exercícios URI/Iniciante/1021.py
1,175
3.859375
4
cedulas = float(input("")) notas100 = int(cedulas / 100) cedulas = cedulas % 100 notas50 = int(cedulas / 50) cedulas = cedulas % 50 notas20 = int(cedulas / 20) cedulas = cedulas % 20 notas10 = int(cedulas / 10) cedulas = cedulas % 10 notas5 = int(cedulas / 5) cedulas = cedulas % 5 notas2 = int(cedulas / 2) cedula...
6efe65031b35a325655c8c80dd5ff15e5f76e315
girishgupta211/algorithms
/find_summer_temparature.py
1,764
4.28125
4
# I've just tried a coding challenge to write a function that returns the length of the shortest possible # left partition of an array of numbers, all of whose elements are less than all of the elements in the corresponding right partition. # # The scenario given was finding the divide between "winter" and "summer" giv...
56a90cb7cf3e2ec9ac92f342c8ea52510577ae2f
yuanhawk/Digital-World
/Python Project/Wk 2 In Class Activities + Homework/Largest Number.py
143
3.96875
4
def is_larger(n1, n2): if n1 > n2: return True else: return False print(is_larger(2, -1)) print(is_larger(-1, 2)) print(is_larger(2, 2))