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 |
|---|---|---|---|---|---|---|
f72a2973777f6e07a472d8d945c6181db55f0149 | hsuanwen0114/sharon8811437 | /HW3/binary_search_tree_06170226.py | 2,729 | 3.6875 | 4 |
# coding: utf-8
# In[33]:
class TreeNode(object):
def __init__(self,x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def insert(self, root, val):
if root == None:
root = TreeNode(val)
return root
else:
... |
1d3fff09c010a933a0ca8e449d26a400c8f82018 | GhadeerHS/FullStack-DojoBootcamp | /Python_Stack/_python/OOP/User-ChainingMethods.py | 937 | 3.78125 | 4 | class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
def make_deposit(self, amount):
self.account_balance += amount
return self
def make_withdrawal(self, amount):
self.account_balance -= amount
retur... |
2545737696b06791648668be7b1ff00f4560fda0 | cheungYX/nlp100 | /python/temp.py | 195 | 3.640625 | 4 | # encoding: UTF-8
x = 12
y = "気温"
z = 22.4
def temp(x, y, z):
# return str(x) + "時の" + y + "は" + str(z)
return '{x}時の{y}は{z}'.format(x=x, y=y, z=z)
print(temp(x, y, z))
|
e50125140d9bea77ba542aa0744c3f8a37559b1e | cheungYX/nlp100 | /python/patoka_taxi.py | 179 | 3.5625 | 4 | # encoding: UTF-8
word1 = "パトカー"
word2 = "タクシー"
res = ""
for i,j in zip(range(0, len(word1)), range(0,len(word2))):
res += word1[i]
res += word2[j]
print(res) |
fbf53fa4ce50fd7df01df3f67659824eeb031b07 | c-a-r-d-g-a-m-e/tacobellgenerator | /taco bell generator.py | 710 | 3.796875 | 4 | import random
word1 = ["crunchy", "soft", "supreme", "beefy", "nacho", "beefy 5-layer", "cheesy", "nacho cheese", "spicy", "mild"]
word2 = [" chicken", " bean", " black bean", " nacho", " doritos locos", " gordita"]
word3 = [ " taco", " burrito"," chalupa", " quesadilla", " bellgrande", " supreme", " crunchwra... |
8bf2921b08e068aa754f0924f164605dd672049a | nauman-sakharkar/Python-2.x | /Skip Repeated Char.py | 164 | 3.953125 | 4 | list=input("Please Enter Your List = ")
output=[]
output = [n for n in list if n not in output]
print("Your Requested List : ", ''.join(output))
print("Thank You")
|
0a3b73ddacb55539c7fbf2cd7c97fe40aed5a0ce | nauman-sakharkar/Python-2.x | /Area of the Triangle.py | 169 | 3.921875 | 4 | b=float(input("Enter the Base of the Triangle = "))
h=float(input("Enter the Height of the Triangle = "))
a=.5*h*b
print("Area of the Triangle is",a)
print("Thank You")
|
88b0275b14cfe4ab86b469926df08dfbe37229cc | nauman-sakharkar/Python-2.x | /Sum of Factorials.py | 285 | 4.03125 | 4 | a=int(input("Please Enter Your Number = "))
b=int(input("Please Enter Your Number = "))
sum=0
for i in range(a,b+1):
fact=1
for j in range(1,i+1):
fact=fact*j
print("Factorial of ",j," = ",fact)
sum=sum+fact
print("Sum of Factorials = ",sum)
print("Thank You")
|
944c8136f1e444ccb9fb15eaacb731df40c67184 | nauman-sakharkar/Python-2.x | /Check Leap Year.py | 128 | 4.03125 | 4 | a=int(input("Please Enter The Year = "))
if a%4==0:
print(a," Is A Leap Year")
else:
print(a,"Is Not A Leap Year")
|
82578460b2e44863b1ec837df47585d1da63f41c | nauman-sakharkar/Python-2.x | /Binary to Decimal.py | 203 | 3.8125 | 4 | a=int(input("Please Enter Your Binary Number = "))
j=1
o=0
while True:
if a<1:
break
else:
s=a%10
o=o+s*j
a=a//10
j=j*2
print("Your Decimal Number : ",o)
|
dbb7679261275df18328c3309f0a675e22714740 | adoskk/PyTorch-Learning-101-Fizz-Buzz-Net | /utils/data_preprocessing.py | 590 | 3.609375 | 4 | import numpy as np
# Represent each input by an array of its binary digits.
def binary_encode(i, num_digits):
return np.array([i >> d & 1 for d in range(num_digits)])
# One-hot encode the desired outputs: [number, "fizz", "buzz", "fizzbuzz"]
def fizz_buzz_encode(i):
if i % 15 == 0:
return np.array([... |
ac4dd126f23e04a3033d8d3c1525f8019b8ce885 | pillared/PLC-Exam-2 | /Q1/driver.py | 1,708 | 3.546875 | 4 | #####################################
#####################################
############# PLC EXAM 2 ############
###### Created by Anthony Asilo #####
########### November 2020 ###########
#### https://github.com/pillared ####
#####################################
#####################################
"""
DRIVER.PY T... |
dc5c2c3645b680a13c5af07cfb859c1079eaee40 | kettchansopon/atm-crud-system | /atm-crud-system.py | 12,721 | 4.125 | 4 | import sqlite3
import os
import pickle
from docx import Document
def create_account():
conn = sqlite3.connect('Account.sqlite')
try:
c = conn.cursor()
c.execute('CREATE TABLE customer (\
customerID TEXT NOT NULL PRIMARY KEY,\
name TEXT NOT NULL,\
... |
1465259df7e87d5df881f870524a316093c37fe8 | Grommash9/python_25_skillbox | /25_zadacha_4/people.py | 3,498 | 3.796875 | 4 | def text_check(some_text):
for symbols in some_text:
if not symbols.isalpha():
raise NameError(symbols, 'не являеться буквой')
if len(some_text) < 3:
raise NameError('Имя или фамилия не должны быть такими короткими')
return some_text
class Person:
def __init__(self... |
37bb145d0f063f2c820004b0e127d3f63241d459 | narendrapetkar/python | /2.dataStructures/1.linkedList/1.singlyLinkedList.py | 1,651 | 3.578125 | 4 | class node:
def __init__(self, data = None, next = None):
self.data = data
self.next = next
class singlyLinkedList:
def __init__(self):
self.start = None
def displayList(self):
print("-----------------------------------------")
if self.start == None:
... |
47608808b2736c157c41e81e69dd5e0ca8daa052 | narendrapetkar/python | /2.dataStructures/2.stacks/1.stackUsingLinkedList.py | 1,223 | 3.953125 | 4 | class node:
def __init__(self, data = None, next = None):
self.data = data
self.next = next
class stack:
def __init__(self, size=5):
self.top = None
self.size = size
self.length = 0
def display(self):
print("--------------------------------------------")
... |
40f56600fec03f9964ac06360ae6eab602a5d7bd | narendrapetkar/python | /2.dataStructures/3.queues/1.queueUsingLinkedList.py | 1,250 | 3.953125 | 4 | class node:
def __init__(self, prev=None, data=None, next=None):
self.prev = prev
self.data = data
self.next = next
class queue:
def __init__(self):
self.start = None
self.end = None
def display(self):
print("---------------------------------------------... |
04a6cd5174c6519f585c799fcab887f7294d232a | dragon0/clock | /minimalist_clock.py | 2,594 | 3.5625 | 4 | from datetime import datetime
from math import sin, cos, radians
import pygame
class Clock:
def __init__(self, width=640, height=480):
self._width = width
self._height = height
def run(self):
self._startup()
while self._running:
self._input()
self._updat... |
aa22158666ec55bbca8870b3716c4dff500454e4 | Bernie-Mason/Writings | /python_notes/characterCount.py | 247 | 3.65625 | 4 | #!python
#
# Python Script : Bernie Mason
#
message = 'It was a bright cold day in April, and the clocks were striking thirteen'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count) |
98f0e692675fc4517abf2c7dfb94c6d12463f9c8 | katti97/learningdatascience | /missing number in array.py | 356 | 3.578125 | 4 | a=[]
print("Enter the no of test cases: ")
tests = int(input())
for test in range(tests):
print('Enter the array size:')
n = int(input())
print('Enter array elements:')
for i in range(n-1):
no = int(input("num:"))
a.append(int(no))
lisum = int(sum(a))
sum=int(n*(n+1)/2... |
5ed7472af54b4e92e4f8b8160dbdfa42fc8a0c7b | deepabalan/byte-of-python | /functions/function_varargs.py | 720 | 4.15625 | 4 |
# When we declare a starred parameter such as *param, then all the
# positional arguments from that point till the end are collected as
# a tuple called 'param'.
# Similarly, when we declare a double-starred parameter such as **param,
# then all the keyword arguments from that point till end are collected
# as a dict... |
8dd5344dc6cf65b54fa6982dfc8fd7b8989b35e0 | Yurisbk/Codigos-Python | /Replace With Alphabet Position.py | 473 | 3.921875 | 4 | def alphabet_position(text):
alphabet_numbers = []
for letra in text:
if type(letra) == str:
x = ord(letra.lower()) - 96
if '-' in str(x):
pass
else:
alphabet_numbers.append(x)
else:
pass
listToStr = '... |
e2f198706079a03d282121a9959c8e913229d07c | hazydazyart/OSU | /CS344/Homework2/Problem4.py | 959 | 4.15625 | 4 | #Megan Conley
#conleyme@onid.oregonstate.edu
#CS344-400
#Homework 2
import os
import sys
import getopt
import math
#Function to check if a number is prime
#Arguments: int
#Return: boolean
#Notes: a much improved function to find primes using the sieve, this time using the
#square root hint from Homework 1.
def isPrim... |
dc4db3e0b382830e15bd1a9ddb6ee4cf0d2ea51f | hazydazyart/OSU | /CS344/Homework2/Problem5.py | 780 | 3.734375 | 4 | #Megan Conley
#conleyme@onid.oregonstate.edu
#CS344-400
#Homework 2
import os
import subprocess
if __name__ == '__main__':
command = 'who'
# Uses popen module to enter command and pipe output
# I used http://www.saltycrane.com/blog/2008/09/how-get-stdout-and-stderr-using-python-subprocess-module/ as a reference ... |
7ea394326afb19d703362bb50c9b8eea783cd797 | cjwawrzonek/Thesis | /model/inputSpaces.py | 2,803 | 4 | 4 | #!/usr/bin/python
# Filename: inputSpaces.py
import numpy as np
from types import *
import math
class inputSpace:
'''Number of input spaces'''
numSpaces = 0
def __init__(self, size, name="Default Space"):
'''The size must be odd'''
if size % 2 == 0:
raise Exception("The size of the side must be odd")
'''... |
a31f8bf711f1e742ba8432dae8125add1f6a7f27 | lj960912/pythonlx | /test1.py | 137 | 3.921875 | 4 | #循环
while True:
# 输入
story = input("说出你的故事")
if len(story) <= 6:
#输出
print(story)
else:
print("太墨迹了")
|
18444d7fbb2ea124b7065c60cad89489d87b4d02 | rvaccarim/kakuro_combinations | /src/kakuro.py | 4,282 | 3.78125 | 4 | import itertools
import collections
from functools import reduce
from typing import List
KakuroData = collections.namedtuple('KakuroData', 'sum length factors')
combinations: List['KakuroData'] = []
Style = collections.namedtuple('Style', 'text background')
def find_combinations():
# we get all the possible comb... |
d47970e2ac4ecf813fab315e24c80e8117b1cb08 | startling/cytoplasm | /cytoplasm/controllers.py | 1,437 | 3.65625 | 4 | # -*- coding: utf-8 -*-
'''These are the things used in making and using controllers.
'''
import imp
import os
class Controller(object):
"""Controllers take data from some files, do stuff with it,
and write it to the build directory."""
def __init__(self, site, data, destination, templates="_templates"):... |
95a2c110eb814244f2dd7c4a6ac3e9a22bb26ef9 | loochao/lch-emacs-1 | /library/programming/python/lch_python5.py | 347 | 3.828125 | 4 | def make_squares(key, value=0):
"""Return a dictionary and a list"""
d = {key:value}
l = [key,value]
return d, l
def __init__(self, first, second, third, fourth, fifth, sixth):
out = (first + second + third + fourth + fifth + sixth)
try:
print x
except NameError:
print "Something is wrong!... |
7f54290a49d1b50aacd0e17cebd218c741edac23 | cflb/SistemasWEB-I-ifbaiano | /aula2 - manipulando strings/manipulando_string_com_funcao-INCOMPLETO.py | 370 | 3.625 | 4 | def invertePalavra(palavra):
"""
Funcao que retorna parte final da palavra invertida
"""
comprimento = len(palavra)
palavra_invertida = palavra[::-1]
nova_palavra = ""
for letra in palavra_invertida:
if letra == " ":
pass
else:
nova_palavra = nov... |
1ba6bdbe1a38142ed97a360d607c33cc7c61a3bb | JXYXie/kattis | /python/stuck_in_a_time_loop.py | 104 | 3.734375 | 4 | #! /usr/bin/python3
days = int(input())
for i in range(1, days+1):
print("%s Abracadabra" %i)
|
a5b0bcd93668247dbaeaa869de1e1f136aa32f28 | emilyscarroll/MadLibs-in-Python | /MadLibs.py | 593 | 4.21875 | 4 | # Story: There once was a very (adjective) (animal) who lived in (city). He loved to eat (type of candy).
#1) print welcome
#2) ask for input for each blank
#3) print story
print("Hello, and welcome to MadLibs! Please enter the following words to complete your story.")
adj = input("Enter an adjective: ")
animal = inp... |
f41baf09646cb49661b3f54acaf289e49426b9bc | PriyanshiPanchal/python | /Matplotlib/Cinema Entertainment/Cinema_Interface.py | 1,849 | 3.8125 | 4 | import Cinema_Functions
restart = ['Yes', 'YES', 'Y', 'yes']
while restart not in ['NO', 'No', 'no', 'N', 'nO', 'n']:
choice1 = int(input('1.Yearly Collection Of All Branchesn\n2.Quaterly Collection(Gross)\n'
'3.Quaterly Collection(Branch Wise)\n4.Performance of a Branch on given Date Ra... |
4ee92676919794308b6c16d822bac420f819156e | PriyanshiPanchal/python | /Matplotlib/Water Supply Management System/D.py | 185 | 3.515625 | 4 | import matplotlib.pyplot as plt
import csv
import numpy as np
import pandas as pd
df = pd.read_csv("D.csv")
df.head()
df.plot.bar(x='Condition',y=['Before','After'])
plt.show() |
2bfee7b8a357fe2dc8c8b700b6232b156e92bb2c | Volseth/astroevents | /astro.py | 2,937 | 3.53125 | 4 | import datetime
import math
MJD_JD_CONVERSION_VALUE = 2400000.5
LONGITUDE_MINUTES_VALUE = 4.0
DEFAULT_DATE_FORMAT = "%Y-%m-%d"
AUTO_CONVERSION_JD_MJD_VALUE = 1721060.5
def find_corresponding_night(JD: float, Lon: float) -> datetime:
"""
From range [0,AUTO_CONVERSION_JD_MJD_VALUE] JD is treated as MJD (years... |
e12de86b8fb4ac44eec683c173b3493618a03fb0 | ericmburgess/maruchamp | /ramen/action.py | 6,638 | 3.921875 | 4 | """An `Action` is a small, self-contained unit of activity, such as:
* A kickoff
* A front (or other) flip
* Pointing the wheels down while in midair
It also may be an ongoing activity, such as:
* Chasing the ball
* Driving to a particular place on the field
The major distinction between an `Act... |
4f82dfb7a6b951b9a5fed1546d0743adb4109fbd | kkeller90/Python-Files | /newton.py | 335 | 4.375 | 4 | # newtons method
# compute square root of 2
def main():
print("This program evaluates the square root of 2 using Newton's Method")
root = 2
x = eval(input("Enter number of iterations: "))
for i in range(x):
root = root - (root**2 - 2)/(2*root)
print(root)
main()
... |
9b404bc765ffe2809bc713acc67a488018014f2b | roksanapoltorak/tester_school_dzien_7 | /bank_account.py | 891 | 3.96875 | 4 | """ """
class BankAccount():
def __init__(self, balance):
if balance <= 0:
raise ValueError('Balance less than 0.')
self.balance = balance
def withdraw(self, amount):
if self.balance < amount:
raise ValueError('You have too little money.')
if amount < 0... |
35a1dde2f54c79e8bdb80f5cd0b0d727c3ee1e4f | Rurelawati/pertemuan_12 | /message.py | 1,000 | 4.1875 | 4 | # message = 'Hello World'
# print("Updated String :- ", message[:6] + 'Python')
# var1 = 'Hello World!' # penggunaan petik tunggal
# var2 = "Python Programming" # penggunaan petik ganda
# print("var1[0]: ", var1[0]) # mengambil karakter pertama
# print("var2[1:5]: ", var2[1:5]) # karakter ke-2 s/d ke-5
# Nama ... |
ab28ad7aa2a605209e30a81b1d3af97c92a4f21d | Jokmonsimon/holbertonschool-web_back_end | /0x00-python_variable_annotations/3-to_str.py | 264 | 4 | 4 | #!/usr/bin/env python3
"To string Function"
def to_str(n: float) -> str:
"""
--------------
METHOD: to_str
--------------
Description:
Method that returns an string from
a float stored in @n:
"""
return str(n)
|
fc13cdd991c7a08aa3375666edc78c19f77479a7 | Jokmonsimon/holbertonschool-web_back_end | /0x02-python_async_comprehension/0-async_generator.py | 483 | 3.78125 | 4 | #!/usr/bin/env python3
"""Async Generator"""
import random
import asyncio
from typing import Generator
async def async_generator() -> Generator[float, None, None]:
"""
-----------------------
METHOD: async_generator
-----------------------
Description:
Generates and returns a float
... |
f3a58f7aa8c0eefb13ea7ebdeb529254f5d8eb4e | songming05/algorithm_with_python | /pythonProject/fastCampus/psByType/MusicNote.py | 579 | 3.71875 | 4 | # listCase1 = 1 2 3 4 5 6 7 8
# listCase2 = 8 7 6 5 4 3 2 1
# listCase3 = 8 1 7 2 6 3 5 4
# print("Start")
# if int("1") == 1 :
# print("true")
# else:
# print("false")
desc = [8, 7, 6, 5, 4, 3, 2, 1]
asc = [1, 2, 3, 4, 5, 6, 7, 8]
p = list(map(int, input().split(" ")))
# print(p[1])
isAsc = True
isDesc = Tru... |
e7c49138ab5debbf3dd5a951779420e2e2084c38 | jamargolden/Computer-Science-Portfolio | /Bank Security Program/safebank.py | 2,050 | 3.734375 | 4 | class Account:
ID = 1
counter = 0
def __init__(self, initial_deposit):
self.balance = initial_deposit
def withdraw(self, amount):
for i in range(0, 3):
check = int(input("What is your account ID? : "))
if not check == self.ID:
self.counter += 1
... |
7ed4c213849fa8f5656a452ee713b432a2dc91c6 | smspillaz/seg-reg | /segmention_with_channel_regularization/utils/visualization.py | 731 | 3.71875 | 4 | """/segmentation_with_channel_regularization/utils/visualization.py
Helper utiliities for visualizing images and segmentations.
"""
import numpy as np
from PIL import Image
def black_to_transparency(img):
"""Convert black pixels to alpha."""
x = np.asarray(img.convert('RGBA')).copy()
x[:, :, 3] = (255 *... |
7099f0a2ad696634535880c7d8adf5f35578b7f9 | seongjin605/python-algorithm | /leetcode/1.easy/merge-two-sorted-lists.py | 809 | 3.953125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# Base Case
if l1 == None:
return l2
if l2 == None:
... |
adc95eba280979fa1eec9be767a9034db906ab3b | seongjin605/python-algorithm | /leetcode/2.medium/binary-tree-level-order-traversal.py | 837 | 3.78125 | 4 | # Definition for a binary tree node.
import collections
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root: return []
t... |
11063b2725df077b031ac43d38356537d6aef6bf | Prdcc/StudentShapers | /RealFunctions/InvertibilityIntro.py | 2,649 | 3.53125 | 4 | from manimlib.imports import *
def doubling_line(x):
return 2*x
def hidden_flat_line(x):
return 0
def parabola(x):
return x**2
class LinearIsInvertible(GraphScene):
CONFIG = {
"x_min" : -5.5,
"x_max" : 5.5,
"y_min" : -11,
"y_max" : 11,
"graph_origin" : ORIGIN... |
05088e67d2f20f00af0cfb0ad1f81203dec73830 | prachichouksey/Hashing-2 | /409_Longest_Palindrome.py | 1,678 | 3.953125 | 4 | # Leetcode problem link : https://leetcode.com/problems/longest-palindrome/
# Time Complexity : O(n)
# Space Complexity : O(n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Your code here along with comments explaining your approach
'''
Basic approach : ... |
cde6e96b795b24308364326c0985720133129b98 | Colonello56/ICC700 | /src/main/java/codeforces/PetyaAndString.py | 106 | 3.8125 | 4 | a = input().lower()
b = input().lower()
if a < b:
print('-1')
elif a > b:
print('1')
else:
print('0') |
dfbbc780f565a00034a58c4a76f58cbba6d66c6f | Garmider008/kolokvium2 | /36.py | 604 | 3.515625 | 4 | '''''
Знайти суму додатніх елементів лінійного масиву цілих чисел.
Розмірність масиву - 10. Заповнення масиву здійснити з клавіатури.
Гармідер Анастасія 122В
'''''
import numpy as np#импортируем библиотеку нампи
s = 0
b=np.zeros(5,dtype=int)
for i in range(5):#проходимся по елементам масива
b[i] = int(input('Введ... |
f553f8bffae621e2f6ef1207cba8ce523f4421d3 | Garmider008/kolokvium2 | /8.py | 667 | 3.59375 | 4 | '''''
Створіть цілочисельний масив А [1..15] за допомогою генератора випадкових чисел з елементами від -15 до 30 і виведіть його на екран.
Визначте найбільший елемент масиву і його індекс.
Гармідер Анастасія 122В
'''''
import numpy as np
import random
p = 0
h = 0
a = np.zeros(12, dtype=int)
for i in range(12):
a[i... |
7d30f856847d8378a31f668dd6c53c0038df0299 | Garmider008/kolokvium2 | /23.py | 1,099 | 3.609375 | 4 | '''
Знайти суму всіх елементів масиву цілих чисел, які менше середнього
арифметичного елементів масиву. Розмірність масиву - 20. Заповнення масиву
здійснити випадковими числами від 150 до 300.
Гармідер Анастасія 122В
'''
import numpy as np#импортируем библиотеку нампи
import random
u=[]
c=0
b=np.zeros(20,dtype=int)#ини... |
ce5158d7d150c8aebe274404a4087084a5caee29 | Garmider008/kolokvium2 | /2.py | 1,043 | 3.765625 | 4 | '''''
Введіть з клавіатури п'ять цілочисельних елементів масиву X. Виведіть накран значення коріння і квадратів кожного з елементів масиву.
Гармідер Анастасія 122В
'''''
import numpy as np#импортируем библиотеку нампи
b=np.zeros(5,dtype=int)#инициализируем матрицу нулями и присваеиваем типу данных тип данных инт
u=[]
u... |
f2cd13048bd193cd249deb047c2a72e94ca3f00c | Garmider008/kolokvium2 | /38.py | 706 | 3.84375 | 4 | '''
Дані про направлення вітру (північний, південний, східний, західний) і
силі вітру за декаду листопада зберігаються в масиві. Визначити, скільки днів дув
південний вітер з силою, що перевищує 8 м / с.
Гармідер Анастасія 122В
'''
c=0
for i in range(10): #діапазон
b=str(input('направлення'))
j=int(input('швидк... |
15c227a247320477806e3eb2df121380f0386a6a | Garmider008/kolokvium2 | /6 (2).py | 943 | 3.671875 | 4 | '''''
Створіть масив А [1..8] за допомогою генератора випадкових чисел зелементами від -10 до 10 і виведіть його на екран.
Підрахуйте кількість від’ємних елементів масиву.
Гармідер Анастасія 122В
'''''
import numpy as np#импортируем библиотеку нампи
import random
count=0
b=np.zeros(8,dtype=int)#инициализируем масив ну... |
4994ecb59234cb1ab07c1af793617249db19d5cc | Garmider008/kolokvium2 | /42.py | 594 | 3.765625 | 4 | '''
Підрахувати кількість елементів одновимірного масиву, для яких
виконується нерівність i*i<ai<i!
Гармідер Анастасія 122В
'''
import math
e=0
for i in range(10):#діапазон
c=math.factorial(i)# факторіал іерції
d=i*i#квадртат ітерації
b = int(input('Введіть число:')) # масив
print(f'{c} меньше за b')
... |
825790a0a32fec4fae31165076de7de15717d478 | mario21ic/python_curso | /session2/11_listas_operaciones.py | 829 | 3.96875 | 4 | # -*- coding: utf-8 -*-
print "#"*3 +" Listas operaciones "+"#"*3
print ""
print "## Eliminar ##"""
lista = [1, '2', ['tres', 4], '5', '6']
del(lista[2])
print "del(lista[2]):",lista
print ""
print "## Fusionar ##"""
lista = lista + ['x','d'] + ['x','y']
print "lista:",lista
print ""
print "## Copiar ##"""
a = [3, ... |
dcf6a2221c0bdfeefabddcf2e4d88f0fc2c5de39 | mario21ic/python_curso | /session2/14_funciones.py | 1,160 | 3.71875 | 4 | # -*- coding: utf-8 -*-
print "#"*3 +" Funciones "+"#"*3
print ""
print "## Simple ##"""
def funcion_simple():
return "Funcion simple"
print funcion_simple()
print ""
print "## Parametros ##"""
def funcion_parametros(cadena):
if cadena is not None:
return cadena
return False
print funcion_para... |
7a31bc4557b531080976b053c795494b5163e8fb | mario21ic/python_curso | /session1/6_condicionales.py | 835 | 4.09375 | 4 | # -*- coding: utf-8 -*-
print "#"*3 +" Condicionales "+"#"*3
print "if:"
if True:
print "Example if"
print "\nelse:"
valor = int(raw_input("Ingrese valor < 10: "))
if valor > 10:
print "Example if"
else:
print "Example else"
print "\nelif:"
valor = int(raw_input("Ingrese valor < 10 y > 5: "))
if valor >... |
5ef369a1af4bdcb5765dffec6ed6db0458e3625c | C-CCM-TC1028-111-2113/homework-4-shanimucar | /assignments/28Fibonacci/src/exercise.py | 304 | 3.75 | 4 |
def main():
#escribe tu código abajo de esta línea
index = int(input("Enter the index: "))
a = 0
b = 1
n = 1
suma = 0
while n <= index:
n = n + 1
a = b
b = suma
suma = a + b
print(suma)
if __name__=='__main__':
main()
|
3c94682c1e805fe089cc1d1f38442918fef8bcbd | ZzzwyPIN/python_work | /chapter2_exercise/mingyan.py | 135 | 3.625 | 4 | sentence = ' once said,"A person who ... new."'
name = "albert einstein"
print(name.title()+sentence)
name1 = "\tSmith Cooper\t"
print(name1.strip())
|
15fbdde473d21906552ec8add054cb74a09a7ce7 | ZzzwyPIN/python_work | /chapter5/Demo5_2.py | 223 | 3.703125 | 4 | anwser = 17
if anwser != 42:
print("That is not the correct anwser. Please try again!")
StringArr = ['a','h','r','g','n']
print('h' in StringArr)
arr1 = 'k'
if arr1 not in StringArr:
print(arr1.title()+" is a good boy.")
|
bb83df21cb7dc89440d61876288bfd6bafce994d | ZzzwyPIN/python_work | /chapter9/Demo9_2.py | 1,137 | 4.28125 | 4 | class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""返回整洁的描述性信息"""
long_name = str(self.year)+' '+self.make+' '+self.model
return long_name.title()
def read_odometer(s... |
e2c9e4c0ae0bf9d4afe46d0e75343d26784fcc33 | kvartak2/Data-Structures | /LinkedList/singly_circular_linked_list.py | 1,803 | 4.03125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = self
class LinkedList:
def __init__(self):
self.head = None
def printlist(self):
temp=list.head
while(temp.next!=list.head):
print(temp.data)
temp=temp.next
... |
b9b62c981f6e2c7a03d12c6ef483a610971ab94a | hartvigmarton/kattis-exercises | /Python/Spavanac.py | 239 | 3.8125 | 4 | time = input()
time = time.split(" ")
hour = int(time[0])
minutes = int(time[1])
if minutes < 45:
minutes = 60 - abs(minutes - 45)
hour -= 1
else:
minutes = minutes - 45
if hour < 0:
hour = 24 + hour
print(hour,minutes) |
7dd73b9813b37013d35de4e8c9558187375ad90b | hartvigmarton/kattis-exercises | /Python/Datum.py | 216 | 3.859375 | 4 | from _datetime import date
import calendar
testInput = input()
testInput = testInput.split()
day = int(testInput[0])
month = int(testInput[1])
myDate = date(2009,month,day)
print(calendar.day_name[myDate.weekday()])
|
a60763d3c614acf94940564ec264949abf0899ff | Leedong-uk/Programers | /twonumbers-plus.py | 343 | 3.671875 | 4 | def solution(numbers):
answer = []
total=[]
n=len(numbers)
for i in range(0,n):
for j in range (i+1,n):
k=numbers[i]+numbers[j]
if k not in total:
total.append(k)
total.sort()
return total
print(solution([2,1,3,4,1]))
print(s... |
b1975fd0595de181338af2471a9135ba3c29c625 | derekwright29/Chaotic-Dynamics | /hw1/logistic_a.py | 574 | 3.609375 | 4 | import matplotlib.pyplot as plt
def logistic_a(x0, R, m):
"""
First part returns the current state of the system, xn as a function of time, n
"""
cur_state = x0
xn = [cur_state]
n = range(0,m+1)
for i in n[1::]:
next_state = cur_state * R * (1 - cur_state) # logistic equat... |
2785927c8c0c73534d66a3e2742c334e3c9c67bd | rocksolid911/lucky13 | /weight_change.py | 314 | 4.21875 | 4 | weight = int(input("enter your weight: "))
print(f'''your weight is {weight}
is it in pound or kilos ?''')
unit = input("(l)pound or (k)kilogram: ")
if unit.upper() == "L":
convert = weight * 0.45
print(f"you are {convert} kilos")
else:
convert = weight / 0.45
print(f"you are {convert} pound")
|
eac160ec897eed706fd6924ef2c55bef93159034 | AlirieGray/Tweet-Generator | /qu.py | 1,052 | 4.21875 | 4 | from linkedlist import LinkedList
from linkedlist import Node
class Queue(LinkedList):
def __init__(self, iterable=None):
super().__init__(iterable)
def enqueue(self, item):
"""Add an object to the end of the Queue."""
self.append(item)
def dequeue(self):
"""Remove and ret... |
e77a731539b98851b980f44a9c867a3396fe1ba3 | Kantarian/GITHUB | /HT_2/HT_2_4.py | 1,057 | 3.5625 | 4 | #4. Створiть 3 рiзних функцiї (на ваш вибiр). Кожна з цих функцiй повинна повертати якийсь результат.
#Також створiть четверу ф-цiю, яка в тiлi викликає 3 попереднi, обробляє повернутий ними результат та також повертає результат.
#Таким чином ми будемо викликати 1 функцiю, а вона в своєму тiлi ще 3
def show_tree... |
4a19086325066692792bd5e8d6a9fab2349ad5e2 | Kantarian/GITHUB | /HT_3/HT_3_4.py | 596 | 3.828125 | 4 | #4. Написати функцію < prime_list >, яка прийматиме 2 аргументи - початок і кінець діапазона, і вертатиме список простих чисел всередині цього діапазона.
def prime_list (start, end):
list_prime = []
for num in range(start, end + 1):
if num > 1:
for i in range(2, num):
... |
ff5c8aaf1b14f4f40633f2aeb26ed964da679620 | Kantarian/GITHUB | /HT_4/HT_4_2.py | 1,995 | 4 | 4 | #2. Створіть функцію для валідації пари ім'я/пароль за наступними правилами:
# - ім'я повинно бути не меншим за 3 символа і не більшим за 50;
# - пароль повинен бути не меншим за 8 символів і повинен мати хоча б одну цифру;
# - щось своє :)
# Якщо якийсь із параментів не відповідає вимогам - породити виключ... |
09a979bccf9cce42b1fa77cf88cf8fa889037879 | michaelworkspace/AdventOfCode2020 | /day01.py | 1,277 | 4.40625 | 4 | from typing import List
def find_product(inputs: List[int]) -> int:
"""Given a list of integers, if the sum of two element is 2020, return it's product."""
# This is the classic Two Sum problem
# This is not good solution because it is O(n^2)
# for x in INPUTS:
# for y in INPUTS:
# ... |
87cc1e1a2dd9cb48913508d3c5c9d098333345fd | honghainguyen777/Learning | /Harvard_CS50_Introduction_to_CS/CS50-Pset6-master/cash.py | 363 | 3.71875 | 4 | # import get_float from cs50
from cs50 import get_float
user_money = 0
# get positive amount of money from user
while (user_money <= 0):
user_money = get_float("Change owned: ")
# convert money into coin unit
u = user_money * 100
# converting to number of coins
num_coins = u//25 + (u % 25)//10 + ((u % 25) % 10)//5 ... |
da703dbeef7ca35bd961260077dfff5f1b7ac925 | saimadhu-polamuri/leetcode_30_days_challenge_may2020 | /number_complement_day04.py | 819 | 3.546875 | 4 |
class Solution:
def findComplement(self, num: int) -> int:
if num == 0:
number= self.bit_complement(num)
else:
remiders = list()
while num >= 1:
reminder = num % 2
num = num // 2
remiders.append(self.bit_compleme... |
911a3f3cefa2ad3f23954e3d1b62b64470d6ed5b | saimadhu-polamuri/leetcode_30_days_challenge_may2020 | /majority_element_day06.py | 1,136 | 3.515625 | 4 | __author__ = "saimadhu.polamuri"
import math
class Solution:
# Approach 01
def majorityElement(self, nums) -> int:
array_len = len(nums)
if array_len > 0:
majority_element = nums[0]
majority_element_frequency = 1
if array_len > 1:
hash_map ... |
53016fdc1655182955e960160d4e70800dd44a9f | saimadhu-polamuri/leetcode_30_days_challenge_may2020 | /k_closest_points_to_origin_day30.py | 754 | 3.5625 | 4 | __author__ = "saimadhu.polamuri"
import math
class Solution:
def kClosest(self, points, K):
total_points = len(points)
distance_dict = {}
for i in range(total_points):
distance_dict[i] = self.get_distance_with_origin(points[i])
# sort the dictionary keys by values
keys = sorted(distanc... |
cee847cc2834b5fc5d1adca2cafcf9631621d449 | saimadhu-polamuri/leetcode_30_days_challenge_may2020 | /sort_characters_by_frequency_day22.py | 654 | 3.75 | 4 | __author__ = "saimadhu.polamuri"
class Solution:
def frequencySort(self, s):
# Frequency dict
frequency_dict = {}
for element in s:
if element in frequency_dict:
frequency_dict[element] += 1
else:
frequency_dict[element] = 1
... |
3ecb2d008a9e9048f8f0305deae58ae363e47da6 | huixuant/adventofcode20 | /day6/part1.py | 372 | 3.71875 | 4 | def main():
with open('input', 'r') as file:
answers = [line.rstrip() for line in file]
answers.append('')
group = ""
count = 0
for ans in answers:
if (ans == ''):
count += len(set(group))
group = ""
else:
group += ans
pr... |
0ad185da2701617e9580000faad35f2c31df8c9a | YasmineCodes/Interview-Prep | /recursion.py | 2,641 | 4.3125 | 4 | # Write a function fib, that finds the nth fibonacci number
def fib(n):
assert n >= 0 and int(n) == n, "n must be a positive integer"
if n == 1:
return 0
elif n == 2:
return 1
else:
return fib(n-1) + fib(n-2)
print("The 4th fibonacci number is: ", fib(4)) # 2
print("The 10th ... |
5a7de5bcb76641823ad023af5b1c9fc14788e4a5 | samkimuel/problem-solving | /코테기출/2020카카오인턴십/키패드누르기v2.py | 1,318 | 3.6875 | 4 | """
@file 키패드누르기v2.py
@brief 2020 카카오 인턴십 1번
@desc 구현
두 번째 풀이
- 키패드 위치를 자료구조로 저장 (리스트, 딕셔너리)
- 키패드 위치
"""
numbers = [1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5]
hand = "right"
def solution(numbers, hand):
answer = ''
# 키패드 0~9의 위치
position = [[1, 3],
[0, 0], [1, 0], [2, 0],
[0... |
3d3c2ea76d310e4dafa304e356b8233f440990a4 | samkimuel/problem-solving | /Programmers/K번째수.py | 225 | 3.546875 | 4 | """
@file K번째수.py
@brief 정렬 - Level 1
@desc
"""
def solution(array, commands):
answer = []
for i in commands:
arr = sorted(array[i[0]-1:i[1]])
answer.append(arr[i[2]-1])
return answer
|
1e0219ee39944e82af499dfd1f1434582e020b56 | misleadingTitle/ProvaBot | /MembroBot/MembroBot/MembroLogic.py | 172 | 3.640625 | 4 | import re
keywords = ['cazzo']
def containsKeyword(inputString):
if re.match(r'.*?\bcazzo\b.*?', inputString):
return True
else:
return False
|
044bca938380e92f9de20b91eb94984d3749ae57 | LuisAlbertoZepedaHernandez/Mision_02 | /misDatos.py | 578 | 3.625 | 4 | # Autor: Luis Alberto Zepeda Hernandez, A01328616
# Descripcion: Elabora un algoritmo y escribe un programa que muestre: Nombre completo, matricula, carrera, escuela de procedencia, y una breve descipcion presonal.
# Escribe tu programa después de esta línea.
print("Nombre:")
print("Luis Alberto Zepeda Hernandez")
p... |
81fb27b95ba0d74fcf80132f50c78f1d693baaeb | toledoneto/Python-TensorFlow | /02 TensorFlow Basics/10. Saving and Restoring Models.py | 2,019 | 3.640625 | 4 | import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
np.random.seed(101)
tf.set_random_seed(101)
# Full Network Example
#
# Let's work on a regression example, we are trying to solve a very simple equation:
#
# y = mx + b
#
# y will be the y_labels and x is the x_data. We are trying to figure o... |
0cc1a20a886dec2e2d65d8187a6eb1e6f92814b6 | Abhi7865/python-projects | /cal.py | 1,101 | 4 | 4 | import numpy
def add():
num1=int(input("enter number 1:"))
num2 = int(input("enter number 2:"))
return num1+num2;
def sub():
num1 = int(input("enter number 1:"))
num2 = int(input("enter number 2:"))
return num1-num2;
def multi():
num1 = int(input("enter number 1:"))
num... |
e3382c4e700995d5decef3245d859372123decae | b21727795/Programming-with-Python | /Quiz2/quiz2_even_operation.py | 596 | 4.3125 | 4 | import sys
def choose_evens(input_string):
evens = [int(element) for element in input_string.split(',') if(int(element)> 0 and int(element) % 2 == 0) ]
all_numbers = [int(element) for element in input_string.split(',') if int(element)> 0]
even_number_rate = sum(evens) / sum(all_numbers)
print("Ev... |
983d13c3603604f8a5274bffd019be4410cf025d | Konan33/Word_Processing_Service | /main.py | 1,585 | 3.96875 | 4 | #Intro
print('*'*56)
print('* CHÀO MỪNG QUÝ KHÁCH ĐÃ ĐẾN VỚI DỊCH VỤ XỬ LÝ VĂN BẢN *')
print('*'*56)
OldString = input('Quý khách vui lòng cho chúng tôi xem văn bản cần xử lý: ')
#Lại là Intro
while True:
print('-'*40)
print('Chúng tôi có những dịch vụ sau đây\n1. Trộm long tráo phụng\n2. Triệu hồi Thánh Gióng\n... |
64f6b88bd332f6ca317d0a22ada0ce2f045f9035 | VeenaArv/PythonPractice | /denominations.py | 2,724 | 3.515625 | 4 | import random
from itertools import combinations
def getExactChangeNum(d):
# d1,d2,d3,d4 is the 4 denominations from least to greatest
changes = []
# fill array with the amt of change itself
for i in range(239):
changes.append(i)
# change array to reflect actual exact change num
for j... |
aa92573b123c0f334eca8304adae5b1410f108e5 | Xia-Sam/hello-world | /rock paper scissors game against computer.py | 1,714 | 4.3125 | 4 | import random
rand_num=random.randint(1,3)
if rand_num==1:
com_side="rock"
elif rand_num==2:
com_side="paper"
else:
com_side="scissors"
i=0
while i<5:
print("You can input 'stop' at anytime to stop the game but nothing else is allowed.")
user_side=input("Please input your choice (R P S stands for r... |
d004b64afb686aa77878e871a9a0ccbafcb21414 | ipavel83/Python | /006fileRead.py | 386 | 3.796875 | 4 | #py3.7
from sys import argv
script, filename = argv[0], argv[1]
print(f"args: {argv}")
txt = open(filename)
print(f'file named "{filename}" contents:')
print(txt.read())
print(f'file named "{filename}" contents by line by line in list:')
txt = open(filename)
print(txt.readlines())
print("type the filename to read a... |
bb0cedf5307d70e5dc8bbc712c890dccc0e7dd37 | ipavel83/Python | /014with.py | 1,364 | 3.859375 | 4 | #!/usr/bin/env python3
#py3.7
with open('hello_foo.txt', 'w') as f:
f.write('hello, world!')
#same as:
# f = opent('hello_foo.txt', 'w')
# try:
# f.wtite('hello, world')
# finally:
# f.close()
with open('hello_foo.txt', 'r') as f:
print(f.read())
print()
#more advanced... |
d3d4f238cba24f0af180985c4f13d5661a0685b5 | ipavel83/Python | /011dictionary.py | 1,861 | 3.625 | 4 | #py3.7
print( {True: 'yes', 1: 'no', 1.0: 'maybe'} ) #prints {True: 'maybe'}
#dictionary creation overwrites values of same key, key is not updated due optimization
#bool is subclass of int, so True is 1
print(True == 1 == 1.0 ) #True
print( (hash(True), hash(1), hash(1.0)) ) #(1, 1, 1)
####back to dict :)
... |
36741092d47d028bac059ff0c10e1eb2449f58fe | 2pushkaraj3/AILab | /Lab2/main.py | 588 | 3.5 | 4 | from enviroment import next_move
import random
from PriorityQueue import PriorityQueue
if __name__ == '__main__':
myQueue = PriorityQueue()
start = list(range(0,9))
random.shuffle(start)
start2 = list(range(0,9))
random.shuffle(start2)
print("start+>",start)
myQueue.insert(start,12)
... |
0e1d92a3893b3b1bf2b2b820da11fd5949278629 | GOD-A01375315/Tarea-05 | /Divisbles.py | 335 | 3.5 | 4 | #encoding: UTF-8
#Autor: Genaro Ortiz Durán
#Descripción: Escribir una función que calcule cuántos cnúmeros de 4 dígitos son divisibles entre 29.
def calcularNumeros():
n=0
for k in range(1000,100000):
if k%29==0:
n+=1
return k
def main():
print("Los numeros divisibles son:",calcul... |
4d86d3e307f5ad156be080c829c0917e85669c7c | aravindnatarajan/InsightProject | /reanalyze.py | 978 | 3.921875 | 4 |
import sys
def bubbleSort(dummy,A): # Bubble Sort Algorithm
for i in range(len(A)):
for j in range(i+1, len(A)):
if A[j] > A[i]:
A[j],A[i] = A[i],A[j]
dummy[j],dummy[i] = dummy[i],dummy[j]
return dummy,A
listWords = [(word.split())[0] for word in open("weights.dat")]
listWeig... |
8b7fd28162687ac356f9e21383bbd9d2c0027dbf | jbjulia/SDEV300 | /Project2/lottery.py | 1,866 | 4.09375 | 4 | import sys
from random import randint
def display_menu():
menu_items = [
"[ 1 ] Generate 3-digit lottery number",
"[ 2 ] Generate 4-digit lottery number",
"[ x ] Quit (Exit application)"
]
print("Please select an option from the following menu:\n") # Print directions
for ite... |
7801cf25e5a1f6eb4060288b9df814c22485272b | Merovizian/Aula13 | /Desafio056.py | 2,074 | 3.515625 | 4 | print(f"\033[;1m{'Desafio 056 - Nome idade e sexo':*^70}\033[m")
masculino_database = ('m','M','Masculino','MASCULINO')
masculino_have = 0
feminino_have = 0
feminino_database = ('f','F','Feminino','FEMININO')
quantidade = int(input("Quantas pessoas cadastrar: "))
media = 0
homem_velho = 0
homem_velho_aux = 0
mulher_men... |
802016a285b2ed02a03e154ab1f16cedfa401532 | Merovizian/Aula13 | /Desafio054.py | 1,639 | 3.921875 | 4 | from datetime import datetime
import calendar
print(f"\033[;1m{'Desafio 054 - Pessoas que atingiram Maioridade':*^70}\033[m")
quant = int(input("Quantas pessoas: "))
maioridade = 0
menoridade = 0
for c in range(0, quant):
nascimento = input("Digite a sua idade (dd/mm/aaaa): ")
dia = int(nascimento[0:2])
me... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.