blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
0bbeae4e032dcb99f0079b30813339e1a48d251f | minari1505/AlgorithmForH-M | /Class2/primenumber.py | 509 | 3.515625 | 4 | def solutions(n):
a = [False,False] + [True]*(n-1)
primes=[]
for i in range(2,n+1):
if a[i]:
primes.append(i)
for j in range(2*i,n+1,i):
a[j] = False
print(primes)
def solutions2(n):
sieve = [True] * (n+1)
m = int(n ** 0.5)
for i in range(2,m... |
ba0cd951a3b67ff07a5ce890abab2665839df472 | JerryHu1994/CS-514-Numerical-Analysis | /hw5/hw5.py | 3,492 | 3.5 | 4 | # Math/CS 514 HW5
# Jieru Hu ID:9070194544
import scipy.integrate as integrate
import numpy as np
from matplotlib import pyplot as plt
#define the function
def f(x):
return np.exp(-x)*np.sin(10*x)
# the integration function of the function f(x)
def fintegration(x):
return -10/float(101)*np.exp(-x)*np.cos(10*... |
37def09c3d71c4f31ee2e0a3bc9866bea6746986 | rpparas/LeetCode-Programming-Problems | /Arrays/SortArrayByParity.py | 1,085 | 3.671875 | 4 | # Problem Statement: https://leetcode.com/problems/sort-array-by-parity-ii/
class Solution:
def sortArrayByParityII(self, A: 'List[int]') -> 'List[int]':
odd = -1
even = -1
for i in range(len(A)):
if i % 2 == 1:
if A[i] % 2 != 1:
odd = self.f... |
fe491cf23d8d3eb6504ff462a742f342e1ccf6fc | rpparas/LeetCode-Programming-Problems | /Trees/BinaryTreeDepth.py | 818 | 3.921875 | 4 | # Problem Statement: https://leetcode.com/problems/maximum-depth-of-binary-tree/
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root: 'TreeNode') -> 'int':
if root is ... |
33263688a0a4d15ca011d98817dba018fa990b53 | shyam573/Hackerrank_Challenges-Python | /30 days of code/Day6 - Let's Review.py | 336 | 3.9375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
strings = []
for _ in range(n):
strings.append(input())
for string in strings:
even = "".join([string[i] for i in range(len(string)) if i%2==0])
odd = "".join([string[i] for i in range(len(string)) if i%2!=0])
p... |
20bdc091aa5936ed6cfbcec4f285e9337f6040c2 | arkharman12/oop_rectangle | /ooprectangle.py | 2,518 | 4.34375 | 4 | class Size(object): #creating a class name Size and extending it from object
def __init__(self, width=0, height=0): #basically it inherts whatever is defined in object
self.__width = width #object is more than an simple argument
self.__... |
bc0266fef219910326d60028497b30444a132b3e | nightql/group-of-service | /提取某一列(含去重).py | 767 | 3.65625 | 4 | import pandas as pd
import csv
def drop_duplicate_column(filename, dup_column, filename2):
df = pd.read_csv(filename, encoding="utf-8")
df.drop_duplicates(subset=[df.columns[dup_column]], keep='first', inplace=True)
df = df[df.columns[dup_column]]
df_list = df.values.tolist()
with open(filename2,... |
cc3b5963b6b15945703222f3a3aa717d00441f13 | TimHeiszwolf/Heis_Python_Tools | /PreSufFix.py | 2,223 | 3.96875 | 4 | #This script asks for a directory and then adds a pre or suffix to each filename in that directory.
import os
#https://stackoverflow.com/questions/9727673/list-directory-tree-structure-in-python
for root, dirs, files in os.walk('.'):
level = root.replace('.', '').count(os.sep)
indent = ' ' * 4 * (level)
print('{}{... |
6ba40eec4a91f64bb1675e456566f2018de3c835 | f73162818/270201070 | /lab7/ex2.py | 322 | 4.125 | 4 | def is_prime(a):
if a <= 1:
return False
for i in range(2,a):
if a%i == 0:
return False
return True
def print_primes_between(a,b):
for i in range(a,b):
if is_prime(i):
print(i)
a = int(input("Enter a number:"))
b = int(input("Enter another number:"))
print_primes_between(a,b)
... |
5f81b2a8b4da4335316f98b616e87d0c2de8ab48 | f73162818/270201070 | /lab4/ex5.py | 113 | 3.859375 | 4 | n = int(input("How many numbers?"))
a = 0
b = 1
for i in range(n):
temp = a
a = b
b = temp + b
print (a) |
33f83261e69ebbcb526e464f3ebde0fe8bce84fd | f73162818/270201070 | /lab4/ex1.py | 119 | 3.984375 | 4 | number = int(input("Enter an integer:"))
for i in range(1,11):
print(str(number) + "x"+ str(i) + "=" + str(number*i)) |
57564f124a15697e52dedaceeef0df8db63ff3cc | f73162818/270201070 | /lab3/ex3.py | 92 | 3.5 | 4 | nums = [8, 60, 43, 55, 25, 134, 1]
sum = 0
for number in nums :
sum += number
print (sum) |
7dc8a97d63bc0a1a417e9f00c5fbfbbf95bed93b | pcc-cs/cs-003c-winter-2019-share | /01-10-19/cars.py | 1,770 | 3.890625 | 4 | """
Exercise 2.10 (page 81, modified): select between hybrid and regular cars based on
depreciation and gas costs. The class version is a bit better because of the way
it holds all the info and logic together for good cohesion.
Copyright (c) 2019, Sekhar Ravinutala.
"""
# Loop version.
def _choice(years, miles_per_ye... |
76a39ca0738ac7528aa266fcda8343f5e65ba1e8 | Jerasor01924/NikolasEraso | /ajedrez.py | 2,256 | 4.4375 | 4 | '''Descripción: Reeborg se mueve horizontal o verticalmente en linea recta
en un campo de 8*8 de ajedrez, desde cualquier posición,
según una direccion y el número de pasos a avanzar
Pre:
Reeborg debe mirar al norte y esta en la posicion (2,1)
Reeborg recibe el parametro de direccion siendo
direccion = 1 = --|
dire... |
c24d39b453f5a7f7cc89ff4042d35e8cbb4f541e | ToxicPlatypus/Python-Codes | /JetBrains Academy/Algorithms in Python The sum of numbers in a range.py | 265 | 3.671875 | 4 | def range_sum(numbers, start, end):
result = 0
for x in numbers:
if start <= x <= end:
result += x
return result
input_numbers = list(map(int, input().split()))
a, b = map(int, input().split())
print(range_sum(input_numbers, a, b)) |
deba8206cc3a761650776575a92b2a2ce818af28 | ToxicPlatypus/Python-Codes | /JetBrains Academy/Nested lists Running average.py | 184 | 3.640625 | 4 | x = input()
li = list(x)
length = len(li) - 1
empty = []
for i in range (length):
num = int(li[i]) + int(li[i+1])
num = num / 2
empty.append(num)
print(empty)
|
029f60a8f332dc3bb33ca5899da0770a2f0180e1 | ToxicPlatypus/Python-Codes | /JetBrains Academy/Class instances Right triangle.py | 485 | 3.875 | 4 | class RightTriangle:
def __init__(self, hyp, leg_1, leg_2):
self.c = hyp
self.a = leg_1
self.b = leg_2
# calculate the area here
area = .5 * input_a * input_b
print(area)
# triangle from the input
input_c, input_a, input_b = [int(x) for x in input... |
d3ea84bce3bd66ec7717c47a027d2d53bc516c71 | bab81/IntroPython | /catchingerrors.py | 224 | 4.03125 | 4 |
try:
number = int(input("Enter a number: "))
print(number)
except ValueError as err: # there can be multiple except blocks for a try block, depending on the type of error.
print("Invalid input")
print (err)
|
b68fa443c48907700332320459f7583e1d288f8a | Ealtunlu/GlobalAIHubPythonCourse | /Homeworks/day_5.py | 1,358 | 4.3125 | 4 | # Create three classes named Animals, Dogs and Cats Add some features to these
# classes Create some functions with these attributes. Don't forget! You have to do it using inheritance.
class Animal:
def __init__(self,name,age):
self.name = name
self.age = age
def is_mammel(self):
... |
615bf3eb1b23eb89cd916c176dc59bd39f66440e | YevRomanov/skillup_05_2021 | /Lesson_3.4/Task_2.py | 359 | 3.640625 | 4 | #######################################Task 2#######################################
#
#
def square(func):
def inner(n):
result = func(n)
return result ** 2
return inner
@square
def function(n):
return n
print(function(1))
print(function(6))
print(function(4))
print(function(7))
print(f... |
34a4eabf5dee1c380f4bc3cc2410af41ec8680ab | YevRomanov/skillup_05_2021 | /Lesson_2.4/sets.py | 969 | 3.953125 | 4 | # Создать множества: A, B, C з любыми элементами.
# Найти:
# 1. Различне элементы для A и B.
# 2. Одинаковые элементы для A и C.
# 3. Объединение 3-х множеств.
from pprint import pprint
#
#
# Создаём множества A, B, C:
A = {1, 3, "hello", 7, 9, False}
B = {1, "bye", 2, None, 5, 8, True}
C = {False, "good",1, 0, 2, ... |
07db6f5313c1d77ac326ac54da0213292b764709 | fergmack/efficient-python-code | /numpy_broadcasting_loops_vs_numpy.py | 2,066 | 3.71875 | 4 | # Loops vs Pandas broadcasting
# The broadcasting comes from numpy, simply put it describes the rules of the output that will result when you do operations within the n-dimensional arrays (could be panels, dataframes, series) or scalar values.
import pandas as pd
import numpy as np
baseball = [['ARI', 'NL', 2012, 734... |
810ae5a7013ba2fcb474a98643b0b380049303aa | RakeshKrishna143/Leetcode | /Valid Anagram.py | 221 | 3.96875 | 4 | '''
Engineer's Revolution
Program to check whether two strings
are anagram to each other
'''
s = 'TRIANGLE'
t = 'IntegraL'
def isAnagram(s,t):
return sorted(s.lower())==sorted(t.lower())
print(isAnagram(s, t))
|
b5fd6cb27a327d0cede09f3eb7dbf5d6569cc63d | roselandroche/cs-module-project-recursive-sorting | /src/sorting/sorting.py | 1,182 | 4.28125 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge(arrA, arrB):
# Your code here
merged_arr = []
x = y = 0
while x < len(arrA) and y < len(arrB):
if arrA[x] < arrB[y]:
merged_arr.append(arrA[x])
x += 1
else:
merged_arr.appe... |
bd8ad01532ed91f730a8148f873fab8d12aed939 | Pythones/MITx_6.00.1x | /PS3a_a.py | 459 | 3.5 | 4 | def f(x):
import math
return 10*math.e**(math.log(0.5)/5.27 * x)
##################################
#Code to paste
##################################
def radiationExposure(start, stop, step):
intNumSteps = int((stop-start)/step)
dblresult = 0
for i in range(intNumSteps):
x = start+(i*step)
dblres... |
754b201b7f5b07bbb39f6caac1f1261f270d8b49 | Pythones/MITx_6.00.1x | /L5P4_m.py | 434 | 3.703125 | 4 | def gcdIter(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
#start grader
intMin = min (a, b) #find the minimun
while intMin > 0: #starting the loop
if a % intMin == 0 and b % intMin == 0:
return intMin
else: ... |
eee637b6c9418bcf8cd670f7572fc266b9489bce | Pythones/MITx_6.00.1x | /Problem Sets/PS2b3.py | 716 | 4.0625 | 4 | balance = 3457
annualInterestRate = 0.15
#Monthly interest rate= (Annual interest rate) / 12.0
Mir = annualInterestRate/12
#Minimum monthly payment = (Minimum monthly payment rate) x (Previous balance)
Mmp = 0
#Monthly unpaid balance = (Previous balance) - (Minimum monthly payment)
Mub = 0
#Updated balance each month... |
585b485a0d72877bf0bc8d2bd6cfd1da98dad767 | Pythones/MITx_6.00.1x | /ProblemSet4/PS4d_m.py | 346 | 3.890625 | 4 | def calculateHandlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string int)
returns: integer
"""
ans = 0
lista = hand.values()
for index in lista:
ans += index
return ans
hand = {'a':1,'q':1, 'l':2, 'm':1, 'u':1, 'i':1}
pr... |
89b47fec89f889959582930a1558a84d259b1838 | Pythones/MITx_6.00.1x | /L5P5_m.py | 286 | 3.734375 | 4 | def gcdRecur(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
#start grader
if b == 0:
return a
else:
return gcdRecur (b, a % b) #Euclids rules!
#end grader
print gcdRecur (9, 12) |
2fa594a9be2dda7f8b60118c12fa5793b3a14d54 | rapaMatiase/Ideas-Python | /Sodoku/Sodoku_4.py | 1,629 | 3.984375 | 4 | # PASO 3.2 - IMPRIMIENDO EN PANTALLA EL TABLERO DE JUEGO
sodokuDesboard = [
[0,0,0],
[0,0,0],
[0,0,0]
]
numberOfRows = len(sodokuDesboard)
for i in range(0, numberOfRows):
print(sodokuDesboard[i])
# Ahora necesitamos solicitar la posicion donde el jugador
# desea colocar un numero, para comenzar a ju... |
2e550b93f54ac544b9716fc25ca588efaf0185d4 | mikuc96/Python | /Basic algorithm & Data Structures/Exceptions/cw7_Rectangle.py | 2,750 | 3.90625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# W pliku rectangles.py zdefiniować klasę Rectangle wraz z potrzebnymi metodami.
# Wykorzystać wyjątek ValueError do obsługi błędów. Napisać kod testujący moduł rectangles.
import math as M
from cw7_Point import Point
class Rectangle:
def __init__(self, x1=... |
29bdcfc755753d2001b16d436008a58bd8e5a177 | mikuc96/Python | /Basic algorithm & Data Structures/Algorithms/cw8_4.py | 653 | 4.03125 | 4 | # -*- coding: utf-8 -*-\
# Zaimplementować algorytm obliczający pole powierzchni trójkąta, jeżeli dane są trzy
# liczby będące długościami jego boków.Jeżeli podane liczby nie
# spełniają warunku trójkąta, to program ma generować wyjątek ValueError.
from math import sqrt
def heron(a, b, c):
"""Obliczanie pola p... |
7b8380f392c7bcaff6a01c096a859d678c3838c1 | mikuc96/Python | /Basic algorithm & Data Structures/A*Algorithm/graph.py | 1,417 | 3.90625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Graph:
"""Klasa reprezentująca postać grafu nieskierowanego"""
def __init__(self):
self.graph = {}
def add_node(self, node):
"""Dodaje wierzchołek do grafu nieskierowanego."""
if node not in self.graph:
self.graph[no... |
89fc9faf82e7481743a175d4972056b0881e494f | mikuc96/Python | /Basic algorithm & Data Structures/Abstract data types./cw10_2.py | 1,701 | 3.984375 | 4 | # -*- coding: utf-8 -*-
# Poprawić implementację tablicową stosu tak, aby korzystała z wyjątków w przypadku pojawienia się błędu.
# Metoda pop() ma zgłaszać błąd w przypadku pustego stosu. Metoda push() ma zgłaszać błąd w przypadku
# przepełnienia stosu. Napisać kod testujący stos.
class Stack:
def __i... |
1d48a48bafd7ededb260f3d98e3b4f5159b8ebc7 | Erikanrs/Erika-Nur-Septiani_I0320022_Tiffani-Bella-Nagari_Tugas-4 | /I0320033_soal3_tugas4.py | 556 | 3.515625 | 4 | #Memeriksa berat bagasi pesawat yang diperbolehkan
#Diketahui berat yang diperbolehkan
Berat_max = 50 lbs
lbs = 0.45 kg
Beratmaxdalamkg = 50 * 0.45
print("Berat maksimum dalam kg adalah: ", Beratmaxdalamkg, "kg")
kasusA = 110
kasusB = 49
resultA = kasusA < Beratmaxdalamkg
resultB = kasusB < Beratmaxdalam... |
f7fc43abd68e35ec61eb6016baf9beff018a456a | xlxmht/DS | /Arrays/sorted_squared.py | 561 | 4.0625 | 4 | # Function takes sorted array and return sorted squared array
def sorted_squared(array):
squared_sorted = []
left = 0
right = len(array) - 1
while left <= right:
if abs(array[left]) < abs(array[right]):
element_to_prepend = array[right]
right -= 1
else:
... |
7b071815a5785d809e38d2a4d64c1199c8c9b250 | xlxmht/DS | /Sorting/bubblesort.py | 450 | 4.3125 | 4 | def bubble_sort(arr):
is_swapped = True
while is_swapped:
is_swapped = False
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
swap(i, i + 1, arr)
is_swapped = True
return arr
def swap(i, j, arr):
arr[i], arr[j] = arr[j], arr[i]
retur... |
8133f7bbdfe2beb44f12509ebf9bcd51eff735b4 | xlxmht/DS | /Sorting/quicksort.py | 1,070 | 4.09375 | 4 | # Last array element is taken as Pivot Element
def quick_sort(array, start_idx, end_idx):
if start_idx < end_idx:
start = start_idx
end = end_idx
print(array)
pivot_index = partition(array, start, end)
quick_sort(array, start, pivot_index - 1)
quick_sort(array, pivot_... |
859523004067d281cc0d81adb5c68a747236301b | CahyaPutera/Latihan-Tugas | /Latihan Class.py | 1,411 | 3.765625 | 4 | class BikinMenu ():
def __init__(self, name, menu, price):
self.name = name
self.menu = menu
self.price = price
self.history = []
def get_menu(self):
print('Menu Makanan')
print('')
print('{} harganya adalah {}' .format(self.menu[0], sel... |
aae6352bb5caafa0f709deb29787a2fc5f6e93df | BichonCby/BaseBSPython | /Action.py | 2,913 | 3.53125 | 4 | # -*-coding:Latin-1 -*
#from Definitions import LOCK_UNLOCK,LOCK_NEW,LOCK_LOCK
from Definitions import *
class Action:
""" Classe qui va gérer les actionneurs hors propulsion
...
"""
def __init__(self,rob,sens):
#valeurs d'init
self.StateRightDoor = 0 #�tat actuel de la porte
s... |
8cdde4d9796c24ace2ee25264cc2d7e5d007e504 | ShreyKumar/Programming-for-Everybody-code | /assign10/week10.py | 510 | 3.6875 | 4 | name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
lines = open(name)
alltimes = dict()
for line in lines:
if line.startswith('From') and not line.startswith('From:'):
words = line.split()
#take times and make a dict
times = words[5]
for chars in times:
hour = times[:2]
alltimes[h... |
acece68f66c532ca2163016dd30904383a9879a0 | PythonPonies/bangazon_cli | /app/customer.py | 3,426 | 4.46875 | 4 | import sqlite3
class Customer(object):
""" The Customer class creates a new Customer with data passed to it.
Method List:
- __init__: instansiates the new Customer with customer_name, city, state, postal_code, and phone_number
- get_customer_name
- get_street_address
- get_city... |
c08e0d661e7c31b5a23f1fe248a3a26c63fac5d0 | PythonPonies/bangazon_cli | /app/ordermanager.py | 7,584 | 4.03125 | 4 | import sqlite3
class OrderManager():
""" The Order Manager class manages orders and products with data passed to it.
Method List
- create_order, customer_has_active_order, add_product_to_origin, get_products_on_order
Arguments
- The object argument lets the Order Manager class inherit pr... |
01ca6366a316e3ebf5fef3d7999a6fd52c440c61 | bl15343/abyteofpython | /advanced/list_comprehensions.py | 165 | 3.828125 | 4 | listone = [2, 3, 4]
#Initialize the second list iff i > 2, and set the values to twice
#the value in listone
listtwo = [2*i for i in listone if i > 2]
print(listtwo) |
19a694d81d5c815cb52406658a810e29ad9b1cf0 | sianteesdale/AgentBasedModel2 | /model.py | 3,506 | 3.796875 | 4 | # IMPORT LIBRARIES
import csv # Used to read in csv files and write them
import drunkframework # Contains functions for the 'Agent' class
import matplotlib.pyplot as plt # Used for plotting
# CREATE VARIABLES
# With [] being empty lists that will be filled
density = []
town = [... |
78af845256468cbf457ff4c06f2a5d62a09a605d | i-qiqi/python-in-action | /functional_program/funcs_lib.py | 1,537 | 3.703125 | 4 | import math
from functools import reduce
def my_abs(x):
if not isinstance(x, (int,float)):
raise TypeError('bad operand type')
if x >= 0:
return x
else:
return -x
def nop():
pass
# 返回多个值
def move(x , y , step , angle=0):
nx = x + step * math.cos(angle)
ny = y - step * ... |
59ef20e2415c778623765a8e192f0b5490d667a1 | x-nm/Python | /Rosalind/binary_search.py | 1,584 | 3.625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
binary search
input:
n
m
sorted array a[n]
list of m int: ki
output:
for each ki, return the 1-based index (j) of a[j] = ki, if no match was found, return -1
2016.01.29 by xnm
'''
#input
file_in = open('binary_search.txt','r')
n_in = int(file_in.readline())
m = i... |
b0cffb4bf6041ee9a73ed1431652db9e90889320 | x-nm/Python | /Class_Interactive_py/rock paper scissors.py | 691 | 3.828125 | 4 | #rock paper scissors
import random
def letter_to_number(letter):
if letter == "rock":
return 1
if letter == "paper":
return 2
if letter == "scissors":
return 3
def number_to_letter(num):
if num == 1:
return "rock"
if num == 2:
return "paper"
if num == 3:
return "scissors"
def rpc(guess):
guessnum... |
86ed03382a5f30c7f7688494412cc419a655add5 | a289237642/algorithm010 | /Week09/387. 字符串中的第一个唯一字符.py | 985 | 3.84375 | 4 | """
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = "leetcode"
返回 0
s = "loveleetcode"
返回 2
提示:你可以假定该字符串只包含小写字母。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from collections import OrderedDict
class Solution(object):
... |
4a8c2ad2eafe2cefe78c0ccd5750f097671c7075 | GermanSumus/Algorithms | /unique_lists.py | 651 | 4.3125 | 4 | """
Write a function that takes two or more arrays and returns a new array of
unique values in the order of the original provided arrays.
In other words, all values present from all arrays should be included in their
original order, but with no duplicates in the final array.
The unique numbers should be sorted by the... |
a2ead2b560d0f1dddae844a9662b019b99daf0a2 | GermanSumus/Algorithms | /largest_prime_factor.py | 708 | 3.890625 | 4 | '''
# 3
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
'''
def largest_prime(n):
def factors(n):
result = set()
for i in range(1, int(n ** 0.5) + 1):
div, mod = divmod(n, i)
if mod == 0:
result |=... |
b7ac1cfbb9087510ade29a2d2605b8cc01345d1f | GermanSumus/Algorithms | /factorialize.py | 268 | 4.21875 | 4 | # Return the factorial of the provided integer
# Example: 5 returns 1 * 2 * 3 * 4 * 5 = 120
def factorialize(num):
factor = 1
for x in range(1, num + 1):
factor = factor * x
print(factor)
factorialize(5)
factorialize(10)
factorialize(25)
|
c2790a23c2030775a1ed612e3ee55c594ad30802 | iamzaidsoomro/Python-Practice | /Calculator.py | 706 | 4.15625 | 4 | def calc():
choice = "y"
while(choice == "y" or choice == "Y"):
numb1 = input("Enter first number: ")
numb2 = input("Enter second number: ")
op = input("Enter operation: ")
numb1 = int(numb1)
numb2 = int(numb2)
if op == '+': print("Sum = " + str(numb1 + nu... |
de917e3c11ac2e41467b10cce99bbea767bb01c6 | PeppaYao/shepherding-problem | /python_basic/ordereddict.py | 438 | 3.75 | 4 | from collections import OrderedDict
od = OrderedDict()
od['c'] = 1
od['a'] = 2
od['b'] = 3
print(od) # key是按照元素插入的顺序来排序的,而不是按照key本身
keys = ['apple', 'banana', 'cat']
values = [4, 5, 6]
od.update(zip(keys, values)) # 向老字典之中追加一个新字典,相当于合并了两个字典
print(od)
od.pop('a') # 删除
print(od)
od.move_to_end('b') # 将'b'元素移动到队尾
prin... |
6544981cdebc92f121c9504e93cf1b464af1cef8 | jnjnslab/python-sample | /04_list/join.py | 163 | 3.765625 | 4 | #リストを連列して文字列にする
print(','.join(['cats','bats','rats']))
print(' '.join(['cats','bats','rats']))
print(''.join(['cats','bats','rats']))
|
aa869b01b62ea34a42e31bba9f4cab6ca3973a85 | jnjnslab/python-sample | /10_file/write.py | 576 | 3.75 | 4 | #ファイルをオープンする
f = open('bacon.txt', 'w', encoding='UTF-8')
#1行書き込む
f.write('Hello World!\n')
f.write('こんにちは!\n')
#ファイルをクローズする
f.close()
#ファイルをオープンする
f = open('bacon.txt', 'a', encoding='UTF-8')
#1行追加する
f.write('Bacon is not a vegetable.\n')
#ファイルをクローズする
f.close()
#ファイルをオープンする
f = open('bacon.txt', 'r', encoding='UTF-8')... |
33e16681b9a56a3704fbb40b4b8e8025fd74b54f | jnjnslab/python-sample | /04_list/list_03.py | 174 | 3.765625 | 4 | #リストの値を変更する
spam = ['cat','bat','rat','elephant']
print(spam)
spam[1] = 'aardvark'
print(spam)
spam[2] = spam[1]
print(spam)
spam[-1] = 12345
print(spam)
|
310c96f69af2d8f73f4a363a36a3a42e6c63f826 | jnjnslab/python-sample | /13_class/class_07.py | 222 | 4.09375 | 4 | #is演算子 同一のオブジェクトか識別する
class Person:
def __init__(self,name):
self.name = name
bob = Person('Bob')
same_bob = bob
print(bob is same_bob)
tom = Person('Tom')
print(bob is tom) |
873c53d8651db1aabe5b58e54c464c6226d771c9 | jnjnslab/python-sample | /28_statistics/02_many.py | 382 | 3.5625 | 4 | # 数値計算に使うライブラリ
import pandas as pd
import numpy as np
import scipy as sp
#データ
cov_data = pd.read_csv("data/3-2-3-cov.csv")
print(cov_data)
# データの取り出し
x = cov_data["x"]
y = cov_data["y"]
# 標本共分散行列
print(np.cov(x, y, ddof = 0))
# 不偏共分散行列
print(np.cov(x, y, ddof = 1))
# 相関行列
print(np.corrcoef(x, y))
|
a2fe42f6c3500282e2173406614443be51682bc5 | jnjnslab/python-sample | /20_tkinter/calc.py | 4,247 | 3.546875 | 4 | import tkinter as tk
class Application(tk.Frame):
def __init__(self,master):
super().__init__(master)
self.pack()
master.geometry("700x155")
master.title("簡易電卓")
self.checkSym=False
self.textNumber=""
self.createButton()
self.createCanvas()
... |
f424d1cd3b3dab9366b0636aa03bf9bc431058c9 | jnjnslab/python-sample | /09_datetime/datetime_05.py | 129 | 3.5625 | 4 | from datetime import date
#日付→文字列
fmt1 = "%Y/%m/%d (%A)"
some_day = date(2020,10,25)
print(some_day.strftime(fmt1))
|
87e2258745beb1162f55ebe6c1b764541d73a8bb | jnjnslab/python-sample | /10_file/readline.py | 247 | 3.578125 | 4 | #ファイルをオープンする
f = open('hello.txt', 'r', encoding='UTF-8')
#1行ずつ読み込む
while True:
data = f.readline()
if data == '':
break
print (data.rstrip('\n'))
#ファイルをクローズする
f.close() |
8f076f012de7d9e71daff7736fc562eff99078aa | kartikay89/Python-Coding_challenges | /countLetter.py | 1,042 | 4.5 | 4 | """
Write a function called count_letters(text, letter), which receives as arguments a text (string) and
a letter (string), and returns the number of occurrences of the given letter (count both capital and
small letters!) in the given string. For example, count_letters('trAvelingprogrammer', 'a') should return 2
an... |
7c54349a4f78cefb44bff8616fc370b865849d48 | kartikay89/Python-Coding_challenges | /phoneNum.py | 1,223 | 4.53125 | 5 | """
Imagine you met a very good looking guy/girl and managed to get his/her phone number. The phone number has 9 digits but, unfortunately, one of the digits is missing since you were very nervous while writing it down.
The only thing you remember is that the SUM of all 9 digits was divisible by 10 - your crush was ne... |
c0f71926967cb09c5823f494e8bbb02d6354efcb | kartikay89/Python-Coding_challenges | /PythonClasses.py | 730 | 4 | 4 | """
Example 1
"""
""" The example shows a very simple data in a class """
class UserData:
"""docstring for UserData"""
def __init__(self, First_Name, last_Name, Age):
self.FN = First_Name
self.LN = last_Name
self.Age = Age
User = UserData("Kartikay", "Singh", 30)
print(User.FN)
print(User.LN)
print(User.A... |
6499d6d509ab6089166ff58f66d174bdaa1177ba | ZiyaadLakay/PersonalProjects | /Python/WorkingWithNumbers.py | 7,415 | 4.5 | 4 | #Ziyaad Lakay
#-------------------------------------------------------
#-------------------------------------------------------
#Even or Odd
num = input("Enter a whole number : ") #Ask the user to enter a positive number
while '.' in num : ... |
f24db7c62d023d0ad59811ff929907179621918b | BertiRean/HackerRank | /10DaysOfStatistics/WeightedMean.py | 716 | 3.703125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
def get_weighted_mean(p_Values, p_Weights, p_N):
mean = 0.0
if p_N == 0:
return 0.0
total_weight = 0.0
for idx, value in enumerate(p_Values):
mean += (value * p_Weights[idx])
total_weight += p_W... |
a9e0cb0fd745e9f49028bfd0a4448e944089dc9a | KleyJkGameDev/Atividades-do-Curso-em-Video-de-Python-Mundo-2 | /exercicios2.py | 6,298 | 4.1875 | 4 | from time import sleep
from datetime import date
# A contagem para no ultimo item. ex: range(0, 4) --> 1, 2, 3
# para contagem regressiva use --> range(4, 0, -1)
# uma terceira virgula serve para iteração --> renge(0, 4, 2) --> 0, 2, 4
programa = 0
while programa == 0:
print('\n')
print('''[1] Contagem regress... |
edf9a9ca91758a61c1403e23c1c27d5158c7dc1a | ravenawk/pcc_exercises | /chapter_06/polling.py | 484 | 4.09375 | 4 | #!/usr/bin/env python3
'''
List people's favorite programming languages
'''
favorite_language = {
'jen': 'pyhton',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
list_of_people = ['jen', 'scott', 'sarah', 'art', 'edward', 'phil']
for person in list_of_people:
if perso... |
c3bd11215bb589aa0940cf92e249d2dd8815b8e8 | ravenawk/pcc_exercises | /chapter_07/deli.py | 413 | 4.28125 | 4 | #!/usr/bin/env python3
'''
Making sandwiches with while loops and for loops
'''
sandwich_orders = ['turkey', 'tuna', 'ham']
finished_sandwiches = []
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
finished_sandwiches.append(current_sandwich)
print(f"I made your {current_sandwich} sandwich.... |
144356a78f850ae6278182a0b19f8774c2834ed8 | ravenawk/pcc_exercises | /chapter_02/name_case.py | 166 | 3.65625 | 4 | #!/usr/bin/env python3
name = "Steve Rogers"
print(f"{name.lower()} is all lowercase. \n{name.upper()} is all uppercase. \n{name.title()} is in title case.")
print(f"{
|
a12ef9a4cf39708675978b57cee13a4d8a33a231 | ravenawk/pcc_exercises | /chapter_03/shrinking_guest_list.py | 1,369 | 4.09375 | 4 | #!/usr/bin/env python3
list_of_guests = ['Arthur Martin Sr.', 'Janet Huertas', 'Grandma Martin']
print(f"I have found a bigger dinner table")
print(f"{list_of_guests[0]}, please join us for dinner tonight.")
print(f"{list_of_guests[1]}, please join us for dinner tonight.")
print(f"{list_of_guests[2]}, please join u... |
4a31b965db2131fd7790ba1e4397ec50463da51c | ravenawk/pcc_exercises | /chapter_10/silent_cats_and_dogs.py | 340 | 3.859375 | 4 | #!/usr/bin/env python3
def print_contents(filename):
try:
with open(filename, 'r') as f:
lines = f.readlines()
for line in lines:
print(line.strip())
except FileNotFoundError:
pass
filenames = ['cats.txt', 'dogs.txt']
for somefile in filenames:
print... |
b0ee2dc3c3865353f42b2b18c45e0a8b77c7c7bc | ravenawk/pcc_exercises | /chapter_04/slices.py | 326 | 4.25 | 4 | #!/usr/bin/env python3
list_of_cubes = [ value**3 for value in range(1,11)]
for cube in list_of_cubes:
print(cube)
print(f"The first 3 items in the list are {list_of_cubes[:3]}.")
print(f"Three items in the middle of the list are {list_of_cubes[3:6]}.")
print(f"The last 3 items in the list are {list_of_cubes[-3:... |
f87fbc9f1ad08e89dd1fd5e561bf0956f01b2a6e | ravenawk/pcc_exercises | /chapter_07/dream_vacation.py | 381 | 4.21875 | 4 | #!/usr/bin/env python3
'''
Polling for a dream vacation
'''
places_to_visit = []
poll = input("Where would you like to visit some day? ")
while poll != 'quit':
places_to_visit.append(poll)
poll = input("Where would you like to visit one day? (Enter quit to end) ")
for place in places_to_visit:
print(f"{p... |
b102953b0aaef366c4056dfb9b94210c416b7512 | ravenawk/pcc_exercises | /chapter_08/user_albums.py | 514 | 4.34375 | 4 | #!/usr/bin/env python3
'''
Function example of record album
'''
def make_album(artist_name, album_title, song_count=None):
''' Create album information '''
album = {'artist': artist_name, 'album name': album_title,}
if song_count:
album['number of songs'] = song_count
return album
while True:
... |
d9dcfac877d83df96bcd621ae7b52e48f214447b | ravenawk/pcc_exercises | /chapter_11/test_employee.py | 643 | 3.96875 | 4 | #!/usr/bin/env python3
import unittest
from employee import Employee
class TestEmployee(unittest.TestCase):
"""Testing Employee class"""
def test_give_default_raise(self):
"""Testing increase salary"""
new_employee = Employee('Test', 'Employee', 50000)
new_employee.increase_salary()
... |
ffc9353559dcbc5d83b825c074ccd23134928e26 | silva-felipe/kattis | /bijele.py | 394 | 3.53125 | 4 | chess_set = {'king': 1, 'queen': 1, 'rooks': 2, 'bishops': 2, 'knights': 2, 'pawns': 8}
chess_v = chess_set.values()
pieces = input().split()
missing_pieces = []
for piece_chess_c, piece in zip(chess_v, pieces):
m = piece_chess_c - int(piece)
missing_pieces.append(m)
print(missing_pieces[0],missing_pieces[1... |
21e35ee5f79eadacf5a31df761128d5c31da68cc | silva-felipe/kattis | /autori.py | 104 | 3.5625 | 4 | long = input()
names = long.split('-')
short = ''
for name in names:
short += name[0]
print(short) |
26b62f140c0731d16b1f906f7f0043aa3e7dbd98 | Tananiko/python-training-2020-12-14 | /nested.py | 172 | 3.78125 | 4 | number = int(input("Adj meg egy szamot"))
if number < 100:
print("Kisebb mint szaz")
if number % 2 == 0:
print("Paros")
else:
print("Paratlan") |
14ad87c52ffe46bd39dcae811e5fcc6653cd4625 | Tananiko/python-training-2020-12-14 | /alarm.py | 256 | 3.78125 | 4 | actual_time = int(input("Hány óra van?"))
print(actual_time)
req_alarm_time = int(input("Hány óra múlva szólaljon meg az ébresztő?"))
print(req_alarm_time)
req_alarm_time = (actual_time + req_alarm_time) % 24
print("Hour: " + str(req_alarm_time))
|
0d1604f91d1634f8d3d55d54edc6ed1bc0ce44ca | Tananiko/python-training-2020-12-14 | /lists.py | 709 | 4.15625 | 4 | names = [] # ures lista
names = ["John Doe", "Jane Doe", "Jack Doe"]
john = ["John Doe", 28, "johndoe@example.com"]
print(names[0])
print(names[1])
# print(names[4]) # list index out of range
print(names[::-1])
print(names)
numbers = [1, 2, 3, 4, 5]
print(numbers)
print(len(numbers))
employees = [['John Doe',... |
bce394f5506bbc6ef537ced584ed64e4c2ac7616 | Tananiko/python-training-2020-12-14 | /files.py | 1,159 | 3.796875 | 4 | def write_hello():
with open("hello.txt", "w") as file:
file.write("hello\n")
# algoritmus
file.write("python\n")
print("end")
# Írjátok ki egy fájlba a kettes szorzótáblát 1*2 - 10*2 (sortöréssel elválasztva)
def write_table():
with open("table.txt", "w") as file:
for i in... |
6f917612da544255dc6bb5a565b2f866a5630d5f | joesprogramming/School-and-Practice | /New folder/car program.py | 830 | 4.0625 | 4 |
#Joe Joseph
#Intro to programming
#Car Class program
# Import class
import car
#Create function
def main():
#Create loop value
x = 0
# Ask for user input
year_py = input('Enter the year of the vehicle: ')
make_py = input('Enter the Make of the vehicle: ')
speed... |
12c1a2d3672a7f0c7d391e958e8a047ff3893106 | joesprogramming/School-and-Practice | /Calculate Factorial of a Number CH 4 pgm 10.py | 281 | 4.25 | 4 | # Joe Joseph
# intro to programming
# Ask user for a number
fact = int(input('Enter a number and this program will calculates its Factorial: ',))
# define formula
num = 1
t = 1
#run loop
while t <= fact:
num = num * t
t = t + 1
print(num)
|
b931256e821d0b59a907d580734f21c455c22eb4 | joesprogramming/School-and-Practice | /person customer/person.py | 1,175 | 4.125 | 4 | #Joe Joseph
# Intro to Programming
#Primary Class
class Person:
def __init__(self, name_p, address_1, phone_1):
self.__name_p = name_p
self.__address_1 = address_1
self.__phone_1 = phone_1
def set_name_p(self, name_p):
self.__name_p = name_p
de... |
d7a33b95fb60bdb1fc73567bbfca75adc92a1fea | arahant/Science-Simulator-Calculator | /python/physics/mechanics/motion/harmonic/SpringSingle.py | 1,732 | 3.890625 | 4 | import math
import numpy as nm
import matplotlib.pyplot as plt
def calculateOscillationTime(mass,K):
return math.sqrt(float(mass)/K)*2*nm.pi
def calculatePotentialEnergy(K,x):
return float(K)*x*x/2
def calculateKineticEnergy(K,A,x):
KE = calculatePotentialEnergy(K,A) \
- calculatePotentialEnergy(... |
04a1307ddf46a5bc3e97b20ce506a1b5aaaeea5b | machine1010/Basic_Python_Visualization_MachineLearning | /Code_Data_PreProcess_Scaling.py | 1,095 | 4 | 4 | #Scaling. This means that you're transforming your data so that it fits within a specific scale, like 0–100 or 0–1. You want to scale data when you're using methods based on measures of how far apart data points, like support vector machines, or SVM or k-nearest neighbors, or KNN.
#All algorithms that are distance bas... |
858109dcf986fdcea8167a62889b596517ddae2f | marswierzbicki/corposnake | /classes/scoreboard.py | 1,508 | 3.71875 | 4 | import pygame
from pygame.sprite import Sprite
class Scoreboard(Sprite):
"""Scoreboard for presenting game score"""
def __init__(self, background_image_path, x, y, currency,
text_color_r, text_color_g, text_color_b, font_size, text_margin_right):
"""Initialize Scoreboard"""
... |
ded2dc7c4cbcc6bc353249ae3ec74a3a299c5ea6 | coolawesomeman/pythonroom | /dfjl.py | 193 | 3.5625 | 4 | # author: coolawesomeman
import turtle
number
t = turtle.Turtle()
for number in numbers:
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.left(90) |
94b27e318f61f25308421ce4e52c95653e2bbcac | TibaZaki/DFSA | /DFSA.py | 3,408 | 3.625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import itertools
import collections
import sys
import codecs
# author: Tiba Zaki Abdulhameed Jan 12,2018 Western Michigan University/Al-Nahrain University Iraq
# this program takes 4 argument
#1: dialect corpus to be morphologicaly processed
#2: MSA vocabulay file of words, e... |
6a159a65ea848c61eb4b35980b2bd524a5487b56 | BzhangURU/LeetCode-Python-Solutions | /T522_Longest_Uncommon_Subsequence_II.py | 2,209 | 4.125 | 4 | ##Given a list of strings, you need to find the longest uncommon subsequence among them. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.
##
##A subsequence is a sequence that can be derived from one s... |
d92385b8f66c54cae70683b6f91adcf86efca138 | DongliHe1/DongliHe | /lab1/lab:ex3.py | 367 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on %(date)s
@author: %(username)s
"""
annual_deposit = int(input('Enter annual deposit: '))
rate = int(input('Enter rate: '))
balance = annual_deposit * (1+(rate/100))**3 + annual_deposit * (1+(rate/100))**2 + annual_deposit * (1+(rate/100))
print('After 3... |
cfdd4c455bce0412f3fb7079f2118e45c0977c7a | jordiBujaldon/xarxes_sockets_python | /server.py | 4,230 | 3.609375 | 4 | import socket
import threading
HOST = '127.0.0.1'
PORT = 8080
ADDR = (HOST, PORT)
BUF_SIZE = 1024
FORMAT = 'utf-8'
class Server(threading.Thread):
"""
Crea un servidor capac de rebre diferents clients
"""
def __init__(self, host, port):
super().__init__()
self.connections = []
... |
99b4c55fe2f2b75c0d24e48972bae80d48f1a9c6 | Malachi-Holden/fun-python-projects | /turing_machine.py | 3,163 | 3.984375 | 4 | """
This is a program for running a turing machine. It is very old and may or may not work.
I plan to redesign it soon
"""
class State:
def __init__(self, ruleNone, rule1, rule2):
"""
:param ruleNone: a tuple (return, state, movement) telling what number to place down, what state to go to... |
f34f8c91e9c0f2a627f072442c9750fbbc6dd08b | mallimuondu/Algorithims | /arranging.py | 457 | 3.9375 | 4 | input1 = int(input("Enter the first number: "))
input2 = int(input("Enter the second number: "))
input3 = int(input("Enter the third number: "))
input4 = int(input("Enter the fourth number: "))
input5 = int(input("Enter the fifth number: "))
tuple_num = []
tuple_num.append(input1)
tuple_num.append(input2)
tuple_nu... |
327bbbe83fa6145053131dbb439b8cdc866f1259 | cparker10/PythonSearch | /count_schools.py | 2,569 | 3.5 | 4 | import csv
import time
import itertools
def school_by_state():
sch_dict = csv.DictReader(open('school_data.csv', 'r'))
start_time = time.time()
# total = 0
print(" ")
print("Schools by State: ")
for key, group in itertools.groupby(sch_dict, lambda x: x['LSTATE05']):
schools_by_state = ... |
a2bf521aa0ee2b5411b972057579429ce044102c | RichardDev01/letter-frequency-school-assignment | /classify_rows.py | 6,175 | 3.5 | 4 | """Classify input text file to Dutch or English language"""
import sys
import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error
def mapper_lf(row: list) -> str:
"""
Map the inputs with 1 and replaces spaces with ' ' and special chars with '_'
:param row: list of string, each ... |
05eead905975be26946149dd664456e6e7f20449 | andrew-chen/csis349 | /dijkstra.py | 3,143 | 3.90625 | 4 | """
Dijkstra's algorithm,
adapted from Tanenbaum's Computer Networks, fifth edition,
rewritten in Python,
adapted to be more Pythonic than a direct port
"""
# have dist be a dict where the keys are pairs
dist = {
(0,0) : 0,
(0,1) : 1,
(1,0) : 1,
(0,2) : 2,
(2,0) : 2,
(0,3) : 3,
(3,0) : 3,
(1,1) : 0,
(1,2)... |
69356a186e7c0d5c6e449f659125c1cfc5a8eb34 | emmanuelcharon/GoogleHashCode | /2017/finals/steiner_tree.py | 47,751 | 3.53125 | 4 | """
Created on 25 Apr. 2018
Python 3.6.4
@author: emmanuelcharon
In this file, we provide different heuristics to solve the Steiner tree problem.
We use "highways" to connect "cities" (instead of backbone to connect routers).
"""
import numpy as np
import random
import math
import time
from routers_basics import Ut... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.