blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ae4cb10b6dce49da5611b08363f75c5f57615bfc | vaishu1312/Python-lab | /ex 6/mat add.py | 567 | 4.1875 | 4 | # Function - Matrix Addition
def add(MA, MB):
r=len(MA)
c=len(MB)
M = []
for i in range(0,r):
M.append([])
for j in range(0,c):
ele = MA[i][j] + MB[i][j]
M[i].append(ele)
return M
a=[[1,2,3],[4,5,6],[2,8,9]]
b=[[6,7,8],[2,4,0],[1,2,8]]
ra=len(a)
ca=len(a[0])
... |
e4b99ef133899ecb5ea4331a97c9ec171ce202e7 | artermi/Solution_of_Some_Problem | /Sherlock_and_Permutations/solution.py | 1,006 | 3.5 | 4 | #!/bin/python3
import os
import sys
# Complete the solve function below.
def fast_pow (Num,Pow,Mod):
ans = 1
base = Num
while Pow > 0:
if Pow % 2 == 1:
Pow = Pow -1
ans = (ans * base) % Mod
Pow = Pow / 2
base = (base * base) % Mod
return int(ans % Mod)... |
767277257093555573edfbbea053025525631be5 | idane19-meet/EAT_IT | /eat_it.py | 2,149 | 4.0625 | 4 | import turtle
def menu():
x = str(input('would you like to start the game? \n (YES/NO) \n would you like to quit the menu bar? \n (QUIT) \n *PLEASE USE CAPITAL LETTERS \n YOUR ANSWER: '))
if x == 'NO' or x == 'QUIT':
quit()
elif x == 'YES':
PRINT('')
menu()
turtle.penup()
#bird = turtle.clo... |
6d55ea921f182b3b82622705339effdc44b159b0 | rabahbedirina/Cisco-Python | /collatz.py | 614 | 3.921875 | 4 | # Scenario
# In 1937, a German mathematician named Lothar Collatz formulated an intriguing hypothesis (it still remains unproven) which can be described in the following way:
# take any non-negative and non-zero integer number and name it c0;
# if it's even, evaluate a new c0 as c0 ÷ 2;
# otherwise, if it's odd, evalu... |
181d65fbbc241dd1e7933223bea0bef0b34a9c61 | rajmohanram/PyLearn | /001_Python_101/03_user_input.py | 310 | 3.9375 | 4 | # This module will ask input from you and assign it to a variable
# define a variable and collect user input
your_input = input("Enter the VLAN ID:")
# input collected from user is always of type : string
print("Your input is {}".format(your_input))
print("Your input is of type {}".format(type(your_input))) |
4d3409938d7259bf749826d71a9dffba1ad2246f | KhvostenkoIhor/khvostenko | /Lesson_14/dz_14_3_1.py | 657 | 4.0625 | 4 | from random import randint
def task_3(n):
t_ind = []
t_elem = []
t1 = tuple([randint(0, 3) for i in range(n)])
t2 = tuple([randint(0, 3) for i in range(n)])
t3 = tuple([randint(0, 3) for i in range(n)])
print("Initial tuples", t1, t2, t3, sep="\n")
for a, b in enumerate(t1):
for i, j... |
2b4ac27e866217b62fc0ec958cce0ead20fb49b2 | mrwilsun/AITI_Homework | /day6/variables&collections.py | 1,005 | 4.1875 | 4 | # Variables and collections
print ("I'm Python. NIce to meet you!")
user_input =input("Enter some data:")
some_var =5
print("yahoo!") if 3>2 else print (2)
li=[4,5,6]
li.append(1)
li.append("banku")
li.append(9)
print(li)
li.pop()
print(li)
li[0]=42
print(li)
print(li[-1])
print(li[1:3])
print(li[2:])
print(... |
b2f269221a7cd011632cbc070745486843b33e0c | jccherry/Data-Structures-And-Algorithms | /03-Dynamic Arrays, Linked Lists, Python List Implementation/John/r-5.7.py | 794 | 3.765625 | 4 | #from problem r-5.7 in goodrich
#algorithm to find repeated integer
from random import randint
#generate array of integers from 1 on
def generateArray(length):
array = []
for i in range(1,length):
array.append(i)
return array
def insertRepeatedDigit(array):
index = randint(0,len(array)-1)
... |
553210b69a2a512a119189dd30bb593a26438c01 | divyasanchana/divyastrove | /letter_or_number.py | 118 | 3.875 | 4 | x=raw_input()
a=x.isdigit()
if(a==True):
print("it is a number")
else:
print("It is a letter")
|
2bba6c8d70ac31fb12a0acd585443ff8143448d3 | Tahanaviwala/python_projects | /median/median.py | 867 | 3.609375 | 4 | D8 = { 'Italy': 17,
'UK': 39,
'USA': 29,
'Germany': 16,
'France': 8,
'China': 3,
'Romania': 1,
'South Korea': 5,
'Netherlands': 3,
'Japan': 15,
'Russia': 3,
'Australia': 1,
'Sweden': 3,
'Taiwan': 1,
'India': ... |
3530627171cda52a44e0da97b3cccce6c714448d | imn00133/PythonSeminar18 | /Users/JUN/BMI_calculator/BMI_calculator.py | 375 | 3.90625 | 4 | weight = (float)(input("몸무게를 입력해주십시오.: "))
height = (float)(input("키를 입력해주십시오.: "))
BMI = abs(weight/(height*height))
if BMI<18.5:
print("저체중")
elif BMI<23:
print("정상")
elif BMI<25:
print("과체중")
elif BMI<30:
print("경도비만")
elif BMI<35:
print("중증도비만")
else:
print("고도비만") |
8cd683e02a73d278cf299c499a3b0bfd5856ec88 | mycks45/DS | /Queue.py | 374 | 3.703125 | 4 | from collections import deque
class Queue:
def __init__(self):
self.que = deque()
def enqueque(self, value):
self.que.appendleft(value)
def dequeque(self):
return self.que.pop()
queue = Queue()
queue.enqueque('harshad')
queue.enqueque('sam')
queue.enqueque('anfu... |
d781bad04dfcdaabb46587b46d86251735199677 | SayaliBaxy/Python | /Palindrome_string.py | 306 | 4.125 | 4 | def main():
s= input("enter a string")
print("The palindrome is:"+ str(palindrome(s)))
def palindrome(s):
if s[::1]==s[::-1]:
print("String is a palindrome")
else:
print("string is not a palindrome")
return s
if __name__=='__main__':
main()
|
6dbdda12c2480c32519acb1381ea5bfc317f7023 | RockmanJim/python-study | /python基础/python语法基础/单例模式/02-创建单例对象.py | 375 | 3.78125 | 4 | class Dog(object):
__instance = None#用这个私有变量存放单例的对象
def __new__(cls):
if cls.__instance == None:
cls.__instance = object.__new__(cls)#cls.__instance?难道还有self.__instance?
return cls.__instance
def __del__(self):
print("del啦!")
d1 = Dog()
d2 = Dog()
print(id(d1))
print(id(d2))
#print(dir(d1))
#print(... |
05d9bdc9d3df94764fcd40277742855595a38431 | mukeshkrishna/datastructures | /Stack.py | 765 | 3.84375 | 4 | class myStack():
def __init__(self):
self.stackList = []
def isEmpty(self):
return len(self.stackList) == 0
def top(self):
if(self.isEmpty()):
return None
return self.stackList[-1]
def push(self,value):
self.stackList.append(value)
... |
b1fa65ad60e58fecaf8b6f53ec7ffa2146951cc8 | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/mtlasi002/question2.py | 188 | 3.921875 | 4 | #ASSIGNMENT_4
#QUESTION_2
#ASIL_MOTALA
#MTLASI002
x=eval(input("Enter the height of the triangle:\n"))
for i in range(1,2*x,2):
print(" "*((2*x-1-i)//2),end="")
print("*"*i) |
97703ae7142b3e2a536b71ff4b14b265899852b2 | amit-dhole/LeetCode-in-Go | /Algorithms/0234.palindrome-linked-list/palindrome-linked-list.py | 823 | 3.859375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
# 迭代
if not head:
return None
# 找到反转段
cur, ... |
9e09fd56d517c38844cd4426a823109ce3edc76d | RinkuAkash/Python-libraries-for-ML | /Numpy/19_identity_matrix.py | 263 | 3.96875 | 4 | '''
Created on 20/01/2020
@author: B Akash
'''
'''
problem statement:
Write a Python program to create a 3-D array with ones on a diagonal and zeros elsewhere.
Expected Output:
[[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 0. 1.]]
'''
import numpy as np
print(np.identity(3)) |
d5cb3ef7888298230d71282ad3416d03d03e5f7d | DM865/TSP | /src/enumeration.py | 580 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 15 18:38:45 2018
@author: marco
"""
from data import *
from solutions import *
def alltours_tsp(cities):
"Generate all possible tours of the cities and choose the shortest tour."
return shortest_tour(alltours(cities))
alltours = ite... |
535155b88e0af4ad9d55f504f127f8b8025ba9bf | gabriel-torres3077/curso-em-video-exercicios | /exercicios/desafio039.py | 656 | 4.15625 | 4 | """
Faça um programa que
leia o ano de nascimento
de um jovem e informe de
acordo com sua idade:
-Se ele ainda vai se alistar ao serviço militar
-Se é a hora de se alistar
-Se já passou do tempo do alistamento
o programa tambem deve
mostrar o tempo que falta ou
passou do prazo
"""
year = int(input('Ensira o seu ano d... |
61a0f5137ccda2a178a309a2d78c42e1cb3fe887 | kindeep/kattissolutions | /thegrandadventure.py | 805 | 3.578125 | 4 | cases = int(input())
def check(path):
bag = []
for c in path:
if c == ".":
pass
elif c == "$":
bag.append("$")
pass
elif c == "|":
bag.append("|")
pass
elif c == "*":
bag.append("*")
pass
... |
8b77b887008f68336620217d2678cd8cd67a2f14 | Hitesh20/OpenCV-Practice-Learning | /geometric_files.py | 540 | 3.5 | 4 | import numpy as np
import cv2
#img = cv2.imread('s1.png', 1)
#3args---height, width, 3
#this gives black image
img = np.zeros([512, 512, 3], np.uint8)
img = cv2.line(img, (0,0), (255,255), (255, 0, 0), thickness=10)
img = cv2.arrowedLine(img, (255,0), (255,255), (255, 155, 0), thickness=10)
img = cv2.rectangle(im... |
9acbf2802c97ebb660b120fa2e0f3409632815af | Jimmyopot/JimmyLeetcodeDev | /Easy/duplicate_array.py | 1,219 | 3.65625 | 4 | # soln 1
class Solution(object):
def removeDuplicates(self, nums):
n = len(nums)
if n <= 1:
return n
i = j = 1
while i < n:
if nums[i] != nums[i-1]:
nums[j] = nums[i]
j += 1
i += 1
return j
l =... |
a659229ab9786994ef09ef716e3219e2814b92c0 | neverkor/labi | /python/laba2.py | 1,017 | 3.9375 | 4 | from math import tan, asin
a = float(input('Введите А: '))
x = float(input('Введите Х: '))
choose = int(input('1 функция G\n2 функция F\n3 функция Y\nВыберите функцию: '))
if choose == 1:
try:
g = 10 * (-45 * a ** 2 + 49 * a * x + 6 * x ** 2) / 15 * a ** 2 + 49 * a * x + 24 * x ** 2
print('G =', g)... |
866b33e753516f2619d51bd61a4c3260032f709e | nayyanmujadiya/ML-Python-Handson | /src/ml/svm_cancer_data.py | 1,776 | 3.5625 | 4 | '''
download dataset from
https://www.kaggle.com/uciml/breast-cancer-wisconsin-data
'''
'''
Step 1: Load Pandas library and the dataset using Pandas
'''
import pandas as pd
dataset = pd.read_csv('Cancer_data.csv')
X = dataset.drop('Diagnosis',axis=1)
y = dataset['Diagnosis']
print(X)
print(y)
from sklearn.model_sel... |
c6752f51afa010dc4dc13c6ba695402de1c1a500 | aswin191993/ProbleSolving_with_Algorithms_and_Data_Structures | /chapter2/ex2.py | 481 | 3.90625 | 4 | class stack:
def __init__(self):
self.items=[]
def __str__(self):
return "stack"
def emptstr(self):
if self.items == []:
return True
else:
return False
def push(self,item):
return self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
fnl=len(self.items)
return ... |
3a061047c931e1f4b14edbe88c92d30c37cd8c34 | keviv202/Python-Code | /Reverse Vowels of a Strings.py | 592 | 3.5625 | 4 | class reverse_vowel:
def rev_vow(self,s):
a=['a','e','i','o','u']
b=[]
c=[]
d=[]
for i in s:
b.append(i)
#print(b)
for i in range(len(s)):
if s[i] in a:
c.append(s[i])
b[i]='!'
k = len(c)
... |
6bac60ebae33a84f92523d640d8790a5443d094d | Tatiana-Yatna/numbers | /src/exercises/current age.py | 140 | 3.953125 | 4 | born=int(input('What year were you born?'))
year=int(input('What is it year now?'))
def age(born):
return year-born
print(age(born))
|
544bc2d13c873cca455d3999f4dced6c328208aa | nvanwinden/Advent-of-Code-2020 | /day12/part01.py | 831 | 3.625 | 4 | f = open('input.txt', 'r')
data = f.readlines()
f.close
data = [line.strip() for line in data]
def change_dir(action, angle, value) :
if action == 'L' :
angle -= value
elif action == 'R' :
angle += value
return (angle)
def get_manhattan_dist(angle) :
y = 0
x = 0
for line in data :
action, value = line[0]... |
c7515e8153958a6efa3ebee7c640d4fc2867f9b3 | cshintov/python | /think-python/ch15.Classes/ex4_draw.py | 3,596 | 4.375 | 4 | '''
exercise 15.4 Draw Rectangle and Circle
'''
from swampy.World import World
class point(object):
'''a point with attributes
x and y coordinates'''
class rectangle(object):
'''a rectangle with attributes
leftbottom corner,height,width'''
class circle(object):
'''a circle with attributes
center ... |
0a8f3c7d65a1d440338745d085287704dec35049 | palhana/palhana | /iterable&iterator.py | 132 | 3.890625 | 4 | import itertools
x=[1,2,3,4]
y=iter(x)
next(y)
next(y)
for i in y:
print(i)
for i in y:
print(i)
for i in y:
print(i)
|
db776ce316a00082646fb963595d499e1763057c | pjs3065/Python_Practice | /three exception.py | 114 | 3.828125 | 4 | sum = 0;
for number in range(1, 101):
if number % 3 == 0:
continue
sum += number
print(sum); |
c965325de7230635fab11fc86fa57da89ad9e202 | gashawdemlew/holbertonschool-higher_level_programming-1 | /0x04-python-more_data_structures/6-print_sorted_dictionary.py | 138 | 4.28125 | 4 | #!/usr/bin/python3
def print_sorted_dictionary(my_dict):
for i, j in sorted(my_dict.items()):
print("{:s}: {}".format(i, j))
|
1bcc07924f16dcc21166a37d500cdc2aa76aa610 | yamogi/Python_Exercises | /ch04/no_vowels.py | 634 | 4.5625 | 5 | # No Vowels
# Demonstrates creating new strings with a for loop
message = input("Enter a message: ") # user enters a message
new_message = "" # initialise empty string for new message
VOWELS = "aeiou" # this is a constant, holding possible vowels
print() # extra newline
for letter in message: # iterate through every ... |
e29ec34ec8c7e17be197ff923ddfe03ac1742350 | Oleh1989/PythonStudy | /SecondApp.py | 223 | 4.125 | 4 | # logical constructions
a = input("Enter first number ")
b = input("Enter second number ")
if int(a) > int(b):
print("{a} > {b}", a, b)
elif int(a) < int(b):
print("{a} < {b}",a,b)
else:
print("{a} = {b}",a,b) |
d6c541871a0cb8256c87f6329986f7aebed9ffcd | MelodyC117/Board-Game | /main.py | 18,143 | 3.5625 | 4 | """
AUTHOR: Melody Chen @ UR CSC 442 (31620871 | mchen73@ur.rochester.edu)
"""
import random
import sys
from copy import deepcopy
import time
class Board:
"initilize board, index list and position maps for both players"
def __init__(self):
self.board = [0, 4, 4, 4, 4, 4, 4,
... |
9be8cf3c82e4bd6926122f2852e259a05c0f9543 | ruben69695/python-course | /Fase 4 - Temas avanzados/Tema 14 - Bases de datos con SQLite/Leccion 03 - Extra/test.py | 1,685 | 4 | 4 | import sqlite3
connection = sqlite3.connect("usuarios.db")
cursor = connection.cursor()
# Create a table with primary key autoincrement and unique columns and not nulls
cursor.execute('''
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
dni CHAR(9) UNIQUE,
name VARCHAR(100) NO... |
7944903e0421ab73ffe7b442d4d2e4cf1441c8b7 | SombraRNZ/PKMN | /pkmn/base.py | 1,350 | 3.546875 | 4 | from typing import Typing
class Base:
def __init__(self, index, name, attack, defense, sp_attack, sp_defense, speed, health, type1, type2 = Typing.Null):
self.index = index
self.name = name
self.attack = attack
self.buff_attack = 0
self.defense = defense
self.buff_defense = 0
self.sp_attack = sp_attack
... |
09c2bd5114891dab7192caea241e56134650e1f6 | D4nfire/Dissertation | /Python_Code/partofalgorithm.py | 1,046 | 3.796875 | 4 | connectedList = []
while (j < len(geneList)):
if (i != j):
#print("This part works") # proof that the idea works
#print(geneList[i])
#print(geneList[j])
if(bool(set(geneList[i]) & set(geneList[j]))):
if(geneList[i] not in connectedList):
connectedList.append(geneList[i])
G.add_edge(geneList[i-1],ge... |
fd57bd6c61cde47627a733f5e230f2b77fa87e81 | idrissi51/Alarm_Clock | /Alarm_clock-v_1.0.py | 1,669 | 3.53125 | 4 |
from tkinter import *
import time
import datetime
import winsound
def alarm(set_alarm_timer):
while True:
time.sleep(1)
current_time = datetime.datetime.now()
now = current_time.strftime("%H:%M:%S")
date = current_time.strftime("%d:%m:%y")
print("The Set Date is:", date)
... |
0bbaa11987b798fe029b56f726d9b59738bded31 | daniel-reich/turbo-robot | /vjkRfBeJtmisqmY99_6.py | 2,548 | 4.25 | 4 | """
You are given a list of 9 7-letter words. You are also given the middle letter
of one of the 6 of them which fit together in a sort of star pattern as
follows:
Word 1 fits diagonally downwards from left to right. Its 1st letter is the
last letter of word 5; 3rd letter the 5th of word 3;last letter the last
lett... |
528ebeee48f824344429ee7d7548986592b5e6a5 | YorkShen/LeetCode | /python/week9/102.py | 900 | 3.84375 | 4 | from collections import deque
# Definition
# for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List... |
5a625cbf4cd0b87e855e9888449fd161d51e1554 | clee6288/PythonProjects | /String_StringMunipulation/hangman.py | 3,274 | 4.34375 | 4 | """
File: hangman.py
Name: Chris Lee
-----------------------------
This program plays hangman game.
Users sees a dashed word, trying to
correctly figure the un-dashed word out
by inputting one character each round.
If the user input is correct, show the
updated word on console. Players have N_TURNS
chances to try and w... |
53ca6d372ff357ac9b96885b731df494a8b0578b | AdamZhouSE/pythonHomework | /Code/CodeRecords/2708/58778/302521.py | 543 | 3.59375 | 4 | s=input()
d=input()
f=input()
h=input()
try:
g=input()
except EOFError:
pass
try:
x=input()
except EOFError:
pass
if(s=='3 5 7' and d=='C 1 2' and f=='C 2 2' and h=='W 1 2'):
print('3\n3\n0')
elif s=='3 5 7' and d=='C 1 5' and f=='C 2 2' and h=='W 1 2' and g=='C 3 2' and x=='W 1 2':
print('2\n2\... |
81c63b039851bedb973b5cb641d11f66fd72a4a0 | Zhangmingyang-Su/Data-Structure-and-Algorithm | /Binary Search.py | 2,733 | 3.96875 | 4 | # Binary Search and Follow Up
# 1 classical binary search
# eg. input -> [1, 3, 5, 7, 9], target = 5 output -> 2
def binary_search(array, target):
if not array:
return None
left, right = 0, len(array) - 1
while left < right:
mid = left + (right - left) // 2
if array[mid] < target:
left = mi... |
5f8debdf98d95037f7b96862ff358c3c36c765f8 | leon997/demsar_naloge | /konkurenca.py | 544 | 3.71875 | 4 | """Konkurenca ne spi. Trgovina za vogalom se je odločila za posebno ponudbo: kupec lahko kupi
toliko izdelkov, kolikor želi. Napiši program, ki blagajnika vpraša, koliko izdelkov je v košarici,
nato vpraša po cenah teh izdelkov in na koncu izpiše vsoto.
Število izdelkov: 3
Cena artikla: 2
Cena artikla: 4.5
Cena artikla... |
a4dcd1818c63f9174e31438caf63c945f610b5f8 | ackers93/code-challenge | /python/addReversedLinkedLists.py | 1,487 | 3.953125 | 4 | 6
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
l1_list = []
l2_list = []
# need to iterate over both li... |
1e67f72abf75e5cd7361562069f2634511a35f79 | Aasthaengg/IBMdataset | /Python_codes/p02261/s516602721.py | 1,057 | 3.90625 | 4 | def bubbleSort(A, N):
flag = 1
while flag:
flag = 0
for j in range(N-1, 0, -1):
if A[j][1] < A[j-1][1]:
A[j], A[j-1] = A[j-1], A[j]
flag = 1
print(*A)
return A
def selectionSort(A, N):
for i in range(N):
minj = i
for j in ... |
99f91d8525321d5dce9a1122b8c2e4800aac2ab3 | julife12/taller | /punto_51.py | 131 | 3.953125 | 4 | a=int(input("digite la cantidad de numeros "))
for i in range(1,a+1):
if i%2==0:
print(i*-1)
else:
print(i) |
5fc0dbfd6b0617c40092e4541b2988473d149d28 | n-man123/HackerRank | /Camel_Case | 108 | 3.796875 | 4 | #!/bin/python3
import sys
import re
s = input().strip()
mylist = re.split("[A-Z]+", s)
print(len(mylist))
|
5b5c449e17f2bc544d434789348c444cc2de74fe | abespitalny/CodingPuzzles | /Leetcode/minimum_time_difference.py | 877 | 3.6875 | 4 | '''
Given a list of 24-hour clock time points in "HH:MM" format, return the minimum minutes difference between any two time-points in the list.
'''
from leetcode import *
class Solution:
# Sorting approach
# Time: O(n*log(n))
# Space: O(n)
def findMinDifference(self, timePoints: List[str]) -> int:
... |
fb54afc0ed2776f583d676a570d74775b1ad2abe | showerhhh/leetcode_python | /t7.py | 450 | 3.609375 | 4 | class Solution:
def reverse(self, x: int) -> int:
sign = 1
if x < 0:
sign = -1
x = -x
y = 0
while x != 0:
y = y * 10 + x % 10
x = int(x / 10)
y = sign * y
if not -pow(2, 31) <= y <= pow(2, 31) - 1:
return 0
... |
8745ac0967526f82f3ba0875b176592e3eb8480e | aulyman/BME205 | /wordcount | 4,967 | 4.21875 | 4 | #!/usr/bin/env python2.7
"""
Audrey Lyman
BME205 Project 1: Scaffolding
Description:
Program takes in standard text file and prints out the number of times
each word in the file was repeated (counted) as a 2-column standard
text file, in an order determined in the command line arguments.
INPUTS: order (--... |
0f399c68c4b2f7e2c892c33f24d8590e36ca3f5f | Szubie/Misc | /Birbeck practice/Birkbeck booleans.py | 591 | 3.578125 | 4 | x=5
y=20
s="Birkbeck"
s2=""
x==5 and y==10
#False, "and" requires both to be True.
x<0 or y>15
#True, "or" requires only one has to be True (y is True)
y%x==0 and len(s)==8
#s.length()==8 (groovy syntax)
#True, both are True.
for n in range(1,3):
s2+=s[n]
#s.substring(1,3) == "Bir"
s2=="Bir" or x/y>0
#Fal... |
f77cf5544bb7f755622b225e47ef082aef7dba3e | lonelyarcher/leetcode.python3 | /stack_tree_iterative_traversal.py | 2,252 | 3.84375 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def inorder(self, root):
# from root, go left, put root into stack
# when left to the end, no root then pop stack
"""
:type root: TreeN... |
fea948a4c3cf8e92c832a13cba6bf1980c0133d5 | evgeniy1408/git_exercise | /Лекция 6 дз нормал.py | 2,856 | 4.46875 | 4 | # Задача-1:
# Следующая программа написана верно, однако содержит места потенциальных ошибок.
# используя конструкцию try добавьте в код обработку соответствующих исключений.
# Пример.
# Исходная программа:
def avg(a, b):
"""Вернуть среднее геометрическое чисел 'a' и 'b'.
Параметры:
- a, b (in... |
7903b9781e890bc51d8a6624ee08a2bb9fb0ea4f | tjclark3/python_diner | /diner.py | 1,798 | 4.3125 | 4 | mainMenu = ['3 Finger', 'Box Combo', 'Caniac Combo'];
sideMenu = ['Fries', 'Texas Toast', 'Cole Slaw'];
total = 0;
user = input('We have 3 options: 3 Finger, Box Combo, and Caniac Combo. WHich would you like to order?');
if user == '3 Finger':
print('Not very hungry? Well which sides would you like with that?')
... |
e58bdf6e4ac4579c0801d38f85e054a670411c14 | clanec15/simple-hash-checker | /Hash_comparator.py | 345 | 3.890625 | 4 | import os
print("Enter your file hash")
a=input()
print("The file hash you entered is",a,)
print("Enter the original hash")
b=input()
print("The hash you entered is",b,)
if a == b:
print("Hash correct, the file isnt corrupted")
else:
print("Hash mismatch, your file can be corrupted or it was tampere... |
6f79fdae47f64c52bfb1afb280af602b94e4a0ac | bfaure/ctci | /ch2/linked_list.py | 1,096 | 3.875 | 4 |
class node:
def __init__(self,data=None):
self.data=data
self.next=None
class linked_list:
def __init__(self):
self.head=node()
def append(self,data):
new_node=node(data)
cur=self.head
while cur.next!=None:
cur=cur.next
cur.next=new_node
def length(self):
cur=self.head
total=0
while cur.n... |
c82eed6dee0cfdf053b7fe56af1b404adc808d40 | ridmic/pytest | /roll.py | 498 | 3.703125 | 4 | from dice import Dice
class Roll():
def __init__(self, dice, rolls=5):
self.dice = dice
self.rolls = int(rolls)
self.rolled = {}
for i in range(0, self.rolls):
self.rolled['dice_' + str(i + 1)] = {'roll': 0, 'held': False}
def roll_all(self):
for i in range... |
6f25a0745e23aad448df91377c27a047bb04d052 | ppodds/NCUCalculusHW | /cal2-03.py | 304 | 3.765625 | 4 | import sympy
x , y = sympy.symbols("x, y")
f = x * (y ** 2) * sympy.ln(x ** 2)
for v1 in [x, y]:
for v2 in [x, y]:
for v3 in [x ,y]:
if v1 + v2 + v3 == 2 * x + y:
sympy.pprint(sympy.Derivative(f, v1, v2, v3))
print('=', sympy.diff(f, v1, v2, v3)) |
f3929205576833ff8da409e518a4808a6561f5d1 | Araym51/Ostroumov_Egor_DZ | /Lesson_5/Task_5_1.py | 793 | 4 | 4 |
"""Задание 1. Функция-генератор rand_nums
Написать функцию-генератор rand_nums, генерирующую N случайных целых чисел
в диапазоне 1 до 100 (включительно). Количество чисел N, которое выдаст генератор
передается в функцию через параметр:
rand15 = rand_nums(15)
next(rand15) # 1-й вызов
11
next(rand15) # 2-й вызов
38
...... |
4fca567284bad70517a6479f69aa427322a88729 | TonyDoen/python_code_review | /fund/TestClosureVars.py | 796 | 3.640625 | 4 | # -*- coding:utf8 -*-
w = x = y = z = 1
def printwxyz():
output = '<int %r id=%#0x val=%d>'
print output % ('w', id(w), w)
print output % ('x', id(x), x)
print output % ('y', id(y), y)
print output % ('z', id(z), z)
def f1():
x = y = z = 2
def f2():
y = z = 3
print '\nin f2:'
printwxyz()
f2()
print '\... |
6e441230e0d178acbe73e0f188995edeb07b3642 | LouiseCerqueira/python3-exercicios-cursoemvideo | /python3_exercicios_feitos/Desafio074.py | 505 | 4.0625 | 4 | '''Crie um programa que vai gerar cinco números aleatórios e colocar em uma tupla. Depois disso mostre a
listagem de números gerados e também indique o menor e o maior valor que estão na tupla'''
from random import randint
cont = 0
for c in range(0,5):
tupla = randint(0,10)
print(tupla, end=' ')
cont+=1
... |
ffd2e178f00dcf81ae7df3576c3f13facbe2b5e2 | amlinger/AdventOfCode | /2016/python/day21/part1.py | 5,383 | 3.6875 | 4 | """
Advent of code 2016 - Day 21, Part 1
Scrambled Letters and Hash
===
The computer system you're breaking into uses a weird scrambling function to
store its passwords. It shouldn't be much trouble to create your own scrambled
password so you can add it to the system; you just have to implement the
scrambler.
The s... |
15fc66efd839d69ffb4617b97b69124d179c0d6d | Northerneye/Backpropogation-Example | /backpropogationExample.py | 1,445 | 4.125 | 4 | import numpy as np
training_rate = .1 #How fast or slow we want this to train
input_node = .5 #Value of the input
weight1 = .5 #Value of the weight from the first layer
hidden_node = 0 #the hidden node is initialized to zero
weight2 = .5 #Value of the weight from the second layer
output_node = 0 #Output is initially se... |
c13fe60f8e550e81a21854850d1c664025328798 | eboladev/Study | /ProgrammingLanguage/Python/HelloWorld/Fac_c.py | 215 | 3.53125 | 4 | #! /usr/bin/env python
def fac(n) :
#return n ? n*fac(n-1) : 1
if n : return n*fac(n-1)
else : return 1
def main() :
for i in xrange(10) :
print i, fac(i)
if __name__ == "__main__" : main()
|
277d4d2680340157164f535015ddfc533f56419b | tomesz87/Hangman | /task/hangman/hangman.py | 1,051 | 3.78125 | 4 | # Write your code here
import random
import sys
print("H A N G M A N")
choice = ''
while choice.lower() not in ['play', 'exit']:
choice = input('Type "play" to play the game, "exit" to quit:')
if choice.lower() == 'exit':
end(0)
list_available = ['python', 'java', 'kotlin', 'javascript']
to_guess = random.... |
9bf610393f5609b3994e5c422a1b258bba532b0a | kachiO/KagNet | /util/find_related_triples.py | 4,986 | 3.5 | 4 | import spacy
import sys
PATH_relation2id = "relation2id.txt"
PATH_entity2id = "entity2id.txt"
PATH_triple2id = "triple2id.txt"
PATH_related_triples = "related_triples.txt"
PATH_related_triples_str = "related_triples_str.txt"
nlp = spacy.load('en')
def find_related_triples(words, k=3):
"""
Given an input sen... |
37d6a900520b94365019c725474d529137239bdd | s0m35h1t/holbertonschool-interview | /0x10-rain/0-rain.py | 627 | 3.75 | 4 | #!/usr/bin/python3
"""
Rain
"""
def rain(walls):
"""calculate how much water will be
retained after rain
Args:
walls is a list of non-negative integers.
Retruns:
Integer indicating total amount of rainwater retained
Or 0.
"""
if len(walls) == 0:
return 0
wa... |
ddb550aa1c403143593be044d579b21e6cfe8abd | TheFuzzStone/hello_python_world | /chapter_8/8_16.py | 849 | 3.84375 | 4 | # 8-16. Imports: Using a program you wrote that has one function in it,
# store that function in a separate file. Import the function into
# your main program file, and call the function using each of these
# approaches:
# import module_name
# from module_name import function_name
# from module_name import function_nam... |
d3f7ad3faa8328861647b646c098f1c32b1a1f47 | halcyonjuly7/hack_highschool_oop | /pvnp/stack.py | 445 | 3.75 | 4 | class Stack:
def __init__(self):
self._stack = []
self._size = 0
def isEmpty(self):
return not self._stack
def push(self, data):
self._stack.append(data)
self._size += 1
def pop(self):
if self._size != 0:
self._size -= 1
retur... |
4bce97ac0c92c9c9c8681ea0e569b941fb6dbb09 | lauradoc/AdventOfCode | /day6.py | 830 | 3.515625 | 4 |
def count_yes_answers():
with open('day6.txt') as f:
lines = f.read().split('\n\n')
counter = 0
for line in lines:
counter += len(set(line.replace('\n', '')))
return counter
# print(count_yes_answers())
def count_yes_answers_2():
with open('day6.... |
43de2ad00ade058fbbdd2812f2ae14c1c79f1fb2 | swapnil-092/smallPrograms | /ds algo.py | 1,406 | 3.65625 | 4 | # This is an N-queen Algorithm
class solution:
def __init__(self):
self.MAX = 100 # size of array
self.A = [0]*self.MAX
def placement(self,i,j): # to check if queen can be placed
for k in range(1,i):
if (self.A[k] == j) or abs(self.A[k] - j) == abs(k - i):
... |
160b23b2754a01deeb1f816c630fb38aeda0a3a0 | aalcan/IA | /clasificador/genera.py | 2,617 | 3.5 | 4 | """
En el comentario del archivo anterior, hice varias cosas,
para poder sacar la matriz de probabilidades,
ahora hay que hacer un programa que a partir de 10 tweets genere la misma
matriz de probabilidades
sabiendo de ante mano cuales son los de stream
Sugiero esta estructura, para lo tweets
{
"Tweets" : [
{"S... |
9c695f5445161a76936e72ac336a9253d9113541 | s4git21/Two-Pointers-1 | /Problem-1.py | 1,086 | 4.15625 | 4 | """
Approach:
1) if you were to sort the first and last flag, your middle flag is automatically sorted
2) use two pointers to keep track of the sorted indices for 0 and 2
3) you'd need to have a 3rd pointer to make comparisons from left to right
4) swap elements at 3rd moving pointer with either left/right pointer if 0... |
c8fbde277eb95ed1ad6677a1da33e65ada14c837 | lilykltran/Python-Flask-App | /final/gbmodel/Model.py | 817 | 3.875 | 4 | """Base class for model. Derived models must implement abstract methods"""
class Model():
def select(self):
"""
Gets all entries from the database
:return: Tuple containing all rows of database
"""
pass
def insert(self, name, streetAddress, city, state, zipCode, hours, ... |
eac0f130f30dee41febfa0c69bd191bdab4f3147 | williamscales/selfdrivingcar | /controller.py | 1,348 | 3.640625 | 4 | # -*- coding: utf-8 -*-
#
# This file presents an interface for interacting with the Playstation
# 4 Controller in Python. Simply plug your PS4 controller into your
# computer using USB and run this script!
#
# NOTE: I assume in this script that the only joystick plugged in is
# the PS4 controller. if this is no... |
6582c75f074982eee9c83b194abb885247ecc1ed | MaxBabii/home_work_python_starter | /home-work_7(1).py | 264 | 4.4375 | 4 | #создайте список
#введите количество его элементов и сами значения,
#выведите эти значения на экранв обратном порядке
my_list = [1, 2, 3, 4, 5][::-1]
print(my_list) |
79e02f138af25205b5a751f848e8476db19b6eea | hasnatosman/boring_stuff | /number.py | 463 | 4.03125 | 4 | def phone(number):
if number == '017':
return "It is a GP number"
elif number == '018':
return "it is a Robi number"
elif number == "016":
return 'It is Airtel Number'
elif number == '019':
return "It is a BanglaLink Number"
elif number == '015':
re... |
a302423539ccfd48a98a08c6d73d73dc18595163 | poohcid/class | /e-Judge/Decreasing.py | 149 | 3.734375 | 4 | """Decreasing"""
def main():
"""function_main"""
start = int(input())
for number in range(start, -1, -1):
print(number)
main()
|
a5c6b1ed074da37aa62d543a9355ffdbb5b56df7 | onesidedsquare/snipetsAndTries | /simpleYMLReader.py | 812 | 3.6875 | 4 | import yaml
# Open the YAML file and load the data into a Python object
with open("config2.yml", "r") as f:
data = yaml.safe_load(f)
# Extract the database host and port information
dbHost = data["database"]["host"]
dbPort = data["database"]["port"]
# Extract the first table name and column names
tableName = dat... |
5dbbe8ccbbd806ae95e5b27db53243ad88294eab | ASePavlova/Lab-3 | /nums.py | 337 | 3.796875 | 4 | #Лабораторная работа 3, список
def find_missing_nums(nums):
n = len(nums)
u = []
m = False
for p in range (1,n+1):
for q in range (0,n):
if p == nums[q]:
m = True
continue
if not m:
u.append(i)
m = False
return u
|
bf42d5cf965c2c725f7a975edf04cf3dc65882f9 | markabrennan/code_challenges | /symmetric_tree.py | 2,799 | 3.84375 | 4 | """
Leet Code Problem # 101: "Symmetric Tree"
"""
# We need a tree node class
class Node:
def __init__(self, val=None, left=None, right=None):
self.value = val
self.left = left
self.right = right
"""
Helper function to traverse tree - pre-order
"""
def preorder(node, vals):
if node is... |
728399a08b8ab8cdc95b0dfc1a9d1ffe38bc94df | yonatanPony/python | /Rock paper scissors MP.py | 3,993 | 4.15625 | 4 | def get_names():
name = input('Whats your name? \n')
print("Hello", name, "!")
return name
#getting player choice and return the usable value
def player_choice():
player = input('Please enter your choice: ')
if not (player == '1' or player == '2' or player == '3'):
player1error = 1... |
dd98510ac233c8881390cd08f72e8e7a8e9e7ccb | SpartArs/DSAlgorithms | /python/plotting.py | 651 | 4.21875 | 4 | '''
Created on May 15, 2015
@author: tekrei
Plotting examples from Introduction to Computation and Programming Using Python
'''
from matplotlib import pylab
if __name__ == '__main__':
principal = 10000 # initial investment
interest_rate = 0.05
years = 20
values = []
for i in range(years + 1):
... |
8984b55bed2fd0b65c1c7a5446693e4811be108c | Arinze95/CS303E | /Documents/CS303E/CS303E-master/listproducts.py | 587 | 3.90625 | 4 | def listproducts(list1, list2):
productsum = 0
for i in range(len(list1)):
productsum += (list1[i] * list2[i])
return(productsum)
def main():
a = (input("Enter a list of numbers separated by spaces: "))
b = (input("Enter another list of numbers separated by spaces: "))
while len(a) != len(b):
a = (input("En... |
f4e430a83763eb9d9cc39098894c5195fa325cb9 | Chanizo/fffc | /file_converter/metadata_reader.py | 1,873 | 3.546875 | 4 | # -*- coding: utf-8 -*-
import os
from file_converter.column_types import ACCEPTED_TYPES
class MetadataReader:
"""
Class with static methods to read and parse metadata from a metadata file
"""
@staticmethod
def read_metadata_file(metadata_file):
"""
Read metadata file and parse i... |
b69490cbde85647c463372f0333c0640dfb3c17d | Mutan0105/python_exercises2 | /name_list.py | 925 | 3.90625 | 4 | #!/usr/bin/python
# -*- encoding: utf-8 -*-
i = 1
name_list = []
def input_check(name):
global i
wrong = []
if ',' not in name:
print '输入不规范,进行自动纠正'
print '这是你第%d次输入错误' % i
i += 1
for n in name.split(' '):
wrong.append(n)
name = ",".join(wrong)
re... |
eb4252aae34e5aa91a637820f2926b7597f83581 | Dickens254/variables_assingnment | /dickvariable.py | 676 | 4.0625 | 4 | # a variable acts as a container that stores data values
#declaring variables
x = 5 #x is the variable
y = 10 # y is another variable
print(x + y) #displays the sum off variable x and variable y
# output will be 15
# storing string data type in variables
t = "john "
z = "peters"
print(t + z)
# output will b... |
4391241cbac2700f9a202453be20782495f0b806 | ivo-bass/SoftUni-Solutions | /programming_fundamentals/list_basics_exercise/8. Seize the Fire.py | 1,155 | 4.21875 | 4 | """Create a program that calculates the total_water that is
needed to put out a "fire cell", based on the given information
about its "fire level" and how much it gets affected by total_water."""
fires_input = input()
total_water = int(input())
fires_list = list(fires_input.split("#"))
total_effort = 0
total_fire = 0... |
5da55d5d466319579ab5424b121f9ea9f358a151 | kuba777/sql | /cars1.py | 594 | 4.15625 | 4 | # -*- coding: utf-8 -*-
#Using the “inventory” table from the previous homework assignment, add ( INSERT )
#5 records (rows of data) to the table. Make sure 3 of the vehicles are Fords while the
#other 2 are Hondas. Use any model and quantity for each.
import sqlite3
with sqlite3.connect("cars.db") as connection:
... |
4a7c8263aaefbb7c29cf98c696930b445dd77b75 | dale-nelson/ift101 | /Lab2P1-a.py | 788 | 3.921875 | 4 | import time
<<<<<<< HEAD
dur = time.time()
=======
>>>>>>> ca52a16fe01ae2a839c77a24d96f2c8c13c511f3
print("This program will take 2 numbers and add them together. Decimals can be used.")
time.sleep(1.5)
def check_if_valid():
while True:
try:
var = float(input("Please enter a number: "))
... |
d455d7abd4b1b1254a80b3c6b66cfed1ac34f858 | daniel-reich/ubiquitous-fiesta | /bdsWZ29zJfJ2Roymv_10.py | 131 | 3.5625 | 4 |
import re
def swap_two(string):
return re.sub(r"([\s\S][\s\S])([\s\S][\s\S])" , lambda m : m.group(2)+m.group(1), string);
|
ea4af0e84b4fa4a3382e329c54e62a24e9af184e | AlexanderKazakov/cpp-seminars | /python/set_and_dictionaries.py | 384 | 3.8125 | 4 | #!/usr/bin/env python3
a = set('abracadabra')
print(a)
b = set('alacazam')
print(b)
print(a - b)
print(a | b)
print(a & b)
print(a ^ b)
d = dict([('a', 3), ('b', 7), ('f', 9)])
for key, val in d.items():
print(key + ' ==> ' + str(val))
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for index, key in enum... |
5f2ebc15606e8a6253b396f108ae61b5d2581375 | webclinic017/alpaca-SDK | /market.py | 1,586 | 3.9375 | 4 | import datetime
import pause
def pause_program(pause_until):
print("The program is paused until {}".format(pause_until))
pause.until(pause_until)
def is_open():
# this function will return true if the market is currently open else false. If false it will wait until next opening time
remaining_time = ... |
994a271ee920b137321fad31c40544744f1e488d | Sourav4yogi/Python | /guessgame.py | 587 | 3.984375 | 4 | import random
print('\tGuess the Number from 1 to 10 in 3 attempts')
num=random.randint(1,10)
def guess():
global g
g=int(input('Guess the number\n'))
return g
count=[]
g=None
guess()
while True:
if g==num and len(count)<=3:
print('You win\n')
break
elif g>num:
count.append(g)
... |
315a58b10a276fe754e2f016e4d08a2c33152d0b | Toonggg/Day-3-sol-repo | /numpy_solutions.py | 2,432 | 3.84375 | 4 | import numpy as np
def id(x):
# This function returns the memory block address of an array.
return x.__array_interface__['data'][0]
# 1. Numpy exercises
# a)
null_vector = np.zeros(shape = 10)
null_vector[4] = 1
print(null_vector)
print()
# b)
v_1 = 10
v_2 = 49
ranged_vector = np.arange(start = v_1, stop = v_2 ... |
d880c13ae41b1f34a80e7d9e5a0244c6e15f3d3a | anamariagds/listas_remoto | /semana7/fibonacci.py | 363 | 4.03125 | 4 | def fibonacci():
n = int(input("Quantos números na sequencia? "))
n1, n2 = 0, 1
cont = 0
while cont <n:
print(f'{n1}, ',end='')
s = n1 + n2
n1 = n2
n2 = s
cont += 1
if cont == (n-1):
print(f'{n1}')
break
def main():
fibona... |
9d12ccaaef9b0fcc4e638f28bde7b05af4ea7fdc | abi-ingram/Python-course1 | /Session5/practices.py | 502 | 3.953125 | 4 | pokemon = ["pikachu", "squirtle", "charizard", "snorlax"]
print(pokemon[1])
pokemon[1] = "bulbasaur"
print(pokemon)
pokemon.insert(0, "squirtle")
print(pokemon)
pokemon.append("eevee")
print(pokemon)
#pokemon = pokemon + ["Spongebob", "Squarepants"]
#print(pokemon)
#pokemon = pokemon * 2
#print(pokemon)
#pokemon.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.