blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
fc607af81e8f640a2dce4593f55301346b268054 | rubenhortas/python_examples | /native_datatypes/none.py | 759 | 4.53125 | 5 | #!/usr/bin/env python3
# None is a null number
# Comparing None to anything other than None will always return False
# None is the only null number
# It has its own datatype (NoneType)
# You can assign None to any variable, but you can not create other NoneType objects
CTE_NONE1 = None
CTE_NONE2 = None
if __name__ =... |
ecbf9208e923d34affac44d9d1f1737d2b5c38da | rubenhortas/python_examples | /bitwise_operations/bitwise_operations.py | 2,536 | 3.84375 | 4 | #!/usr/bin/env python3
import sys
# Operators:
# a & b AND
# a | b OR
# a ^ b XOR
# ~a NOT
# a << n Left shift
# a >> n Right shift
# Compound operators:
# a &= b -> a = a & b
# a |= b -> a = a | b
# a ^= b -> a = a ^ b
# a <<= n -> a = a << n
# a >>= n -> a = a >> n
# Read the value of a bit on a given pos... |
1e4b9996e3492e6c58c95f3cc0ed12c06237b54e | CheeseC4k3/practicepython | /pythonexercise3.py | 201 | 3.9375 | 4 | #!/bin/python3
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = []
r = int(input("random number"))
#show all numbers in list smaller than input r
for i in a:
if i < r:
b.append(i)
print(b)
|
02b9e622abdf5b4b5e6a8b0c38e91c4a32ea50bb | CheeseC4k3/practicepython | /pythonexercise10.py | 494 | 3.765625 | 4 | #!/bin/python3
import random
#generade two lists of random length containing random ints (cant be duplicates inside one list!)
a = random.sample(range(1, 50), random.randint(10, 40))
b = random.sample(range(1, 50), random.randint(10, 40))
#print lists and length of lists
print("list a contains ", len(a)," integers: ",... |
6fced84e573d8d71cc4e909433a1df0df90f9719 | ajsmash7/Project1DiceGame | /FarkleDiceGame.py | 4,144 | 4.125 | 4 | # Author: Ashley Johnson
# Program: Farkle Dice Game
# This is the main controller. Automated functions of rolls and scoring are in the Turn module.
import Turn
from dataclasses import dataclass
@dataclass
class Player:
name: str
score: int
turn_score: int
turn: bool
file: str
print('''
... |
90e6d217436cf7a44df1f25d26d9357f6c26612d | FlySB/AI-Learning | /SIR_important_node/SIRSpread.py | 1,933 | 3.515625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import random
def CreateER(N, p):
mat = np.random.rand(N, N)
mat = np.where(mat>p, 0, 1)
for i in range(N):
mat[i, i] = 0
mat[i, :] = mat[:, i]
return mat
def Distribution(mat):
(a, b) = mat.shape
Count = np.array([mat[i, :].su... |
d5f513d28706c3879027122668266e579277d87f | CTimmerman/3DHubsHangman | /lib/database.py | 844 | 3.75 | 4 | import sqlite3, time
class Database:
def __init__(self, db_file=':memory:'):
""" create a database connection to a SQLite database """
self.con = sqlite3.connect(db_file)
print(sqlite3.version)
cur = self.con.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS scores (
score integer NOT NUL... |
03a3b5dc2e270f2142cc6ba674e643ef9f8c9922 | seymaerkul/deneme | /filmKatalogu.py | 2,052 | 3.78125 | 4 | filmler={"kara korsanın laneti":{"yapım yılı":1957,"imdb":8.2,"tür":"korku"},"sinegin intikamı":{"yapım yılı":1945,"imdb":9.2,"tür":"korku"}}
#print(filmler)
def filmEkle():
filmAdı=input("film adı gir")
global filmler
if filmAdı:
yapım_yılı=input("yapım yılı gir")
imdb=input("imdb")
... |
f8c6cceeafe5526f617b1978d6d50105e9068c2b | GeorgiyX/lab_3 | /lab_3/librip/decorators.py | 1,080 | 4.09375 | 4 | # Здесь необходимо реализовать декоратор, print_result который принимает на вход функцию,
# вызывает её, печатает в консоль имя функции, печатает результат и возвращает значение
# Если функция вернула список (list), то значения должны выводиться в столбик
# Если функция вернула словарь (dict), то ключи и значения до... |
87f9a870fcfc343f1581fb8fdff39c9e4e807a3d | Omeljan/checkio.org | /Elementary/Correct_Sentence.py | 1,150 | 4.03125 | 4 | '''
For the input of your function, you will be given one sentence. You have to return a corrected version, that starts with a capital letter and ends with a period (dot).
Pay attention to the fact that not all of the fixes are necessary. If a sentence already ends with a period (dot), then adding another one will be ... |
eb95b73e72cc859bb4cc146ffa620e5246870921 | Benjamin7991/My-Code-Wars-Solutions | /6KYU/MexicanWave.py | 182 | 3.71875 | 4 | def wave(people):
list = []
for i in range(len(people)):
if people[i] != " ":
list.append(people[:i] + people[i].upper() + people[i+1:])
return list
|
d1230ed1aad337d8368d57930f1ac8ac85525861 | Benjamin7991/My-Code-Wars-Solutions | /6KYU/YourOrderPlease.py | 324 | 3.703125 | 4 | def order(sentence):
result = []
list = []
for char in sentence:
if char.isnumeric():
list.append(char)
sentence = sentence.split()
diction = dict(zip(list,sentence))
od = sorted(diction.items())
for item in od:
result.append(item[1])
return ' '.join(resu... |
e53f0871a479fe7577121cd5f77b8425e760e517 | Benjamin7991/My-Code-Wars-Solutions | /7KYU/Automorphic_number.py | 118 | 3.515625 | 4 | def automorphic(n):
squared = n**2
if str(n) in str(squared):
return 'Automorphic'
return 'Not!!'
|
4e1204b7794b877823a46db52e266f8a8c19dc98 | Benjamin7991/My-Code-Wars-Solutions | /6KYU/Count_chars_in_your_string.py | 176 | 3.984375 | 4 | def count(string):
dict = {}
for char in string:
if char not in dict:
dict[char] = 1
else:
dict[char] += 1
return dict
|
11b361754c85d49acc34df5ee8192fa81031a798 | Benjamin7991/My-Code-Wars-Solutions | /5KYU/Blackjack_Scorer.py | 377 | 3.6875 | 4 | def score_hand(cards):
hand = []
for item in cards:
if item.isnumeric():
hand.append(int(item))
if item == 'J' or item == 'Q' or item == 'K':
hand.append(10)
if item == 'A':
hand.append(11)
while sum(hand) > 21 and 11 in hand:
han... |
98e438a29d4eb7c7e5197312c798f2609fc88136 | Benjamin7991/My-Code-Wars-Solutions | /7KYU/Strong_Number.py | 383 | 3.859375 | 4 | def strong_num(number):
digits = [x for x in str(number)]
l = []
factorial = 1
for digit in digits:
factorial = 1
#if int(n) >= 1:
for i in range (1,int(digit)+1):
factorial = factorial * i
l.append(factorial)
if sum(l) == number:
... |
70826c9a98ac73a26f86c1c733334065ced4a325 | Benjamin7991/My-Code-Wars-Solutions | /7KYU/PrinterErros.py | 302 | 3.765625 | 4 | def printer_error(s):
range = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]
errors = int()
denominator = len(s)
for letters in s:
if letters not in range:
errors += 1
else:
pass
return str(errors) + "/" + str(denominator)
|
11cc8fdcc71692674eeba8ca8ba4e979b1917f3c | Benjamin7991/My-Code-Wars-Solutions | /7KYU/Sum-Sqaure_even_Root_odd.py | 124 | 3.859375 | 4 | import math
def sum_square_even_root_odd(nums):
return round(sum([x**2 if x %2 ==0 else math.sqrt(x) for x in nums]),2)
|
88b370381ec90cbf4d3c69c315443ad2087c89ed | Benjamin7991/My-Code-Wars-Solutions | /7KYU/Start_with_a_Vowel.py | 384 | 3.734375 | 4 | def vowel_start(st):
chars = '?_,.!@#$%^&*()\'-{}""[]/\<>;:`~|=+'
vowels = ['a', 'e', 'i', 'o', 'u']
test = ''.join([x for x in st.split()])
result = ''
for char in test.lower():
if char in vowels:
result += ' ' + char
else:
result += char
return... |
0a24777b66a89e7bd905811b4b5a933d10429e00 | Kerbx/tpt | /Scripts/boolean/boolean38.py | 192 | 3.65625 | 4 | # boolean38 Прохоренков ИСП-211
x = int(input())
y = int(input())
x1 = int(input())
y1 = int(input())
if abs(x - x1) == abs(y - y1):
print('True.')
else:
print('False.') |
5575d934a4fa0f599eb87be4d7331c8b47ba8669 | Kerbx/tpt | /Scripts/begin/begin8.py | 151 | 3.578125 | 4 | # Begin1 Прохоренков ИСП-211
a = float(input())
b = float(input())
print(f'Среднее арифметическое = {(a + b) / 2}') |
5a2d791d37b6dac0fa7e09556189f2fae68d2939 | Kerbx/tpt | /Scripts/boolean/boolean17.py | 149 | 3.609375 | 4 | # boolean17 Прохоренков ИСП-211
a = input()
if len(a) == 3 and int(a) % 2 != 0:
print('Истина.')
else:
print('Ложь.') |
0e8244629ebf768ab09981e4cc5df61062ae2784 | Kerbx/tpt | /Scripts/if/if11.py | 143 | 3.546875 | 4 | # if11 Прохоренков Егор ИСП-211
a = int(input())
b = int(input())
if a != b:
a, b = max(a, b), max(a, b)
elif a == b:
a, b = 0, 0
print(a, b) |
0310253afad93229826b91aa3c57b2eb09ca99ab | IliesChibane/H4ckT0b3rF3st-2k21 | /projects/Save_The_Princess_Bot/SaveThePrincess.py | 2,432 | 3.84375 | 4 | from initialization.UI import start
from initialization.PrincessPosition import PrincessPositionGen
# Princess contains the position of the princess in the grid
# i contains a value necessary for the UI don't worry about it
i, Princess = PrincessPositionGen()
#Knight contains the initial position of the knig... |
811ec6dcf1a872f58e8189e103ab1fa618857a65 | IliesChibane/H4ckT0b3rF3st-2k21 | /your_projects/Matrix calculator_Rayssy/Matrix calculator.py | 371 | 3.515625 | 4 | Ma = [[2,2],[1,3]]
Mb = [[1,2],[4,8]]
C = []
def product(A,B):
for i in range(0,len(A)):
for j in range(0,len(A)):
c1 = A[i][j] + B[j][i]
C.append(c1)
print(C)
return
def inverse(M):
det = M[0][0]*M[1][1]-M[0][1]*M[1][0]
I = [[M[1][1]/det,-M[0][1]/det],[-M[1][0]/det,M[0][0]/det]]... |
205b9972f8ed48656efbd28bf565b42235454692 | IliesChibane/H4ckT0b3rF3st-2k21 | /your_projects/allaeddineomc_tic-tac-toe/src/main.py | 9,119 | 4.09375 | 4 | #! "/usr/bin/python3"
#imports needed by some functions to work
import random
#just reference for the names and position of the 9 slots of the tic-tac-toe matrix
'''
a b c
d e f
g h i
'''
# the slot class is not very different from the string class but it allows only some specific values to be inserted
class slot():... |
91b1daef899430a9a9845929c4c9546664f86825 | saeedehmoghadam/exam-3 | /snake.py | 239 | 3.859375 | 4 | import random
lenghth_snake = (int(input("enter your number for lenghth snake :")))
for i in range( lenghth_snake):
if i % 2 == 0:
print ("*" , end ='')
else :
print ("!" ,end='')
|
1c7ae764060927e1fa2898e7964946b76603aa05 | sijokappen/ML | /MLMedicals/Tests.py | 2,314 | 4 | 4 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, Optional
class Handler(ABC):
"""
The Handler interface declares a method for building the chain of handlers.
It also declares a method for executing a request.
"""
@abstractmethod
def set_next(self,... |
b4642af405871a89e0e22fc7a93763896ad1c240 | EngageTrooper/Basic_Calculator_Python | /Calculator_Fle.py | 820 | 4.15625 | 4 | def add(num1,num2):
return num1 + num2
def subtract(num1,num2):
return num1 - num2
def multiply(num1,num2):
return num1 * num2
def divide(num1,num2):
return num1 / num2
print("Please Select Operation -\n" \
"1.Add \n" \
"2.Subtract \n" \
"3.Multiply \n" \
"4.Divide \n" )
select = in... |
9f3ebc4c86962cd2de05ca1612ed57e6bf0dab35 | cbradshaw11/PythonTools | /TechInterviews/MergeSort2.py | 509 | 3.734375 | 4 | array = [2,5,1,9,7,16,25]
def mergesort(l):
if len(l) == 1:
return
mid = int(len(l)/2)
left = l[:mid]
right = l[mid:]
mergesort(left)
mergesort(right)
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] > right[j]:
l[k] = left[i]
i+=1
else:
l[k] = right[j... |
8bbc2665619e9220f2b79aba29a1cefd27bd67a1 | cbradshaw11/PythonTools | /TechInterviews/QuickSort.py | 495 | 3.8125 | 4 |
def partition(arr, low, high):
pivot = arr[high]
pi = low
for i in range(low, high):
if arr[i] > pivot:
arr[pi], arr[i] = arr[i], arr[pi]
pi += 1
arr[pi], arr[high] = arr[high], arr[pi]
return pi
def quicksort(arr, low, high):
if len(arr) < 2:
return
if low >= high:
retu... |
8f1f5be13a5789a67be0d28eb9882430aa70979e | cbradshaw11/PythonTools | /TechInterviews/StringManip.py | 125 | 3.703125 | 4 | def manip(s):
s = "hello world"
print(s)
def manip2(s):
s = s+"hello"
print(s)
s = "hi"
print(s)
manip2(s)
print(s)
|
4ef9e33cf91abe9be008a745f46268ae6cedbf83 | namsam429/PythonExcercisesCS466D | /InBangNhan2.py | 260 | 3.5625 | 4 | s = ""
for i in range(1,11):
for x in range(2,6):
s += str(x) + " x " + str(i) + " = " + str(x*i) + "\t"
s = s + "\n"
s = s + "\n"
for i in range(1,11):
for x in range(6,10):
s += str(x) + " x " + str(i) + " = " + str(x*i) + "\t"
s = s + "\n"
print(s)
|
fe9c72edc1c65aa45176f569134bc14e2fe89e83 | QuinnLee/project_euler | /euler035.py | 935 | 3.6875 | 4 | '''
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
'''
from itertools import permutations
fro... |
4bed6b43fdb8d6664dad44ff0cf64337dbf7f040 | QuinnLee/project_euler | /euler052.py | 693 | 3.703125 | 4 | '''
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
'''
from collections import Counter
if __name__ == "__main__":
for i in range(1, 10**9)... |
ef6054bc8634345e4dbf0647f5e4b1bf0c1e6fcb | QuinnLee/project_euler | /euler040.py | 848 | 3.890625 | 4 | '''
An irrational decimal fraction is created by concatenating the positive integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of the following expression.
d1 × d10 × d100 × d1000 × d... |
5afc31693650400f83732fa599cb914cc41128e1 | QuinnLee/project_euler | /euler032.py | 1,589 | 3.859375 | 4 | '''
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.
Fin... |
3705caac30d02e219fefddf6bb895055781faa1d | QuinnLee/project_euler | /euler047.py | 1,030 | 3.671875 | 4 | '''
The first two consecutive numbers to have two distinct prime factors are:
14 = 2 × 7
15 = 3 × 5
The first three consecutive numbers to have three distinct prime factors are:
644 = 2² × 7 × 23
645 = 3 × 5 × 43
646 = 2 × 17 × 19.
Find the first four consecutive integers to have four distinct... |
1a01e322557f851cc7ca77ba487cf006402dde19 | r-suresh-kumar/Udacity-MatrixClass | /matrix.py | 426 | 3.859375 | 4 | import math
from math import sqrt
import numbers
def zeroes(height, width):
"""
Creates a matrix of zeroes.
"""
g = [[0.0 for _ in range(width)] for __ in range(height)]
return Matrix(g)
def identity(n):
"""
Creates a n x n identity matrix.
"""
... |
143ac1418d9b9839c16858a1930f91e297f39d2a | KevinT02/MainProgram | /student.py | 1,700 | 3.84375 | 4 | from base64 import b64encode
from user import User
class Student(User):
'''
An account object that hold the information of the user: full name, username, password
Attributes
-----------
name: str
The name of the user of the account
username: str
The username of the student acc... |
bc58264b283fba5b14d04ed9209f4b1c88426820 | secf4ult/CS50 | /pset6/credit/credit.py | 853 | 3.984375 | 4 | from cs50 import get_string
# prompt user for credit card number
while True:
n = get_string("Number: ")
if (float(n) > 0):
break
# calculate the checksum
checksum = 0
# the most significant number's index
index = len(n)
for c in n:
# string to int
c = int(c)
# for even position
if (in... |
adf3040108af6a841a7537701db5e2bfecedea73 | jainhimani1999/adhocIntern | /problem-6.py | 623 | 3.515625 | 4 | #for cat command
file = open("file.txt", "r")
#print(file.read())
#for cat -E command
for line in file:
print(line.strip() + "$")
#for cat -n command
count = 1
for line in file:
print(str(count)+line.strip())
count+=1
#for output redirection cat file > file1
location = input('Enter the fil... |
697f5a40fc6b60fc5690d8016b770ed911d40448 | jainhimani1999/adhocIntern | /problem-1.py | 172 | 3.671875 | 4 | import datetime
k=input('Enter your name')
l = int(input('Enter your age'))
now = datetime.datetime.now()
print(k +'will turn 95 by the year :'+ str((95-l)+now.year))
|
2443b451b346e76b351d0b1918ba1efef1fb2e1f | ProTrickstar/Simple_Distribution-C-110 | /temp.py | 623 | 3.6875 | 4 | from os import name
import statistics
import pandas as pd
import plotly.figure_factory as ff
import csv
import random
import plotly.graph_objects as go
df = pd.read_csv("newdata.csv")
data = df["temp"].tolist()
population_mean = statistics.mean(data)
std_deviation = statistics.stdev(data)
print("Population... |
f86482889f39d990b99cd3ccb066a332e34eaf32 | pillofoos/Ejemplos | /TomaDecisiones.py | 636 | 4.1875 | 4 | #Archivo: TomaDecisiones.py
#Descripcion: Ejemplo en el que se muestra la utilizacion de la sentencia if, if..else, if..elif..else
# la funcion input y la utilizacion del depurador (antes y despues de conversion)
antiguedad = (int)(input("Ingrese la antiguedad en años:"))
if antiguedad > 5:
print("Le c... |
46e1e115113fe50a4b168ec40efa3b963aeadb12 | SidSoft/rosalind | /lgis/lgis.py | 2,634 | 3.921875 | 4 | """
Longest Increasing Subsequence
A subsequence of a permutation is a collection of elements of the permutation in the order that they appear. For example, (5, 3, 4) is a subsequence of (5, 1, 3, 4, 2).
A subsequence is increasing if the elements of the subsequence increase, and decreasing if the elements decrease. F... |
f13a20ded6c945ff809a8e466776420242fdc35e | sasazlat/UdacitySolution-ITSDC | /Matrices/5_matrix_transpose.py | 4,187 | 4.4375 | 4 |
# coding: utf-8
# # Transpose of a Matrix
#
# In this set of exercises, you will work with the transpose of a matrix.
#
# Your first task is to write a funciton that takes the transpose of a matrix.
# Think about how to use nested for loops efficiently.
#
# The second task will be to write a new matrix multiplication... |
19b5fe9fe18d1f1ebb7967dea569eb86361b827e | sasazlat/UdacitySolution-ITSDC | /computer_vision/project/Traffic_Light_Classifier.py | 26,855 | 3.921875 | 4 |
# coding: utf-8
# # Traffic Light Classifier
# ---
#
# In this project, you’ll use your knowledge of computer vision techniques to
# build a classifier for images of traffic lights! You'll be given a dataset
# of traffic light images in which one of three lights is illuminated: red,
# yellow, or green.
#
# In this n... |
7578527e9e65c2b8046f348e0d97b5ac3b723bdb | sasazlat/UdacitySolution-ITSDC | /PprobabilityDistribution/discrete_probability_exercise.py | 6,717 | 4.53125 | 5 |
# coding: utf-8
# # Discrete Probability Exercise
#
# You have two dice. These are fair, six-sided dice with the values one
# through six.
#
# You take the dice, and you roll them. Then you take the sum of the two
# numbers. For example, if you roll the dice and get 5 and 4, then the sum
# would be 9.
#
#
# ![alt ... |
a6e3069a5aee2db758dc6fb7d1230307f09e6742 | sasazlat/UdacitySolution-ITSDC | /Matrices/2_matrices_in_python.py | 4,969 | 4.75 | 5 |
# coding: utf-8
# ## Coding Matrices
#
# Here are a few exercises to get you started with coding matrices. The
# exercises start off with vectors and then get more challenging
#
# ### Vectors
# In[ ]:
### TODO: Assign the vector <5, 10, 2, 6, 1> to the variable v
v = [5,10,2,6,1]
# The v variable contains a Pyt... |
3f194d29c829ac5f28018cc17d02ed81f1eb7f94 | sasazlat/UdacitySolution-ITSDC | /PprobabilityDistribution/8_central_limit_theorem_demo.py | 18,600 | 3.984375 | 4 |
# coding: utf-8
# # The Central Limit Theorem and Continuous Probability Distributions
#
# Run the code in each of the cells below. Since this is a demonstration, you
# do not need to add any code.
#
# You have an understanding of discrete probability distributions and how they
# apply to self-driving cars. Now you... |
0b01bedb1b179940d4628e2aed6191556410accd | sasazlat/UdacitySolution-ITSDC | /PprobabilityDistribution/7_2D_selfdrivingcar.py | 5,241 | 4.1875 | 4 |
# coding: utf-8
# # Self Driving Car 2D World
#
# In the code cell, you'll find skeleton code for a class called
# SelfDrivingCar.
#
#
# The SelfDrivingCar class is initialized with the number of rows and number of
# columns in a 2D grid.
#
# The class also contains four methods. You will need to implement these thr... |
3ecc605cb1db65fa88a0c5015cb5b6cb01c0e92a | linchpindyk/dice-statistic | /rolling-dice.py | 786 | 3.765625 | 4 | from __future__ import division
import random
import numpy
from collections import Counter
def roll_dice():
return random.randrange(1,7)
def get_probability(num_repeat):
array = []
for x in range(int(num_repeat)):
rolled_number = roll_dice()
array.append(rolled_number)
statistic = Cou... |
db0d7bb3f334022dfd4e2aa6e9df901954253958 | zhenghaoyang/PythonCode | /ex29.py | 580 | 4.03125 | 4 | # --coding: utf-8 --
people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs:
print "The world is dry!"
dogs += 5
if people >= dogs:
... |
8f7e68843db46063d1ea23e20f305fda2408d991 | zhenghaoyang/PythonCode | /ex15.py | 1,317 | 4.15625 | 4 | # --coding: utf-8 --
#从sys模块导入argv
from sys import argv
#用户输入参数解包
script,filename = argv
#打开文件,赋值给txt
txt = open(filename)
#打印出文件名
print "Here's your file %r:"%filename
#打印出txt变量读取文件的文本
#txt.close()
print txt.read()
txt.close()
print "Type the filename again:"
#读取用户输入的参数
file_again = raw_input(">")
#读取用户输入的文件名,读取其中的文本,... |
bc5941753aae47ac87167e1c0b4df45829ec6070 | feixiao5566/Py_Rabbic | /animal/animal.py | 463 | 3.5 | 4 | #!/usr/bin/env python
# encoding: utf-8
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
def run(self):
print('Dog is running...')
class Cat(Animal):
def run(self):
print('cat is running...')
dog = Dog()
dog.run()
cat = Cat()
cat.run()
a = l... |
dd78ad850cee3b8e3b42da655cfedc5864231dd8 | feixiao5566/Py_Rabbic | /higher_order/map_reduce.py | 1,008 | 3.78125 | 4 | #!/usr/bin/env python
# encoding: utf-8
def f(x):
return x*x
r = map(f,[1,2,3,4,5,6,7,8,9])
print(list(r))
#map()函数接收两个参数,一个是函数,一个是Iterable
#map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回
L=[]
for n in [1,2,3,4,5,6,7,8,9]:
L.append(f(n))
print(L)
#等同于这个,但是没有第一个更清晰看明用意
print(list(map(str,[1,2,3,4,5,6,7,8,9])))
#把字符转成... |
b69297a4739a27198855e9478fb43b65c4cf2586 | zyro-mixed-bag/algorithms-python | /BinarySearchTree.py | 5,114 | 3.71875 | 4 | class nodeObj:
def __init__(self,value, left = None, right = None, parent = None):
self.value = value
self.left = left
self.right = right
self.parent = parent
def buildBST(A):
root = nodeObj(A[0])
for element in A[1:]:
root = insertNode(root, nodeObj(elemen... |
cd22aa8ee2bc1ba44c8af3f5bd7d880c7edac4eb | krishnavetthi/Python | /hello.py | 817 | 4.5 | 4 | message = "Hello World"
print(message)
# In a certain encrypted message which has information about the location(area, city),
# the characters are jumbled such that first character of the first word is followed by the first character of the second word,
# then it is followed by second character of the first word and... |
f3684d854c99ce8cf5630b38c06978384a7a71bc | sanketpathak64/Data-Structures-and-Algorithms | /sorting/radixsort.py | 734 | 3.6875 | 4 | def countSort(arr,exp):
n=len(arr)
output=[0]*n
count=[0]*10
for i in range(n):
index=(arr[i]//exp)%10
count[index]+=1
print(count)
for i in range(1,10):
count[i]+=count[i-1]
print(count)
i=n-1
while(i>=0):
index=(arr[i]//exp)%10
print("index: ... |
6f1d632e84962fef1e601440b2ad5624b4ad97d5 | matiasvinicius/Algoritmos | /Code/04d_heap_sort.py | 1,165 | 3.859375 | 4 | """
A = uma lista
i_pai = índice do "nó" pai (posição no arranjo)
n_heap = comprimento da lista
Verifica se o nó pai é maior que os filhos (esq e dir)
Se for menor, realiza a troca e chama recursivamente para o novo pai
"""
def refazer_heap_max(A, i_pai, n_heap):
esq = 2*i_pai + 1
dir = 2*i_pai + 2
if esq... |
490ec2521537384c618938b9a39cfd375c818686 | matiasvinicius/Algoritmos | /Code/04a_ordenacao_basica.py | 1,632 | 3.765625 | 4 | def insertion_sort(A):
end = len(A)
i = 0
j = 0
while i < end:
value = A[i]
j = i
while j>0 and A[j-1] > value:
A[j] = A[j-1]
j = j-1
A[j] = value
i += 1
return A
def insertion_sort_rec(A, n):
if n == 1: return
insertio... |
e9b3fa0dc7b98118bc2ee972483463684eb53255 | fmrigueiro/MathQuestionTagging | /python_scripts/find_keywords_in_text.py | 2,393 | 3.890625 | 4 | """
This script scans through each question's text and looks for keywords found within the text.
If a keyword is made up of several words, it counts the keyword if each individual word
is found within the text
@author Luigi Patruno
@date 15 April 2015
"""
import pandas as pd
from time import time
def main():
... |
bfffd6fa58039eb9813f7b93f0f1aab13fbc2fc7 | justgolikeme/My_MachineLearning | /the_use_Numpy/the_exam_Numpy/num_1.py | 6,239 | 3.53125 | 4 | # -*- coding:utf-8 -*-
__author__ = 'Mr.Lin'
__date__ = '2019/11/13 15:58'
"""
1 Import the numpy package under the name `np`
通用引用别名‘np’导入numpy包
"""
import numpy as np
"""
#### 2. Print the numpy version and the configuration (★☆☆)
打印numpy的版本以及配置
"""
print("numpy 版本")
print(np.__version__)
print("numpy 配置")... |
15eaa88d003f3d9768e96e0f170532447a4ea7dc | tooget/Self-Study-Leetcode-Archive | /1.two-sum.py | 1,234 | 3.578125 | 4 | # [1] Two Sum
# https://leetcode.com/problems/two-sum/description/
# * algorithms
# * Easy (44.90%)
# * Source Code: 1.two-sum.0.py
# * Total Accepted: 2.4M
# * Total Submissions: 5.4M
# * Testcase Example: '[2,7,11,15]\n9'
# Given an array of integers, return indices of the two numbers such that they ad... |
f82381434d82e1a418dca7fa546122a1ca627408 | SweetyShukla/Deep-Learning-A-Z | /ann.py | 5,693 | 3.5625 | 4 | # Artificial Neural Network
# Installing Theano
# pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
# Installing Tensorflow
# pip install tensorflow
# Installing Keras
# pip install --upgrade keras
# Part 1 - Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyp... |
1ecb86e88978b39cd7d1ac4c83ad36363b21600d | sknaht/algorithm | /python/string/Substring with Concatenation of All Words.py | 1,356 | 3.703125 | 4 | """
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
For example, given:
s: "barfoothefoobarman"
words: ["foo", "bar"]
You should re... |
590c47acb063f6a9e15144db530970d98c2ee357 | sknaht/algorithm | /python1/leetcode/310-minimum-height-trees.py | 876 | 3.59375 | 4 | class Solution(object):
def findMinHeightTrees(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: List[int]
"""
graph = {i : set() for i in xrange(n)}
degree = {i : 0 for i in xrange(n)}
for s, e in edges:
graph[s].add(... |
a2796c635a21f7febed83fb97f94a21d18bd2214 | sknaht/algorithm | /python1/leetcode/304-range-sum-query-2d-immutable.py | 1,169 | 3.515625 | 4 | class NumMatrix(object):
def __init__(self, matrix):
"""
initialize your data structure here.
:type matrix: List[List[int]]
"""
if not matrix:
self.s = [0]
else:
s = [[0] * (len(matrix[0]) +1) for i in xrange(len(matrix) + 1)]
... |
852194126de9eed2729893a6e66a78005fb95b06 | sknaht/algorithm | /python1/binary-search-tree.py | 3,225 | 3.78125 | 4 | class TreeNode(object):
def __init__(self, key, val):
self.key, self.val, self.right, self.left = key, val, None, None
class BSTree(object):
def __init__(self):
self.root = None
def __delete_min(self, node):
if not node.left:
return node.right
node.left = sel... |
53dc717faf5a263745de570604771901897bfae4 | sknaht/algorithm | /python/other/Maximum Product Subarray.py | 553 | 4.0625 | 4 | """
ind the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
"""
class Solution:
# @param {integer[]} nums
# @return {integer}
def maxProduct(self, nums):... |
4a5ab7196046ee86a307596673b4b15aea94fffa | sknaht/algorithm | /python/sort/merge-k-sorted-lists.py | 1,352 | 3.921875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, repr(sel... |
b3e75865a9fd80dff8126a5ba0e5a9ad89303104 | sknaht/algorithm | /python/bfs/Surrounded-Regions.py | 1,731 | 3.828125 | 4 | """
Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
For example,
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
"""
class Solution:
... |
fb9f4bbb1eb4957e34f84b0a006afb85606c2535 | Joseph-Zapata/actividad-producto-desempe-o | /punto2.py | 242 | 4.0625 | 4 | #Escribir una función que cuente la cantidad de apariciones de cada carácter en una cadena de texto, y los devuelva en un diccionario.
cadena = input("Escriba su frase: ")
dic = {x:cadena.count(x) for x in cadena}
print(dic)
# Joseph Zapata Piedrahita |
4677210d36d49332179918fc33fa365e65f16744 | Sunethan/APD-analyser | /plugin/Cacher.py | 1,489 | 3.828125 | 4 | # 快取器類別
class Cacher:
def __init__(self):
self.computed = False
self.data = None
def save(self, data):
# 把資料存到記憶體中,這邊你也可以自行實作把資料存到硬碟
# !目前版本不會檢查輸入,理論上輸入不同應該要重新算一次
print("save data to cache")
self.data = data
self.computed = True
def read(self):
... |
8d3b1c37477cd499fd19db3512c344bc2e3c4f2f | dubblin27/pythonfordatascience | /Movie_recommendation_adv.py | 4,630 | 3.546875 | 4 | #colloborative filtering will be used
# model based CF using singular value Decomposition and
# Memeory based Decomposition by cosine simularity
from math import sqrt
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split... |
4084a64ffe7d52b14cb8b756e1efe29d46730493 | MichaelKirkaldyV/mean-deploy-2 | /python_stack/python_OOP/arithmetic_module/main.py | 313 | 3.71875 | 4 | #imports arithmetic module within the same folder.
#Then uses the module as a variable and calls its functions using the .method
#Adds parameters.
#prints out the solutions that each function returns.
import arithmetic
print arithmetic.add(5, 8)
print arithmetic.subtract(10, 5)
print arithmetic.multiply(12, 6)
|
bac35ce6161287aca9e03ea210f0c59e8068f312 | mustafaPipaliya/python | /temp.py | 524 | 3.734375 | 4 | # total_sum = 0
# n = 1
# while total_sum < 200:
# previous_sum = total_sum #140 n = 7
# total_sum += n ** 2 #204 n = 8
# if total_sum > 200:
# total_sum = previous_sum
# n -= 1
# break
# n += 1
# print(f"Total Summation : {total_sum} at n = {n}")
total_... |
4c6728ff5df9411e3ef61b953cc268cd93fc55d1 | HristoAleksiev/turtle-crossing-game | /score.py | 1,483 | 3.9375 | 4 | import math
from turtle import Turtle
class ScoreBoard(Turtle):
def __init__(self):
super().__init__()
self.game_level = 1
self.penup()
self.hideturtle()
self.color("black")
self.display_level()
self.draw_finish_line()
def display_level(self):
... |
c41bdf84fe7069299f822e6d27bf4c52493d2dff | shrinidhi99/tkinter-app | /src/messagebox.py | 297 | 3.96875 | 4 | from tkinter import *
import tkinter.messagebox
root = Tk()
tkinter.messagebox.showinfo('Window Title', 'Humans can live upto 120 years.')
answer = tkinter.messagebox.askquestion('Question 1', 'Do you like me?')
if answer == 'yes':
print(' : ) ')
else:
print(' : ( ')
root.mainloop() |
f4fad1000ed28895c819b3bc71a98e7a9f3e87b6 | ofreshy/interviews | /hackerrank/medium/merge_the_tools.py | 2,042 | 4.46875 | 4 | """
Consider the following:
A string,
, of length where
.
An integer,
, where is a factor of
.
We can split
into substrings where each subtring, , consists of a contiguous block of characters in . Then, use each to create string
such that:
The characters in
are a subsequence of the characters in
.
An... |
06f8cf70cd26e9c71b989fcb63f7525fb4fc3fff | ofreshy/interviews | /interviewcake/apple_stock.py | 2,451 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Suppose we could access yesterday's stock prices as a list, where:
The values are the price in dollars of Apple stock.
A higher index indicates a later time.
So if the stock cost $500 at 10:30am and $550 at 11:00am, then:
stock_prices_yesterday[60] = 500
Write an efficient funct... |
0fe0c0821c74097f3a0875f6a48e9559ee062b38 | ofreshy/interviews | /fabfitfun/name_count_order.py | 607 | 3.953125 | 4 |
from collections import defaultdict
from operator import itemgetter
def order(names):
"""
Iterable of names
:param names: list of names
:return: the name that happens most frequently in the list. If there is a tie, name with highest lexical order
"""
names_dict = defaultdict(int)
for name... |
4ec19a0fba6806230acc2db598c789ff817e3045 | ofreshy/interviews | /edabit/expert/mine_sweeper.py | 2,806 | 3.78125 | 4 | """
This challenge is based on the game Minesweeper.
Create a function that takes a grid of # and -,
where each hash (#) represents a mine and each dash (-) represents a mine-free spot.
Return a list where each dash is replaced by a digit indicating
the number of mines immediately adjacent to the spot (horizontally, ... |
99b64fadb7a03719f434fdc299025cb1e2412118 | ofreshy/interviews | /zalando/ships_v1.py | 2,859 | 3.90625 | 4 | # you can write to stdout for debugging purposes, e.g.
# print "this is a debug message"
class Board(object):
"""
Board is a mutable object where each coordinate is a key
and the value is bool representing whether it was hit or not
"""
@classmethod
def from_n(cls, n):
"""
Crea... |
7ddd97ed6cc317d4fdf9fc1731d8425d2eb3b6a4 | gunjan-madan/Namith | /Module4/1.3.py | 915 | 4.40625 | 4 | #Real Life Problems
'''Task 1: Delivery Charges'''
print("***** Task 1: *****")
print()
# Create a program that takes the following input from the user:
# - The total number of sand sack and cement sack
# - Weight of each sack [Hint: use for loop to get the weight]
# - Use a variable to which the weight of the sack... |
c8b8060d5aeb1374f0ef0bb89f436884e1b32748 | gunjan-madan/Namith | /Module2/3.1.py | 1,328 | 4.71875 | 5 | # In the previous lesson, you used if-elif-else statements to create a menu based program.
# Now let us take a look at using nested if-elif statements in creating menu based programs.
'''Task 1: Nested If-else'''
print()
print("*** Task 1: ***")
print()
#Make a variable like winning_number and assign any number to it b... |
552c0f6239df522b27684179f216efe7b10a7037 | gunjan-madan/Namith | /Module2/1.3.py | 1,705 | 4.21875 | 4 | # You used the if elif statement to handle multiple conditions.
# What if you have 10 conditions to evaluate? Will you write 10 if..elif statements?
# Is it possible to check for more than one condition in a single if statement or elif statement?
# Let's check it out
"""-----------Task 1: All in One ------------... |
2116556259168b1b86ede0903cb447ae8fb0a479 | git-gagan/complex--number-calculator | /code.py | 1,860 | 3.515625 | 4 | # --------------
import math
class complex_numbers:
def __init__(self,r,i):
self.real=r
self.imag=i
def __repr__(self):
if self.real == 0.0 and self.imag == 0.0:
return "0.00"
if self.real == 0:
return "%.2fi" % self.imag
if self.imag... |
f36fd365929003b92229a08a013b4cf1af4cc5bd | NasserAbuchaibe/holbertonschool-web_back_end | /0x00-python_variable_annotations/1-concat.py | 383 | 4.21875 | 4 | #!/usr/bin/env python3
"""Write a type-annotated function concat that takes a string str1 and a
string str2 as arguments and returns a concatenated string
"""
def concat(str1: str, str2: str) -> str:
"""[Concat two str]
Args:
str1 (str): [string 1]
str2 (str): [string 2]
Returns:
... |
aed951b7be8ea0190cdbb2b8f431300c16b21ffd | mryklis/IS211_Assignment13 | /test.py | 239 | 3.796875 | 4 | import sqlite3
DATABASE = 'hw13.db'
conn = sqlite3.connect(DATABASE)
c = conn.cursor()
c.execute('''insert into STUDENTS (FIRSTNAME, LASTNAME) values ('f','l')''')
conn.commit()
c.execute('''select * from STUDENTS''')
print c.fetchall() |
fbfc8f6e250907a6db3cf55b9a722b4738942b1b | jcprimo/python-training | /weather/City/city.py | 1,008 | 3.9375 | 4 |
class City:
def __init__(self, name, temp, lat, lon, timezone):
self.name = name
self.temp = temp
self.lat = lat
self.lon = lon
self.timezone = timezone
def print_info(self):
print("Name => ", self.name, " Temperature = ", self.temp, " In celsius = ", self.conv... |
0750b18a8b2f0d235b638130811bb6cc4f19c9ce | jcprimo/python-training | /hanoi/towers_manipulation.py | 2,627 | 3.921875 | 4 | import time
def create_no_ring_hanoi_tower(size):
res_tower = []
for i in range(size):
res_tower.append(0)
return res_tower
def search_ring(ring_id, towers):
nb_towers = len(towers)
towers_height = len(towers[0])
chosen_ring = ring_id
while True:
try:
if chos... |
b1daed49251f323bed4a3bb7d09314ced236fc57 | deadwalker010/Crashpoint1 | /Wheel_of_fortune/Wheel_of_fortune.pyde | 4,642 | 3.5 | 4 | import math
from time import sleep
add_library("sound")
totalWidth = 1000
totalHeight = 1000
circleX = totalWidth // 2
circleY = totalHeight // 2
circleDist = 0 # this will be defined outside of the functions so we can use this variable globally
outerCircleRadius = (circleX + circleY) // 2 - 60
innerCircleRadius = 7... |
a0e97bf1099add7ff626c888a7cb6fe981314777 | Lionelding/EfficientPython | /3_ClassAndInheritance/25_Always_Use_super_for_Inheritance.py | 1,121 | 3.65625 | 4 | # Item 25: Always Use super to Inherit the parent class
'''
1. Method Resolution Order --> __class__.mro()
2. Using super().__init__ and MRO resolve the diamond inheritance issue
'''
# `Diamond Inheritance Issue`
'''
self.value is reset back to 5
'''
from pprint import pprint
class MyBaseClass(object):
def __init__... |
86c3101fdbefa2f974984837cb491a2c62499e7d | Lionelding/EfficientPython | /ConcurrencyAndParallelism/40_Corountines.py | 3,561 | 3.53125 | 4 | # Item 40: Corountines
"""
1. yield == iteractively return + receive
2. Within a generator, the value of the yeild expression will
be whatever value was passed to the generator's `send` method from the exterior code
3. Corountine can run many functions `seemingly` at the same time.
4. `yield from` composes generato... |
31bc1789c9cddfef609d48fc36f7c1ecb0542864 | Lionelding/EfficientPython | /ConcurrencyAndParallelism/36a_MultiProcessing.py | 2,434 | 4.46875 | 4 | # Item 36: Multi-processing
"""
* For CPU intensive jobs, multiprocessing is faster
Because the more CPUs, the faster
* For IO intensive jobs, multithreading is faster
Because the cpu needs to wait for the I/O despite how many CPUs available
GIL is the bottleneck.
* Multi-core multi-threading is worse than single... |
2ac3ceb50003d412be9a392dfa3be9f078f8a891 | Lionelding/EfficientPython | /MetaclassesAndAttributes/29_Use_Plain_Attributes_Instead_of_Get_and_Set_Methods.py | 1,804 | 4 | 4 | # Item 29: Use Plain Attributes Instead of Get and Set Methods
'''
1. Avoid to define set() and get() explictly
2. With decorator, both setter and getter need to match the attribute name
3. Use setter to validate input type or value
4. Make attribute immutable
5. class.__init__() --> @property.setter, before an object... |
368b25a3c24acd2bd61811676f685cb5083bbd46 | Lionelding/EfficientPython | /3_ClassAndInheritance/27_Private_Attributes.py | 1,778 | 4.28125 | 4 | # Item 27: Prefer Public Attributes Over Private Attributes
'''
1. classmethod has access to the private attributes because the classmethod is declared within the object
2. subclass has no direct access to its parent's private fields
3. subclass can access parents' private fields by tweeking its attribute names
4. Docu... |
3eabf8de3faf6c8bda2531a8a2292bd763113f2e | josiellestechleinn/AulasPython | /recebendo_dados_usuario.py | 1,241 | 4.40625 | 4 | """
Recebendo dados do usuário
input() -> todo dado recebido via input é do tio string
Em python, string é tudo que estiver entre:
- Aspas simples;
- Aspas duplas;
- Aspas simples triplas;
- Aspas duplas triplas;
Exemplos:
- apsas simples -> 'Josielle'
- aspas duplas -> "Josielle"
- aspas simples triplas -> '''Josiel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.